@camstack/addon-export-google 0.1.125 → 0.1.126

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.
@@ -2,6 +2,7 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
+ let node_crypto = require("node:crypto");
5
6
  //#region src/google-home/cap-dispatch.ts
6
7
  async function dispatchCapCall(api, call) {
7
8
  switch (call.kind) {
@@ -6059,7 +6060,7 @@ var ZodIssueCode = {
6059
6060
  var ZodFirstPartyTypeKind;
6060
6061
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6061
6062
  //#endregion
6062
- //#region ../types/dist/sleep-BaWhXZFm.mjs
6063
+ //#region ../types/dist/sleep-D1jjWAr8.mjs
6063
6064
  /**
6064
6065
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6065
6066
  * window to float samples (D455).
@@ -6207,9 +6208,16 @@ function isSecretMarker(value) {
6207
6208
  const ref = value["$secret"];
6208
6209
  return typeof ref === "string" && ref.length > 0;
6209
6210
  }
6211
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6212
+ function isSecretMarkerLike(value) {
6213
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6214
+ }
6210
6215
  function isSecretClear(value) {
6211
6216
  return isRecord$7(value) && value["$secretClear"] === true;
6212
6217
  }
6218
+ function isSecretFieldView(value) {
6219
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6220
+ }
6213
6221
  /**
6214
6222
  * The UI view of a stored secret field value: a marker becomes "set", inline
6215
6223
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6652,7 +6660,7 @@ var NOT_RUN = {
6652
6660
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6653
6661
  * because the hub (and this addon's boot) must not hang on a migration.
6654
6662
  */
6655
- async function runAddonMigrations(host, migrations, logger) {
6663
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6656
6664
  const first = migrations[0];
6657
6665
  if (first === void 0) return NOT_RUN;
6658
6666
  const owner = first.meta.owner;
@@ -6681,7 +6689,9 @@ async function runAddonMigrations(host, migrations, logger) {
6681
6689
  else if (status === "blocked") blocked.push(id);
6682
6690
  else skipped.push(id);
6683
6691
  };
6692
+ const selected = options.only === void 0 ? null : new Set(options.only);
6684
6693
  for (const step of declaration.steps) {
6694
+ if (selected !== null && !selected.has(step.id)) continue;
6685
6695
  const bound = byId.get(step.id);
6686
6696
  if (bound === void 0 || step.action === "skip") {
6687
6697
  skipped.push(step.id);
@@ -6859,11 +6869,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6859
6869
  }
6860
6870
  return out;
6861
6871
  }
6872
+ /**
6873
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6874
+ *
6875
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6876
+ * scope (global, one node, one device, one integration, one row of a business
6877
+ * collection) and the field path inside that scope — so saving the same field
6878
+ * twice updates the same ref, and the ref itself says which settings blob
6879
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6880
+ * copied onto another ref does not decrypt.
6881
+ *
6882
+ * Array items are addressed by ITEM ID, never by index
6883
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6884
+ *
6885
+ * Pure and browser-safe: no node builtins, no I/O.
6886
+ */
6887
+ /** The URI scheme of every keychain ref. */
6888
+ var SECRET_REF_SCHEME = "secret://";
6862
6889
  var GLOBAL_SCOPE = { kind: "global" };
6863
6890
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6864
6891
  function globalSecretScope() {
6865
6892
  return GLOBAL_SCOPE;
6866
6893
  }
6894
+ /**
6895
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6896
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6897
+ * addon running forked.
6898
+ */
6899
+ function normalizeSecretOwner(addonId) {
6900
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6901
+ }
6867
6902
  function encodeSegment(value) {
6868
6903
  return encodeURIComponent(value);
6869
6904
  }
@@ -6874,6 +6909,16 @@ function decodeSegment(value) {
6874
6909
  return null;
6875
6910
  }
6876
6911
  }
6912
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6913
+ function formatSecretScope(scope) {
6914
+ switch (scope.kind) {
6915
+ case "global": return "global";
6916
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6917
+ case "device": return `device/${scope.deviceId}`;
6918
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6919
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6920
+ }
6921
+ }
6877
6922
  /**
6878
6923
  * The field path of a value inside an array item, addressed by the item's id:
6879
6924
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6882,6 +6927,13 @@ function decodeSegment(value) {
6882
6927
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6883
6928
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6884
6929
  }
6930
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6931
+ function buildSecretRef(parts) {
6932
+ const owner = normalizeSecretOwner(parts.owner);
6933
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6934
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6935
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6936
+ }
6885
6937
  function parseScope(segments) {
6886
6938
  switch (segments[0]) {
6887
6939
  case "global": return {
@@ -7799,14 +7851,18 @@ var BaseAddon = class {
7799
7851
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7800
7852
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7801
7853
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7854
+ *
7855
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7856
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7857
+ * omitted applied ids "newer").
7802
7858
  */
7803
- async runMigrations(migrations) {
7859
+ async runMigrations(migrations, options) {
7804
7860
  const api = this.ctx.api.migrations;
7805
7861
  const report = await runAddonMigrations({
7806
7862
  declareOwner: (input) => api.declareOwner.mutate(input),
7807
7863
  startMigration: (input) => api.startMigration.mutate(input),
7808
7864
  finishMigration: (input) => api.finishMigration.mutate(input)
7809
- }, migrations, this.ctx.logger);
7865
+ }, migrations, this.ctx.logger, options);
7810
7866
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7811
7867
  return report;
7812
7868
  }
@@ -8809,6 +8865,13 @@ var RevConflictError = class extends RecordsError {
8809
8865
  this.name = "RevConflictError";
8810
8866
  }
8811
8867
  };
8868
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8869
+ var RecordSecretUnavailableError = class extends RecordsError {
8870
+ constructor(detail) {
8871
+ super("secret-unavailable", detail);
8872
+ this.name = "RecordSecretUnavailableError";
8873
+ }
8874
+ };
8812
8875
  var InvalidRecordError = class extends RecordsError {
8813
8876
  constructor(detail) {
8814
8877
  super("invalid-record", detail);
@@ -8839,6 +8902,8 @@ var RECORD_BATCH_MAX = 1e3;
8839
8902
  var RECORD_QUERY_MAX = 1e3;
8840
8903
  /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8841
8904
  var RECORD_SETTINGS_MAX_ROWS = 5e4;
8905
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8906
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8842
8907
  /**
8843
8908
  * Secret fields of a record, addressed the way a Zod schema declares them
8844
8909
  * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
@@ -8881,6 +8946,128 @@ function secretArrayPrefixes(path) {
8881
8946
  }
8882
8947
  return prefixes;
8883
8948
  }
8949
+ function isRecord$4(value) {
8950
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8951
+ }
8952
+ function elementId(element, idKey, declared, prefix) {
8953
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8954
+ if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
8955
+ return id;
8956
+ }
8957
+ /**
8958
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8959
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8960
+ * result is a new body, `data` is untouched.
8961
+ */
8962
+ var REMOVE_LEAF = Symbol("remove-leaf");
8963
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8964
+ if (!isRecord$4(node)) return node;
8965
+ const segment = segments[index];
8966
+ if (segment === void 0) return node;
8967
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8968
+ const child = node[segment.key];
8969
+ const keys = [...walkedKeys, segment.key];
8970
+ const last = index === segments.length - 1;
8971
+ if (segment.each) {
8972
+ if (!Array.isArray(child)) return node;
8973
+ const prefix = keys.join(".");
8974
+ const idKey = arrayKeys[prefix];
8975
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8976
+ const mapped = child.map((element) => {
8977
+ const id = elementId(element, idKey, declared, prefix);
8978
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8979
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8980
+ });
8981
+ return {
8982
+ ...node,
8983
+ [segment.key]: mapped
8984
+ };
8985
+ }
8986
+ if (segment.map) {
8987
+ if (!isRecord$4(child)) return node;
8988
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8989
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8990
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8991
+ return [mapKey, visit({
8992
+ declared,
8993
+ concrete,
8994
+ value
8995
+ })];
8996
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8997
+ return {
8998
+ ...node,
8999
+ [segment.key]: Object.fromEntries(kept)
9000
+ };
9001
+ }
9002
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9003
+ if (last) {
9004
+ const replacement = visit({
9005
+ declared,
9006
+ concrete,
9007
+ value: child
9008
+ });
9009
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9010
+ return {
9011
+ ...node,
9012
+ [segment.key]: replacement
9013
+ };
9014
+ }
9015
+ return {
9016
+ ...node,
9017
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9018
+ };
9019
+ }
9020
+ /** Replace/remove every present secret leaf; returns a NEW body. */
9021
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
9022
+ let current = data;
9023
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9024
+ return current;
9025
+ }
9026
+ /**
9027
+ * The keychain collection name a kind's secrets live under. Prefixed so a
9028
+ * record's refs never collide with the refs a legacy collection of the same name
9029
+ * already holds during an adoption.
9030
+ */
9031
+ function recordSecretCollection(kind) {
9032
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9033
+ }
9034
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9035
+ function recordSecretRef(owner, kind, rowId, concretePath) {
9036
+ return buildSecretRef({
9037
+ owner,
9038
+ scope: {
9039
+ kind: "row",
9040
+ collection: recordSecretCollection(kind),
9041
+ rowId
9042
+ },
9043
+ fieldPath: concretePath
9044
+ });
9045
+ }
9046
+ /**
9047
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9048
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9049
+ * token. The form hands it to the secret field, which reveals the value by ref
9050
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9051
+ * stored secret (the records door reads a view as KEEP).
9052
+ *
9053
+ * ONE implementation for the entries service and for every addon that serves
9054
+ * its own instances (`RecordIntegrationInstances`).
9055
+ */
9056
+ function isRecord$3(value) {
9057
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9058
+ }
9059
+ function secretViewsOf(owner, kind, id, decl, data) {
9060
+ if (decl.secretPaths.length === 0) return data;
9061
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9062
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9063
+ return {
9064
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9065
+ v: 1,
9066
+ set: true
9067
+ };
9068
+ });
9069
+ return isRecord$3(shown) ? shown : data;
9070
+ }
8884
9071
  /**
8885
9072
  * The share-view scope kinds a share-link token can carry. The hub mints
8886
9073
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9133,6 +9320,7 @@ function defineEntryKind(name, spec) {
9133
9320
  class: "config",
9134
9321
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9135
9322
  retention: { none: "an entry goes only when the operator deletes it" },
9323
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9136
9324
  ...spec.database === void 0 ? {} : { database: spec.database },
9137
9325
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9138
9326
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -13262,6 +13450,205 @@ function buildCapturingReply(envelope) {
13262
13450
  };
13263
13451
  return wrapper;
13264
13452
  }
13453
+ /**
13454
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13455
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13456
+ *
13457
+ * Every instance is one record of the addon's own kind, keyed by the
13458
+ * `integrations` registry id. The records door does the secret work: a field the
13459
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13460
+ * deleting the row deletes the secret, and one row's value is never another's.
13461
+ *
13462
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13463
+ * token or the view the form was given KEEP the stored secret;
13464
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13465
+ */
13466
+ /** The most instances one addon lists (an integrations page, not a table). */
13467
+ var INSTANCES_LIST_MAX = 1e3;
13468
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13469
+ function topLevelSecretKeys(paths) {
13470
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13471
+ }
13472
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13473
+ function secretMapKeys(paths) {
13474
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13475
+ }
13476
+ /**
13477
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13478
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13479
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13480
+ */
13481
+ function secretMapPatch(value) {
13482
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13483
+ const out = {};
13484
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13485
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13486
+ return Object.keys(out).length > 0 ? out : null;
13487
+ }
13488
+ /** Does the kind's body schema carry an `enabled` field? */
13489
+ function declaresEnabled(kind) {
13490
+ const json = toJSONSchema(kind.schema, {
13491
+ unrepresentable: "any",
13492
+ io: "input"
13493
+ });
13494
+ const properties = Reflect.get(json, "properties");
13495
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13496
+ }
13497
+ var RecordIntegrationInstances = class {
13498
+ records;
13499
+ kind;
13500
+ hooks;
13501
+ handle;
13502
+ secretKeys;
13503
+ secretMaps;
13504
+ nameField;
13505
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13506
+ registryOwnsEnabled;
13507
+ constructor(records, kind, hooks) {
13508
+ this.records = records;
13509
+ this.kind = kind;
13510
+ this.hooks = hooks;
13511
+ this.handle = records.kind(kind);
13512
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13513
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13514
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
13515
+ this.registryOwnsEnabled = hooks.description.role === "devices";
13516
+ if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
13517
+ }
13518
+ /**
13519
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
13520
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13521
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13522
+ */
13523
+ async readResolved(id) {
13524
+ try {
13525
+ const record = await this.handle.getResolved(id);
13526
+ return record === null ? null : {
13527
+ id,
13528
+ body: record.data,
13529
+ enabled: record.data.enabled !== false,
13530
+ secrets: "resolved"
13531
+ };
13532
+ } catch (err) {
13533
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
13534
+ const stored = await this.handle.get(id);
13535
+ if (stored === null) return null;
13536
+ return {
13537
+ id,
13538
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13539
+ enabled: stored.data.enabled !== false,
13540
+ secrets: "unavailable"
13541
+ };
13542
+ }
13543
+ }
13544
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13545
+ async getResolved(id) {
13546
+ return (await this.readResolved(id))?.body ?? null;
13547
+ }
13548
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13549
+ async listResolved() {
13550
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13551
+ const out = [];
13552
+ for (const record of page.records) {
13553
+ const read = await this.readResolved(record.id);
13554
+ if (read !== null) out.push(read);
13555
+ }
13556
+ return out;
13557
+ }
13558
+ viewOf(record) {
13559
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13560
+ const rawName = record.data[this.nameField];
13561
+ const kind = this.hooks.kindOf?.(record.data);
13562
+ const health = this.hooks.health?.(record.data, record.id);
13563
+ return {
13564
+ id: record.id,
13565
+ name: typeof rawName === "string" ? rawName : record.id,
13566
+ configured: this.hooks.configured(record.data),
13567
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13568
+ formValues: shown,
13569
+ ...kind !== void 0 ? { kind } : {},
13570
+ ...health?.status !== void 0 ? { status: health.status } : {},
13571
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13572
+ };
13573
+ }
13574
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13575
+ ...this.hooks.description,
13576
+ mintsId: true
13577
+ };
13578
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13579
+ listInstances = async () => {
13580
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13581
+ };
13582
+ getInstance = async ({ id }) => {
13583
+ const record = await this.handle.get(id);
13584
+ return record === null ? null : this.viewOf(record);
13585
+ };
13586
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13587
+ createInstance = async ({ id, name, kind }) => {
13588
+ const minted = id ?? this.hooks.mintId?.({
13589
+ name,
13590
+ ...kind !== void 0 ? { kind } : {}
13591
+ });
13592
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13593
+ await this.handle.put({
13594
+ id: minted,
13595
+ data: this.hooks.initialBody(name, kind)
13596
+ }, { ifRev: 0 });
13597
+ await this.hooks.onChanged?.(minted, "created");
13598
+ return { id: minted };
13599
+ };
13600
+ updateInstance = async ({ id, name, values }) => {
13601
+ const patch = {};
13602
+ for (const [key, value] of Object.entries(values)) {
13603
+ if (value === void 0) continue;
13604
+ if (this.secretMaps.has(key)) {
13605
+ const entries = secretMapPatch(value);
13606
+ if (entries !== null) patch[key] = entries;
13607
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
13608
+ else if (isSecretClear(value)) patch[key] = null;
13609
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13610
+ }
13611
+ if (name !== void 0) patch[this.nameField] = name;
13612
+ await this.handle.patch(id, patch);
13613
+ await this.hooks.onChanged?.(id, "updated");
13614
+ return { ok: true };
13615
+ };
13616
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
13617
+ setInstanceEnabled = async ({ id, enabled }) => {
13618
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13619
+ await this.handle.patch(id, { enabled });
13620
+ await this.hooks.onChanged?.(id, "enabled");
13621
+ return { ok: true };
13622
+ };
13623
+ /** The row and its keychain refs go together (the records door). */
13624
+ deleteInstance = async ({ id }) => {
13625
+ await this.handle.delete(id);
13626
+ await this.hooks.onChanged?.(id, "deleted");
13627
+ return { ok: true };
13628
+ };
13629
+ testInstance = async (input) => {
13630
+ if (this.hooks.test === void 0) return {
13631
+ success: false,
13632
+ status: "unsupported",
13633
+ error: "This integration declares no connection test"
13634
+ };
13635
+ return this.hooks.test(input);
13636
+ };
13637
+ /** The flat provider object to hand to `registerProvider`. */
13638
+ toProvider() {
13639
+ return {
13640
+ describe: this.describe,
13641
+ instanceFormSchema: this.instanceFormSchema,
13642
+ listInstances: this.listInstances,
13643
+ getInstance: this.getInstance,
13644
+ createInstance: this.createInstance,
13645
+ updateInstance: this.updateInstance,
13646
+ setInstanceEnabled: this.setInstanceEnabled,
13647
+ deleteInstance: this.deleteInstance,
13648
+ testInstance: this.testInstance
13649
+ };
13650
+ }
13651
+ };
13265
13652
  var EncodeProfileSchema = object({
13266
13653
  video: object({
13267
13654
  codec: _enum([
@@ -14307,7 +14694,13 @@ var MigrationLedgerEntrySchema = object({
14307
14694
  * joined by the engine from the catalogues it knows this boot. Absent when no
14308
14695
  * catalogue lists the id (a newer database).
14309
14696
  */
14310
- meta: MigrationMetaSchema.optional()
14697
+ meta: MigrationMetaSchema.optional(),
14698
+ /**
14699
+ * Set when this is an applied row of an addon owner whose catalogue the answering
14700
+ * process has not loaded (the owner has not declared yet): the row is applied, the
14701
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
14702
+ */
14703
+ ownerNotLoaded: boolean().optional()
14311
14704
  });
14312
14705
  /** A catalogued migration that is not applied, with where it stands. */
14313
14706
  var MigrationPendingEntrySchema = object({
@@ -50089,13 +50482,6 @@ var ExportInstanceUnknownError = class extends Error {
50089
50482
  function statusInstanceOf(input) {
50090
50483
  return "instanceId" in input ? input.instanceId : void 0;
50091
50484
  }
50092
- /**
50093
- * A single-instance provider's check: an absent id or its own passes, any other throws
50094
- * `ExportInstanceUnknownError`.
50095
- */
50096
- function assertOwnExportInstance(addon, own, instanceId) {
50097
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
50098
- }
50099
50485
  var LinkStateSchema = _enum([
50100
50486
  "unlinked",
50101
50487
  "linked",
@@ -53931,6 +54317,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
53931
54317
  }), object({ success: boolean() }), {
53932
54318
  kind: "mutation",
53933
54319
  auth: "admin"
54320
+ }), method(object({ id: string() }), object({
54321
+ rows: number().int().nonnegative(),
54322
+ secrets: number().int().nonnegative()
54323
+ }), {
54324
+ kind: "mutation",
54325
+ auth: "admin"
53934
54326
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
53935
54327
  addonId: string(),
53936
54328
  settings: record(string(), unknown())
@@ -54055,32 +54447,57 @@ var IntegrationInstancePatchSchema = object({
54055
54447
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54056
54448
  values: record(string(), unknown())
54057
54449
  });
54058
- method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }), method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }), method(object({
54059
- id: IntegrationInstanceIdSchema.optional(),
54060
- name: string().min(1),
54061
- kind: string().min(1).optional()
54062
- }), object({ id: string() }), {
54063
- kind: "mutation",
54064
- auth: "admin"
54065
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54066
- kind: "mutation",
54067
- auth: "admin"
54068
- }), method(object({
54069
- id: IntegrationInstanceIdSchema,
54070
- enabled: boolean()
54071
- }), object({ ok: literal(true) }), {
54072
- kind: "mutation",
54073
- auth: "admin"
54074
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54075
- kind: "mutation",
54076
- auth: "admin"
54077
- }), optionalMethod(object({
54078
- id: IntegrationInstanceIdSchema.nullable(),
54079
- values: record(string(), unknown())
54080
- }), TestConnectionResultSchema$1, {
54081
- kind: "mutation",
54082
- auth: "admin"
54083
- });
54450
+ var integrationInstancesCapability = {
54451
+ name: "integration-instances",
54452
+ scope: "system",
54453
+ mode: "collection",
54454
+ methods: {
54455
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54456
+ /** The form; `id: null` is the create form. */
54457
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54458
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54459
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54460
+ /**
54461
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
54462
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
54463
+ */
54464
+ createInstance: method(object({
54465
+ id: IntegrationInstanceIdSchema.optional(),
54466
+ name: string().min(1),
54467
+ kind: string().min(1).optional()
54468
+ }), object({ id: string() }), {
54469
+ kind: "mutation",
54470
+ auth: "admin"
54471
+ }),
54472
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54473
+ kind: "mutation",
54474
+ auth: "admin"
54475
+ }),
54476
+ /**
54477
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54478
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54479
+ */
54480
+ setInstanceEnabled: method(object({
54481
+ id: IntegrationInstanceIdSchema,
54482
+ enabled: boolean()
54483
+ }), object({ ok: literal(true) }), {
54484
+ kind: "mutation",
54485
+ auth: "admin"
54486
+ }),
54487
+ /** Delete the record and its keychain refs together. */
54488
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54489
+ kind: "mutation",
54490
+ auth: "admin"
54491
+ }),
54492
+ testInstance: optionalMethod(object({
54493
+ id: IntegrationInstanceIdSchema.nullable(),
54494
+ values: record(string(), unknown())
54495
+ }), TestConnectionResultSchema$1, {
54496
+ kind: "mutation",
54497
+ auth: "admin"
54498
+ })
54499
+ }
54500
+ };
54084
54501
  /**
54085
54502
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
54086
54503
  * session (server-initiated offer pattern, identical to the main
@@ -79549,6 +79966,13 @@ Object.freeze({
79549
79966
  access: "create",
79550
79967
  role: "admin"
79551
79968
  },
79969
+ "integrations.clearSettings": {
79970
+ capName: "integrations",
79971
+ capScope: "system",
79972
+ addonId: null,
79973
+ access: "delete",
79974
+ role: "admin"
79975
+ },
79552
79976
  "integrations.create": {
79553
79977
  capName: "integrations",
79554
79978
  capScope: "system",
@@ -91068,7 +91492,11 @@ var ActionSceneExports = class {
91068
91492
  * scenes. The addon is its only writer; the in-memory copy it loads at boot is what every
91069
91493
  * fulfillment intent reads.
91070
91494
  */
91071
- /** A single-instance addon keeps its records under its own addon id. */
91495
+ /**
91496
+ * The id the first Google Home instance keeps: the one every record and every pasted fulfillment
91497
+ * URL was created under. New instances get minted ids; the legacy `/fulfillment` route answers
91498
+ * for this one.
91499
+ */
91072
91500
  var GOOGLE_INSTANCE_ID = "export-google";
91073
91501
  var ExposedDeviceEntrySchema = object({
91074
91502
  deviceId: number(),
@@ -91098,6 +91526,204 @@ var EMPTY_GOOGLE_EXPORTS = {
91098
91526
  };
91099
91527
  /** The settings keys that moved into the record; the migrations name them. */
91100
91528
  var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
91529
+ var GoogleHomeBodySchema = object({
91530
+ name: string().min(1),
91531
+ enabled: boolean().optional()
91532
+ });
91533
+ var GOOGLE_HOMES_KIND_NAME = "google-homes";
91534
+ var GOOGLE_HOME_NAME = "Google Home";
91535
+ var googleHomesKind = defineEntryKind(GOOGLE_HOMES_KIND_NAME, {
91536
+ title: "Google Home instances",
91537
+ nameField: "name",
91538
+ schema: GoogleHomeBodySchema
91539
+ });
91540
+ var LinkedAccountSchema = object({
91541
+ userId: string(),
91542
+ username: string(),
91543
+ linkedAt: number()
91544
+ });
91545
+ var GoogleLinksBodySchema = object({
91546
+ name: string().min(1),
91547
+ linkedAccounts: array(LinkedAccountSchema)
91548
+ });
91549
+ var GOOGLE_LINKS_KIND_NAME = "google-links";
91550
+ var GOOGLE_LINKS_NAME = "Google links";
91551
+ var googleLinksKind = defineEntryKind(GOOGLE_LINKS_KIND_NAME, {
91552
+ title: "Google linked accounts",
91553
+ nameField: "name",
91554
+ schema: GoogleLinksBodySchema
91555
+ });
91556
+ var EMPTY_GOOGLE_LINKS = {
91557
+ name: GOOGLE_LINKS_NAME,
91558
+ linkedAccounts: []
91559
+ };
91560
+ /** The settings key that moved into the `google-links` record; the migrations name it. */
91561
+ var MOVED_LINKS_KEY = "linkedAccounts";
91562
+ //#endregion
91563
+ //#region src/google-instance.ts
91564
+ /** The most instances one hub lists. */
91565
+ var INSTANCES_MAX = 1e3;
91566
+ var GoogleInstance = class {
91567
+ id;
91568
+ home;
91569
+ exportsRow;
91570
+ linksRow;
91571
+ stores;
91572
+ logger;
91573
+ scenes;
91574
+ tail = Promise.resolve();
91575
+ constructor(id, home, exportsRow, linksRow, stores, logger, makeScenes) {
91576
+ this.id = id;
91577
+ this.home = home;
91578
+ this.exportsRow = exportsRow;
91579
+ this.linksRow = linksRow;
91580
+ this.stores = stores;
91581
+ this.logger = logger;
91582
+ this.scenes = makeScenes((entries) => this.writeExports({ actions: [...entries] }), exportsRow.actions);
91583
+ }
91584
+ get name() {
91585
+ return this.home.name;
91586
+ }
91587
+ get enabled() {
91588
+ return this.home.enabled !== false;
91589
+ }
91590
+ get devices() {
91591
+ return this.exportsRow.devices;
91592
+ }
91593
+ get linkedAccounts() {
91594
+ return this.linksRow.linkedAccounts;
91595
+ }
91596
+ applyHome(home) {
91597
+ this.home = home;
91598
+ }
91599
+ isExposed(deviceId) {
91600
+ return this.exportsRow.devices.some((entry) => entry.deviceId === deviceId);
91601
+ }
91602
+ /** One write at a time per instance: two concurrent changes must not lose each other. */
91603
+ serial(work) {
91604
+ const run = this.tail.then(work, work);
91605
+ this.tail = run.catch(() => void 0);
91606
+ return run;
91607
+ }
91608
+ /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
91609
+ writeExports(patch) {
91610
+ return this.serial(async () => {
91611
+ const next = {
91612
+ name: this.exportsRow.name,
91613
+ devices: patch.devices ?? this.exportsRow.devices,
91614
+ actions: patch.actions ?? this.exportsRow.actions
91615
+ };
91616
+ await this.stores.exports.put({
91617
+ id: this.id,
91618
+ data: next
91619
+ });
91620
+ this.exportsRow = next;
91621
+ });
91622
+ }
91623
+ /** Google's SYNC is the first thing a completed link does: the only "linked" signal there is. */
91624
+ recordLink(caller) {
91625
+ return this.serial(async () => {
91626
+ if (this.linksRow.linkedAccounts.some((a) => a.userId === caller.userId)) return;
91627
+ const next = {
91628
+ name: this.linksRow.name,
91629
+ linkedAccounts: [...this.linksRow.linkedAccounts, {
91630
+ userId: caller.userId,
91631
+ username: caller.username,
91632
+ linkedAt: Date.now()
91633
+ }]
91634
+ };
91635
+ await this.stores.links.put({
91636
+ id: this.id,
91637
+ data: next
91638
+ });
91639
+ this.linksRow = next;
91640
+ this.logger.info("export-google: recorded linked account", { meta: {
91641
+ instanceId: this.id,
91642
+ userId: caller.userId
91643
+ } });
91644
+ });
91645
+ }
91646
+ removeLink(userId) {
91647
+ return this.serial(async () => {
91648
+ const kept = this.linksRow.linkedAccounts.filter((a) => a.userId !== userId);
91649
+ if (kept.length === this.linksRow.linkedAccounts.length) return;
91650
+ const next = {
91651
+ name: this.linksRow.name,
91652
+ linkedAccounts: kept
91653
+ };
91654
+ await this.stores.links.put({
91655
+ id: this.id,
91656
+ data: next
91657
+ });
91658
+ this.linksRow = next;
91659
+ });
91660
+ }
91661
+ };
91662
+ var GoogleInstanceRegistry = class {
91663
+ stores;
91664
+ logger;
91665
+ makeScenes;
91666
+ loaded = /* @__PURE__ */ new Map();
91667
+ loading = /* @__PURE__ */ new Map();
91668
+ constructor(stores, logger, makeScenes) {
91669
+ this.stores = stores;
91670
+ this.logger = logger;
91671
+ this.makeScenes = makeScenes;
91672
+ }
91673
+ /** The instance, loaded (home, exposure AND links) on first use; null when no such instance. */
91674
+ get(id) {
91675
+ const ready = this.loaded.get(id);
91676
+ if (ready !== void 0) return Promise.resolve(ready);
91677
+ const inFlight = this.loading.get(id);
91678
+ if (inFlight !== void 0) return inFlight;
91679
+ const started = this.load(id).finally(() => {
91680
+ this.loading.delete(id);
91681
+ });
91682
+ this.loading.set(id, started);
91683
+ return started;
91684
+ }
91685
+ /** An instance already loaded; never reads. */
91686
+ peek(id) {
91687
+ return this.loaded.get(id);
91688
+ }
91689
+ async load(id) {
91690
+ const home = await this.stores.homes.get(id);
91691
+ if (home === null) return null;
91692
+ const [exported, links] = await Promise.all([this.stores.exports.get(id), this.stores.links.get(id)]);
91693
+ const instance = new GoogleInstance(id, home.data, exported?.data ?? EMPTY_GOOGLE_EXPORTS, links?.data ?? EMPTY_GOOGLE_LINKS, this.stores, this.logger, this.makeScenes);
91694
+ this.loaded.set(id, instance);
91695
+ return instance;
91696
+ }
91697
+ /** Every instance row, as stored. */
91698
+ async list() {
91699
+ return (await this.stores.homes.query({ limit: INSTANCES_MAX })).records.map((record) => ({
91700
+ id: record.id,
91701
+ body: record.data
91702
+ }));
91703
+ }
91704
+ /** The instance row changed (name, switch): a loaded instance takes it. */
91705
+ async refreshHome(id) {
91706
+ const home = await this.stores.homes.get(id);
91707
+ const instance = this.loaded.get(id);
91708
+ if (home === null) {
91709
+ this.loaded.delete(id);
91710
+ return;
91711
+ }
91712
+ if (instance === void 0) {
91713
+ await this.get(id);
91714
+ return;
91715
+ }
91716
+ instance.applyHome(home.data);
91717
+ }
91718
+ /** The instance is gone: its exposure and links rows go with it, and nothing serves it. */
91719
+ async remove(id) {
91720
+ this.loaded.delete(id);
91721
+ this.loading.delete(id);
91722
+ await this.stores.exports.delete(id);
91723
+ await this.stores.links.delete(id);
91724
+ this.logger.info("export-google: instance deleted with its exposure and links", { meta: { instanceId: id } });
91725
+ }
91726
+ };
91101
91727
  //#endregion
91102
91728
  //#region src/google-home/trait-catalog.ts
91103
91729
  /**
@@ -91782,11 +92408,17 @@ var OauthVerifiedResultSchema = object({
91782
92408
  }).nullable();
91783
92409
  function buildRoutes(deps) {
91784
92410
  return [{
92411
+ method: "POST",
92412
+ path: "/fulfillment/:instanceId",
92413
+ access: "public",
92414
+ description: "Google Home smart-home fulfillment of one instance (SYNC / QUERY / EXECUTE / DISCONNECT)",
92415
+ handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, req.params["instanceId"] ?? "")
92416
+ }, {
91785
92417
  method: "POST",
91786
92418
  path: "/fulfillment",
91787
92419
  access: "public",
91788
- description: "Google Home smart-home fulfillment (SYNC / QUERY / EXECUTE / DISCONNECT)",
91789
- handler: (req, reply) => handleFulfillmentRequest(req, reply, deps)
92420
+ description: `Legacy fulfillment URL: answers for the first instance (${GOOGLE_INSTANCE_ID})`,
92421
+ handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, GOOGLE_INSTANCE_ID)
91790
92422
  }];
91791
92423
  }
91792
92424
  /** Read `Authorization: Bearer <token>` case-insensitively. Node lower-cases
@@ -91798,7 +92430,7 @@ function readBearer(headers) {
91798
92430
  }
91799
92431
  return null;
91800
92432
  }
91801
- async function handleFulfillmentRequest(request, reply, deps) {
92433
+ async function handleFulfillmentRequest(request, reply, deps, instanceId) {
91802
92434
  const bearer = readBearer(request.headers);
91803
92435
  if (bearer === null) {
91804
92436
  deps.logger.warn("google fulfillment: rejected — no bearer token");
@@ -91817,84 +92449,19 @@ async function handleFulfillmentRequest(request, reply, deps) {
91817
92449
  username: verified.data.username,
91818
92450
  scopes: verified.data.scopes
91819
92451
  };
91820
- const result = await handleFulfillment(request.body, deps.fulfillment, caller);
92452
+ const lookup = await deps.resolveFulfillment(instanceId);
92453
+ if (!lookup.ok) {
92454
+ deps.logger.warn("google fulfillment: rejected — instance not served", { meta: {
92455
+ instanceId,
92456
+ reason: lookup.code
92457
+ } });
92458
+ reply.code(404).send({ error: lookup.code });
92459
+ return;
92460
+ }
92461
+ const result = await handleFulfillment(request.body, lookup.deps, caller);
91821
92462
  reply.code(result.status).send(result.body);
91822
92463
  }
91823
92464
  //#endregion
91824
- //#region src/oauth-integration.ts
91825
- /**
91826
- * The `export-google` OAuth client — the descriptor behind
91827
- * `/api/oauth2/authorize?integration=export-google`.
91828
- *
91829
- * Shaped exactly like `packages/addon-export-alexa/src/oauth-integration.ts`
91830
- * and `packages/addon-provider-homeassistant/src/ha-export/oauth-integration.ts`,
91831
- * which is the claim that file already makes and this one tests: a third
91832
- * integration is CONFIGURATION, not framework work
91833
- * ([D101](../../../docs/decisions/adr-0101.md)). Nothing in the kernel learned
91834
- * the word "Google".
91835
- */
91836
- /**
91837
- * Where Google lands after consent. Both origins are fixed and public and both
91838
- * are needed: `oauth-redirect` is production, `oauth-redirect-sandbox` is what
91839
- * the Actions console uses while the Action is in test mode — which is the ONLY
91840
- * mode a self-hosted hub will ever be in, since publishing an Action requires
91841
- * Google certification the operator cannot obtain for a private integration.
91842
- *
91843
- * Google appends the project id (`.../r/<project-id>`), so these stay prefixes.
91844
- */
91845
- var GOOGLE_REDIRECT_PREFIXES = ["https://oauth-redirect.googleusercontent.com/r/", "https://oauth-redirect-sandbox.googleusercontent.com/r/"];
91846
- /**
91847
- * What a linked Google Home NEEDS — the single meaning `requestedScopes`
91848
- * carries everywhere (see `oauth-integration.cap.ts`).
91849
- *
91850
- * `category:device [view, create]`, and each half is consumed by a named check
91851
- * in `fulfillment-router.ts`: `view` gates SYNC and QUERY, `create` gates
91852
- * EXECUTE. It is a category rather than a `capability:` list because the trait
91853
- * catalog is meant to grow, and a new trait row must not force every operator
91854
- * to re-link.
91855
- *
91856
- * **No `addon:` grant, and that is measured rather than assumed.** The single
91857
- * hub-side entry point, `POST /addon/export-google/fulfillment`, is
91858
- * `access: 'public'` and authenticates the token itself via
91859
- * `oauthVerifyAccessToken`, so it never passes through the
91860
- * `access: 'authenticated'` gate that [D103](../../../docs/decisions/adr-0103.md)
91861
- * checks an `addon:` grant on. Same field, same meaning, different routes.
91862
- *
91863
- * Google's smart-home account linking is a CONFIDENTIAL client — the client id
91864
- * and secret live in the Actions console, which is why there is no
91865
- * `requiresPkce` here. Note that the hub does not verify that secret either
91866
- * ([D92](../../../docs/decisions/adr-0092.md)); the security of the link rests
91867
- * on the authorization code and the redirect-prefix allow-list above.
91868
- */
91869
- function buildGoogleOauthIntegration() {
91870
- return {
91871
- integrationId: "export-google",
91872
- displayName: "Google Home",
91873
- requestedScopes: [{
91874
- type: "category",
91875
- target: "device",
91876
- access: ["view", "create"]
91877
- }],
91878
- allowedRedirectPrefixes: [...GOOGLE_REDIRECT_PREFIXES],
91879
- /**
91880
- * No expiry, for the reason Alexa's descriptor spells out at length: a
91881
- * smart-home link is meant to last until the user unlinks it, there is no
91882
- * unattended re-link, and a 30-day refresh silently kills the integration a
91883
- * month after setup.
91884
- *
91885
- * What bounds a leaked refresh token is revocation, not time — and for THIS
91886
- * integration revocation bites on the very next call, because the one entry
91887
- * point (`/fulfillment`) calls `oauthVerifyAccessToken` before doing any
91888
- * work, and that refuses once the session carries `revokedAt`.
91889
- *
91890
- * Google also has its own severing path: `action.devices.DISCONNECT`, which
91891
- * `fulfillment-router.ts` handles by dropping the linked-account record so
91892
- * `getStatus` stops claiming the export is live.
91893
- */
91894
- refreshTokenTtlSec: "never"
91895
- };
91896
- }
91897
- //#endregion
91898
92465
  //#region src/migrations/drop-public-hub-url.ts
91899
92466
  /**
91900
92467
  * The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
@@ -92018,10 +92585,84 @@ async function planDropMovedExposure(ports) {
92018
92585
  }] };
92019
92586
  }
92020
92587
  //#endregion
92588
+ //#region src/migrations/instance-and-links.ts
92589
+ /**
92590
+ * Google becomes a multi-instance exporter (planning#422 P2). Two migrations, both `block-owner`:
92591
+ * the addon must not serve a link ledger it cannot trust, and after them nothing reads the old key.
92592
+ *
92593
+ * 1. `moveInstanceAndLinks` (procedure): the first instance is the `google-homes` row under the
92594
+ * id `export-google`, and the `linkedAccounts` setting becomes the `google-links` row under
92595
+ * the same id. An existing row is never overwritten; a row this pass just wrote is read BACK
92596
+ * and must equal what the settings carried, or the pass throws.
92597
+ * 2. `planDropMovedLinks` (plan): the key is deleted only while the record holds every user the
92598
+ * settings carried; a record that cannot be read leaves the key in place.
92599
+ */
92600
+ function linksOf(value) {
92601
+ if (!Array.isArray(value)) return [];
92602
+ return value.flatMap((entry) => {
92603
+ const parsed = LinkedAccountSchema.safeParse(entry);
92604
+ return parsed.success ? [parsed.data] : [];
92605
+ });
92606
+ }
92607
+ async function moveInstanceAndLinks(ports) {
92608
+ const stored = await ports.readStored();
92609
+ const hasLinks = MOVED_LINKS_KEY in stored;
92610
+ const linkedAccounts = linksOf(stored[MOVED_LINKS_KEY]);
92611
+ const raw = stored[MOVED_LINKS_KEY];
92612
+ const understood = Array.isArray(raw) ? raw.length : 0;
92613
+ if (understood > linkedAccounts.length) ports.warn(`Google migration: ${understood - linkedAccounts.length} linked account(s) were not understood and are left out`);
92614
+ const home = await ports.putHome({ name: GOOGLE_HOME_NAME });
92615
+ const links = hasLinks ? await ports.putLinks({
92616
+ name: GOOGLE_LINKS_NAME,
92617
+ linkedAccounts
92618
+ }) : "exists";
92619
+ if (await ports.readHome() === null) throw new Error("the Google Home instance row is not there after it was written");
92620
+ if (links === "created") {
92621
+ const held = await ports.readLinks();
92622
+ if (held === null || canonical(held.linkedAccounts) !== canonical(linkedAccounts)) throw new Error("the Google links record does not match the legacy settings; nothing was cleared");
92623
+ }
92624
+ if (home === "exists" && links === "exists") return {
92625
+ outcome: "already-done",
92626
+ summary: { moved: false }
92627
+ };
92628
+ return {
92629
+ outcome: "done",
92630
+ summary: {
92631
+ instance: home === "created",
92632
+ linked: links === "created" ? linkedAccounts.length : 0
92633
+ }
92634
+ };
92635
+ }
92636
+ async function planDropMovedLinks(ports) {
92637
+ const stored = await ports.readStored();
92638
+ if (!("linkedAccounts" in stored)) return { edits: [] };
92639
+ const refuse = (reason) => {
92640
+ ports.warn(`Google migration: the legacy linkedAccounts key is kept: ${reason}`);
92641
+ throw new Error(`the legacy Google linkedAccounts key is not deleted: ${reason}`);
92642
+ };
92643
+ const held = await ports.readLinks();
92644
+ if (held === null) return refuse("no links record exists");
92645
+ const heldUsers = new Set(held.linkedAccounts.map((a) => a.userId));
92646
+ for (const account of linksOf(stored[MOVED_LINKS_KEY])) if (!heldUsers.has(account.userId)) return refuse(`the record lacks the user ${account.userId}`);
92647
+ const id = `${GOOGLE_INSTANCE_ID}.${MOVED_LINKS_KEY}`;
92648
+ return { edits: [{
92649
+ op: "deleteKeys",
92650
+ scope: ADDON_SETTINGS_TABLE,
92651
+ keys: [id],
92652
+ precondition: preconditionOf({ [id]: {
92653
+ addonId: GOOGLE_INSTANCE_ID,
92654
+ key: MOVED_LINKS_KEY,
92655
+ value: stored[MOVED_LINKS_KEY]
92656
+ } })
92657
+ }] };
92658
+ }
92659
+ //#endregion
92021
92660
  //#region src/migrations/index.ts
92022
92661
  var DROP_PUBLIC_HUB_URL_ID = "export-google/2026-11-02-drop-public-hub-url";
92023
92662
  var EXPOSURE_TO_RECORD_ID = "export-google/2026-11-04-exposure-to-record";
92024
92663
  var DROP_MOVED_EXPOSURE_ID = "export-google/2026-11-04-drop-moved-exposure";
92664
+ var INSTANCE_AND_LINKS_ID = "export-google/2026-11-04-instance-and-links";
92665
+ var DROP_MOVED_LINKS_ID = "export-google/2026-11-04-drop-moved-links";
92025
92666
  var FIXTURE_MARK = "the linked account list the migration does not know";
92026
92667
  /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
92027
92668
  var ADDON_MIGRATIONS = [
@@ -92072,9 +92713,115 @@ var ADDON_MIGRATIONS = [
92072
92713
  fixtureMark: FIXTURE_MARK
92073
92714
  },
92074
92715
  plan: planDropMovedExposure
92716
+ },
92717
+ {
92718
+ meta: {
92719
+ id: INSTANCE_AND_LINKS_ID,
92720
+ owner: "export-google",
92721
+ level: "addon-state",
92722
+ seq: 4,
92723
+ dependsOn: [],
92724
+ store: "settings",
92725
+ scope: "cluster",
92726
+ onFailure: "block-owner",
92727
+ bodyKind: "procedure",
92728
+ description: "Create the first Google Home instance under the id export-google and move the linked accounts into its google-links record; both rows are read back before anything is deleted",
92729
+ fixtureMark: FIXTURE_MARK
92730
+ },
92731
+ procedure: moveInstanceAndLinks
92732
+ },
92733
+ {
92734
+ meta: {
92735
+ id: DROP_MOVED_LINKS_ID,
92736
+ owner: "export-google",
92737
+ level: "addon-state",
92738
+ seq: 5,
92739
+ dependsOn: [INSTANCE_AND_LINKS_ID],
92740
+ store: "settings",
92741
+ scope: "cluster",
92742
+ onFailure: "block-owner",
92743
+ bodyKind: "plan",
92744
+ description: "Delete the linkedAccounts settings key once the google-links record holds what it carried",
92745
+ fixtureMark: FIXTURE_MARK
92746
+ },
92747
+ plan: planDropMovedLinks
92075
92748
  }
92076
92749
  ];
92077
92750
  //#endregion
92751
+ //#region src/oauth-integration.ts
92752
+ /**
92753
+ * The `export-google` OAuth client — the descriptor behind
92754
+ * `/api/oauth2/authorize?integration=export-google`.
92755
+ *
92756
+ * Shaped exactly like `packages/addon-export-alexa/src/oauth-integration.ts`
92757
+ * and `packages/addon-provider-homeassistant/src/ha-export/oauth-integration.ts`,
92758
+ * which is the claim that file already makes and this one tests: a third
92759
+ * integration is CONFIGURATION, not framework work
92760
+ * ([D101](../../../docs/decisions/adr-0101.md)). Nothing in the kernel learned
92761
+ * the word "Google".
92762
+ */
92763
+ /**
92764
+ * Where Google lands after consent. Both origins are fixed and public and both
92765
+ * are needed: `oauth-redirect` is production, `oauth-redirect-sandbox` is what
92766
+ * the Actions console uses while the Action is in test mode — which is the ONLY
92767
+ * mode a self-hosted hub will ever be in, since publishing an Action requires
92768
+ * Google certification the operator cannot obtain for a private integration.
92769
+ *
92770
+ * Google appends the project id (`.../r/<project-id>`), so these stay prefixes.
92771
+ */
92772
+ var GOOGLE_REDIRECT_PREFIXES = ["https://oauth-redirect.googleusercontent.com/r/", "https://oauth-redirect-sandbox.googleusercontent.com/r/"];
92773
+ /**
92774
+ * What a linked Google Home NEEDS — the single meaning `requestedScopes`
92775
+ * carries everywhere (see `oauth-integration.cap.ts`).
92776
+ *
92777
+ * `category:device [view, create]`, and each half is consumed by a named check
92778
+ * in `fulfillment-router.ts`: `view` gates SYNC and QUERY, `create` gates
92779
+ * EXECUTE. It is a category rather than a `capability:` list because the trait
92780
+ * catalog is meant to grow, and a new trait row must not force every operator
92781
+ * to re-link.
92782
+ *
92783
+ * **No `addon:` grant, and that is measured rather than assumed.** The single
92784
+ * hub-side entry point, `POST /addon/export-google/fulfillment`, is
92785
+ * `access: 'public'` and authenticates the token itself via
92786
+ * `oauthVerifyAccessToken`, so it never passes through the
92787
+ * `access: 'authenticated'` gate that [D103](../../../docs/decisions/adr-0103.md)
92788
+ * checks an `addon:` grant on. Same field, same meaning, different routes.
92789
+ *
92790
+ * Google's smart-home account linking is a CONFIDENTIAL client — the client id
92791
+ * and secret live in the Actions console, which is why there is no
92792
+ * `requiresPkce` here. Note that the hub does not verify that secret either
92793
+ * ([D92](../../../docs/decisions/adr-0092.md)); the security of the link rests
92794
+ * on the authorization code and the redirect-prefix allow-list above.
92795
+ */
92796
+ function buildGoogleOauthIntegration() {
92797
+ return {
92798
+ integrationId: "export-google",
92799
+ displayName: "Google Home",
92800
+ requestedScopes: [{
92801
+ type: "category",
92802
+ target: "device",
92803
+ access: ["view", "create"]
92804
+ }],
92805
+ allowedRedirectPrefixes: [...GOOGLE_REDIRECT_PREFIXES],
92806
+ /**
92807
+ * No expiry, for the reason Alexa's descriptor spells out at length: a
92808
+ * smart-home link is meant to last until the user unlinks it, there is no
92809
+ * unattended re-link, and a 30-day refresh silently kills the integration a
92810
+ * month after setup.
92811
+ *
92812
+ * What bounds a leaked refresh token is revocation, not time — and for THIS
92813
+ * integration revocation bites on the very next call, because the one entry
92814
+ * point (`/fulfillment`) calls `oauthVerifyAccessToken` before doing any
92815
+ * work, and that refuses once the session carries `revokedAt`.
92816
+ *
92817
+ * Google also has its own severing path: `action.devices.DISCONNECT`, which
92818
+ * `fulfillment-router.ts` handles by dropping the linked-account record so
92819
+ * `getStatus` stops claiming the export is live.
92820
+ */
92821
+ refreshTokenTtlSec: "never"
92822
+ };
92823
+ }
92824
+ //#endregion
92078
92825
  //#region src/public-endpoint.ts
92079
92826
  /** The typed refusal when the role resolves to nothing. */
92080
92827
  var NO_PUBLIC_ENDPOINT_REASON = {
@@ -92114,6 +92861,7 @@ var buildConsoleSetupFromRole = async (input) => {
92114
92861
  }]
92115
92862
  };
92116
92863
  const origin = result.origin;
92864
+ const fulfillmentPath = input.instanceId === void 0 ? `/addon/${input.addonId}/fulfillment` : `/addon/${input.addonId}/fulfillment/${input.instanceId}`;
92117
92865
  return {
92118
92866
  note: [
92119
92867
  "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
@@ -92124,7 +92872,7 @@ var buildConsoleSetupFromRole = async (input) => {
92124
92872
  fields: [
92125
92873
  {
92126
92874
  label: "Fulfillment URL",
92127
- value: `${origin}/addon/${input.addonId}/fulfillment`
92875
+ value: `${origin}${fulfillmentPath}`
92128
92876
  },
92129
92877
  {
92130
92878
  label: "Authorization URL",
@@ -92143,7 +92891,7 @@ var buildConsoleSetupFromRole = async (input) => {
92143
92891
  };
92144
92892
  //#endregion
92145
92893
  //#region src/types.ts
92146
- var DEFAULT_SETTINGS = { linkedAccounts: [] };
92894
+ var DEFAULT_SETTINGS = {};
92147
92895
  //#endregion
92148
92896
  //#region src/export-google.addon.ts
92149
92897
  /**
@@ -92151,9 +92899,14 @@ var DEFAULT_SETTINGS = { linkedAccounts: [] };
92151
92899
  *
92152
92900
  * Architecture:
92153
92901
  *
92154
- * Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment
92902
+ * Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment/<instanceId>
92155
92903
  * (hub Fastify → addon-routes cap)
92156
92904
  *
92905
+ * The addon is MULTI-instance (planning#422): every Actions-console project is one
92906
+ * `integration-instances` row of the `google-homes` kind with its own exposure and its own
92907
+ * link ledger. The first instance keeps the id `export-google`, so the legacy
92908
+ * `/fulfillment` URL still answers for it. One OAuth client serves every instance.
92909
+ *
92157
92910
  * There is no cloud function in the middle. Google's smart-home platform calls
92158
92911
  * the fulfillment URL the operator configured, so the hub answers directly —
92159
92912
  * a shorter path than Alexa's, which needs an operator-owned Lambda because
@@ -92161,7 +92914,8 @@ var DEFAULT_SETTINGS = { linkedAccounts: [] };
92161
92914
  *
92162
92915
  * Capabilities registered:
92163
92916
  * - `device-export` — the operator picks which devices Google sees.
92164
- * - `addon-routes` — mounts `/addon/export-google/fulfillment`.
92917
+ * - `addon-routes` — mounts `/addon/export-google/fulfillment[/<instanceId>]`.
92918
+ * - `integration-instances` — the Google Home instances (role `services`).
92165
92919
  * - `oauth-integration` — declares this addon a linkable client of the
92166
92920
  * hub's core `/api/oauth2/*` server.
92167
92921
  *
@@ -92183,36 +92937,27 @@ var DEFAULT_SETTINGS = { linkedAccounts: [] };
92183
92937
  * decides, so widening scope is one row.
92184
92938
  */
92185
92939
  var ADDON_ID = "export-google";
92940
+ /** The per-device toggle key: `google:<instanceId>:<deviceId>:enabled`. */
92941
+ var DEVICE_KEY = /^google:([^:]+):(\d+):enabled$/;
92942
+ var deviceKey = (instanceId, deviceId) => `google:${instanceId}:${deviceId}:enabled`;
92186
92943
  var ExportGoogleAddon = class extends BaseAddon {
92187
92944
  gateway = null;
92188
- /**
92189
- * The `google-exports` record: what Google syncs. Loaded once at boot after the migrations;
92190
- * this addon is its only writer, so the in-memory copy is the synchronous read the fulfillment
92191
- * path needs. No settings key backs it.
92192
- */
92193
- exportsRow = EMPTY_GOOGLE_EXPORTS;
92194
- exportsHandle = null;
92195
- get exposedDevices() {
92196
- return this.exportsRow.devices;
92197
- }
92198
- /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
92199
- async writeExports(patch) {
92200
- const handle = this.exportsHandle;
92201
- if (handle === null) throw new Error("export-google: the exposure record is not open");
92202
- const next = {
92203
- name: this.exportsRow.name,
92204
- devices: patch.devices ?? this.exportsRow.devices,
92205
- actions: patch.actions ?? this.exportsRow.actions
92206
- };
92207
- await handle.put({
92208
- id: GOOGLE_INSTANCE_ID,
92209
- data: next
92210
- });
92211
- this.exportsRow = next;
92212
- }
92945
+ registry = null;
92946
+ instances = null;
92947
+ fulfillments = /* @__PURE__ */ new WeakMap();
92213
92948
  constructor() {
92214
92949
  super({ ...DEFAULT_SETTINGS });
92215
92950
  }
92951
+ requireRegistry() {
92952
+ if (this.registry === null) throw new Error("export-google: addon not initialized");
92953
+ return this.registry;
92954
+ }
92955
+ /** The instance or a typed refusal naming it: a device-export call never guesses one. */
92956
+ async requireInstance(instanceId) {
92957
+ const instance = await this.requireRegistry().get(instanceId);
92958
+ if (instance === null) throw new ExportInstanceUnknownError(ADDON_ID, instanceId);
92959
+ return instance;
92960
+ }
92216
92961
  async onInitialize() {
92217
92962
  const gateway = createApiDeviceGateway({
92218
92963
  api: this.ctx.api,
@@ -92221,9 +92966,53 @@ var ExportGoogleAddon = class extends BaseAddon {
92221
92966
  this.gateway = gateway;
92222
92967
  const records = this.ctx.records;
92223
92968
  if (records === void 0) throw new Error("export-google needs ctx.records — check execution.placement (hub-only)");
92224
- await records.declare({ "google-exports": googleExportsKind });
92225
- const exportsHandle = records.kind(googleExportsKind);
92226
- this.exportsHandle = exportsHandle;
92969
+ await records.declare({
92970
+ "google-homes": googleHomesKind,
92971
+ "google-exports": googleExportsKind,
92972
+ "google-links": googleLinksKind
92973
+ });
92974
+ const stores = {
92975
+ homes: records.kind(googleHomesKind),
92976
+ exports: records.kind(googleExportsKind),
92977
+ links: records.kind(googleLinksKind)
92978
+ };
92979
+ const registry = new GoogleInstanceRegistry(stores, this.ctx.logger, (persist, initial) => new ActionSceneExports({
92980
+ api: this.ctx.api,
92981
+ logger: this.ctx.logger,
92982
+ isAdminUser: async (userId) => {
92983
+ return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
92984
+ },
92985
+ persist
92986
+ }, initial));
92987
+ this.registry = registry;
92988
+ this.instances = new RecordIntegrationInstances(records, googleHomesKind, {
92989
+ description: {
92990
+ role: "services",
92991
+ instanceMode: "multiple",
92992
+ kind: "homes",
92993
+ canTest: false
92994
+ },
92995
+ formSchema: (id) => this.homeForm(id),
92996
+ initialBody: (name) => ({ name }),
92997
+ mintId: () => `google-home-${(0, node_crypto.randomUUID)().slice(0, 8)}`,
92998
+ health: (body, id) => {
92999
+ if (body.enabled === false) return { status: {
93000
+ state: "off",
93001
+ label: "Off"
93002
+ } };
93003
+ const linked = registry.peek(id)?.linkedAccounts.length;
93004
+ if (linked === void 0) return { status: { state: "unknown" } };
93005
+ return linked > 0 ? { status: {
93006
+ state: "ok",
93007
+ label: `${linked} linked account(s)`
93008
+ } } : { status: {
93009
+ state: "unknown",
93010
+ label: "Not linked yet"
93011
+ } };
93012
+ },
93013
+ configured: () => true,
93014
+ onChanged: (id, change) => this.onInstanceChanged(id, change)
93015
+ });
92227
93016
  await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
92228
93017
  readStored: async () => this.resolveGlobalStore(),
92229
93018
  warn: (message) => {
@@ -92233,9 +93022,9 @@ var ExportGoogleAddon = class extends BaseAddon {
92233
93022
  } });
92234
93023
  },
92235
93024
  putExports: async (body) => {
92236
- if (await exportsHandle.get("export-google") !== null) return "exists";
93025
+ if (await stores.exports.get("export-google") !== null) return "exists";
92237
93026
  try {
92238
- await exportsHandle.put({
93027
+ await stores.exports.put({
92239
93028
  id: GOOGLE_INSTANCE_ID,
92240
93029
  data: body
92241
93030
  }, { ifRev: 0 });
@@ -92245,108 +93034,55 @@ var ExportGoogleAddon = class extends BaseAddon {
92245
93034
  }
92246
93035
  return "created";
92247
93036
  },
92248
- readExports: async () => (await exportsHandle.get("export-google"))?.data ?? null
92249
- }));
92250
- this.exportsRow = (await exportsHandle.get("export-google"))?.data ?? EMPTY_GOOGLE_EXPORTS;
92251
- const actionScenes = new ActionSceneExports({
92252
- api: this.ctx.api,
92253
- logger: this.ctx.logger,
92254
- isAdminUser: async (userId) => {
92255
- return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
92256
- },
92257
- persist: (entries) => this.writeExports({ actions: [...entries] })
92258
- }, this.exportsRow.actions);
92259
- actionScenes.reconcile().catch((err) => {
92260
- this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: { error: errMsg$1(err) } });
92261
- });
92262
- const ownInstance = (instanceId) => assertOwnExportInstance("export-google", ADDON_ID, instanceId);
92263
- const deviceExportProvider = {
92264
- getStatus: async (input) => {
92265
- ownInstance(statusInstanceOf(input));
92266
- return {
92267
- linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
92268
- exposedDeviceCount: this.exposedDevices.length,
92269
- setup: await this.buildSetupBlock()
92270
- };
92271
- },
92272
- listInstances: async () => [{
92273
- instanceId: ADDON_ID,
92274
- name: "Google Home",
92275
- enabled: true,
92276
- kind: "google-home"
92277
- }],
92278
- listSupportedDeviceKinds: async ({ instanceId }) => {
92279
- ownInstance(instanceId);
92280
- return [...SUPPORTED_DEVICE_KINDS];
92281
- },
92282
- listExposedDevices: async ({ instanceId }) => {
92283
- ownInstance(instanceId);
92284
- return this.exposedDevices.map((entry) => ({ deviceId: String(entry.deviceId) }));
92285
- },
92286
- exposeDevice: async ({ instanceId, deviceId }) => {
92287
- ownInstance(instanceId);
92288
- return this.exposeDevice(deviceId);
92289
- },
92290
- unexposeDevice: async ({ instanceId, deviceId }) => {
92291
- ownInstance(instanceId);
92292
- return this.unexposeDevice(deviceId);
92293
- },
92294
- listSupportedEntityKinds: async () => ["device", "action"],
92295
- listExposedEntities: async ({ instanceId }) => {
92296
- ownInstance(instanceId);
92297
- await actionScenes.reconcile();
92298
- return [...this.exposedDevices.map((entry) => ({ entity: {
92299
- kind: "device",
92300
- deviceId: String(entry.deviceId)
92301
- } })), ...actionScenes.list()];
92302
- },
92303
- exposeEntity: async ({ instanceId, entity }) => {
92304
- ownInstance(instanceId);
92305
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
92306
- if (entity.kind === "action") return actionScenes.expose(entity.actionId);
92307
- throw new Error("export-google: a notification target cannot be exported to Google Home");
93037
+ readExports: async () => (await stores.exports.get("export-google"))?.data ?? null,
93038
+ putHome: async (body) => {
93039
+ if (await stores.homes.get("export-google") !== null) return "exists";
93040
+ try {
93041
+ await stores.homes.put({
93042
+ id: GOOGLE_INSTANCE_ID,
93043
+ data: body
93044
+ }, { ifRev: 0 });
93045
+ } catch (err) {
93046
+ if (err instanceof RevConflictError) return "exists";
93047
+ throw err;
93048
+ }
93049
+ return "created";
92308
93050
  },
92309
- unexposeEntity: async ({ instanceId, entity }) => {
92310
- ownInstance(instanceId);
92311
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
92312
- if (entity.kind === "action") return actionScenes.unexpose(entity.actionId);
92313
- throw new Error("export-google: a notification target cannot be exported to Google Home");
93051
+ putLinks: async (body) => {
93052
+ if (await stores.links.get("export-google") !== null) return "exists";
93053
+ try {
93054
+ await stores.links.put({
93055
+ id: GOOGLE_INSTANCE_ID,
93056
+ data: body
93057
+ }, { ifRev: 0 });
93058
+ } catch (err) {
93059
+ if (err instanceof RevConflictError) return "exists";
93060
+ throw err;
93061
+ }
93062
+ return "created";
92314
93063
  },
92315
- getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
92316
- getDeviceLiveContribution: async () => null,
92317
- applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
92318
- };
93064
+ readHome: async () => (await stores.homes.get("export-google"))?.data ?? null,
93065
+ readLinks: async () => (await stores.links.get("export-google"))?.data ?? null
93066
+ }));
93067
+ for (const row of await registry.list()) {
93068
+ const instance = await registry.get(row.id);
93069
+ if (instance === null) continue;
93070
+ instance.scenes.reconcile().catch((err) => {
93071
+ this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: {
93072
+ instanceId: instance.id,
93073
+ error: errMsg$1(err)
93074
+ } });
93075
+ });
93076
+ }
93077
+ const deviceExportProvider = this.buildDeviceExportProvider();
92319
93078
  const routeProvider = buildAddonRouteProvider(ADDON_ID, buildRoutes({
92320
93079
  ctx: this.ctx,
92321
93080
  logger: this.ctx.logger,
92322
- fulfillment: {
92323
- logger: this.ctx.logger,
92324
- sync: {
92325
- gateway,
92326
- logger: this.ctx.logger,
92327
- listExposed: () => this.exposedDevices.map((entry) => entry.deviceId),
92328
- actions: actionScenes
92329
- },
92330
- query: {
92331
- gateway,
92332
- logger: this.ctx.logger,
92333
- isExposed: (deviceId) => this.isExposed(deviceId),
92334
- actions: actionScenes
92335
- },
92336
- execute: {
92337
- gateway,
92338
- logger: this.ctx.logger,
92339
- isExposed: (deviceId) => this.isExposed(deviceId),
92340
- actions: actionScenes
92341
- },
92342
- recordLink: (caller) => this.recordLink(caller),
92343
- removeLink: (userId) => this.removeLink(userId)
92344
- }
93081
+ resolveFulfillment: (instanceId) => this.resolveFulfillment(instanceId)
92345
93082
  }));
92346
93083
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
92347
93084
  this.ctx.logger.info("export-google: initialized", { meta: {
92348
- exposedCount: this.exposedDevices.length,
92349
- linkedAccounts: this.config.linkedAccounts.length,
93085
+ instances: (await registry.list()).length,
92350
93086
  willReportState: false
92351
93087
  } });
92352
93088
  return [
@@ -92361,16 +93097,151 @@ var ExportGoogleAddon = class extends BaseAddon {
92361
93097
  {
92362
93098
  capability: oauthIntegrationCapability,
92363
93099
  provider: oauthIntegrationProvider
93100
+ },
93101
+ {
93102
+ capability: integrationInstancesCapability,
93103
+ provider: this.instances.toProvider()
92364
93104
  }
92365
93105
  ];
92366
93106
  }
92367
93107
  async onShutdown() {
92368
93108
  this.gateway = null;
93109
+ this.registry = null;
92369
93110
  }
92370
- isExposed(deviceId) {
92371
- return this.exposedDevices.some((entry) => entry.deviceId === deviceId);
93111
+ async onInstanceChanged(id, change) {
93112
+ const registry = this.requireRegistry();
93113
+ if (change === "deleted") await registry.remove(id);
93114
+ else if (change === "created") await registry.get(id);
93115
+ else await registry.refreshHome(id);
92372
93116
  }
92373
- async exposeDevice(deviceIdRaw) {
93117
+ homeForm(id) {
93118
+ const target = id === null ? "<instance id>" : id;
93119
+ return this.schema({ sections: [{
93120
+ id: ADDON_ID,
93121
+ title: "Connection",
93122
+ description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
93123
+ columns: 1,
93124
+ fields: [{
93125
+ type: "info",
93126
+ key: "__google-setup-banner",
93127
+ label: "Setup overview",
93128
+ variant: "info",
93129
+ content: [
93130
+ "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
93131
+ `Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel (the fulfillment URL ends in /fulfillment/${target}), and link your account from the Home app.`,
93132
+ "Each Google Home instance is one Actions-console project with its own devices and linked accounts.",
93133
+ "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
93134
+ ].join("\n")
93135
+ }]
93136
+ }] });
93137
+ }
93138
+ async resolveFulfillment(instanceId) {
93139
+ const instance = await this.requireRegistry().get(instanceId);
93140
+ if (instance === null) return {
93141
+ ok: false,
93142
+ code: "unknown_instance"
93143
+ };
93144
+ if (!instance.enabled) return {
93145
+ ok: false,
93146
+ code: "instance_disabled"
93147
+ };
93148
+ return {
93149
+ ok: true,
93150
+ deps: this.fulfillmentFor(instance)
93151
+ };
93152
+ }
93153
+ /** The fulfillment wiring of ONE instance: its exposure, its links, nobody else's. */
93154
+ fulfillmentFor(instance) {
93155
+ const cached = this.fulfillments.get(instance);
93156
+ if (cached !== void 0) return cached;
93157
+ const gateway = this.requireGateway();
93158
+ const logger = this.ctx.logger;
93159
+ const deps = {
93160
+ logger,
93161
+ sync: {
93162
+ gateway,
93163
+ logger,
93164
+ listExposed: () => instance.devices.map((entry) => entry.deviceId),
93165
+ actions: instance.scenes
93166
+ },
93167
+ query: {
93168
+ gateway,
93169
+ logger,
93170
+ isExposed: (deviceId) => instance.isExposed(deviceId),
93171
+ actions: instance.scenes
93172
+ },
93173
+ execute: {
93174
+ gateway,
93175
+ logger,
93176
+ isExposed: (deviceId) => instance.isExposed(deviceId),
93177
+ actions: instance.scenes
93178
+ },
93179
+ recordLink: (caller) => instance.recordLink(caller),
93180
+ removeLink: (userId) => instance.removeLink(userId)
93181
+ };
93182
+ this.fulfillments.set(instance, deps);
93183
+ return deps;
93184
+ }
93185
+ buildDeviceExportProvider() {
93186
+ return {
93187
+ getStatus: async (input) => {
93188
+ const requested = statusInstanceOf(input);
93189
+ const rows = await this.requireRegistry().list();
93190
+ const target = requested ?? rows[0]?.id;
93191
+ if (target === void 0) return {
93192
+ linkState: "unlinked",
93193
+ exposedDeviceCount: 0,
93194
+ setup: await this.buildSetupBlock(void 0, 0)
93195
+ };
93196
+ const instance = await this.requireInstance(target);
93197
+ return {
93198
+ linkState: instance.linkedAccounts.length > 0 ? "linked" : "unlinked",
93199
+ exposedDeviceCount: instance.devices.length,
93200
+ setup: await this.buildSetupBlock(instance.id, instance.linkedAccounts.length)
93201
+ };
93202
+ },
93203
+ listInstances: async () => (await this.requireRegistry().list()).map((row) => ({
93204
+ instanceId: row.id,
93205
+ name: row.body.name,
93206
+ enabled: row.body.enabled !== false,
93207
+ kind: "google-home"
93208
+ })),
93209
+ listSupportedDeviceKinds: async ({ instanceId }) => {
93210
+ await this.requireInstance(instanceId ?? "export-google");
93211
+ return [...SUPPORTED_DEVICE_KINDS];
93212
+ },
93213
+ listExposedDevices: async ({ instanceId }) => {
93214
+ return (await this.requireInstance(instanceId ?? "export-google")).devices.map((entry) => ({ deviceId: String(entry.deviceId) }));
93215
+ },
93216
+ exposeDevice: async ({ instanceId, deviceId }) => this.exposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
93217
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
93218
+ listSupportedEntityKinds: async () => ["device", "action"],
93219
+ listExposedEntities: async ({ instanceId }) => {
93220
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93221
+ await instance.scenes.reconcile();
93222
+ return [...instance.devices.map((entry) => ({ entity: {
93223
+ kind: "device",
93224
+ deviceId: String(entry.deviceId)
93225
+ } })), ...instance.scenes.list()];
93226
+ },
93227
+ exposeEntity: async ({ instanceId, entity }) => {
93228
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93229
+ if (entity.kind === "device") return this.exposeDevice(instance, entity.deviceId);
93230
+ if (entity.kind === "action") return instance.scenes.expose(entity.actionId);
93231
+ throw new Error("export-google: a notification target cannot be exported to Google Home");
93232
+ },
93233
+ unexposeEntity: async ({ instanceId, entity }) => {
93234
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93235
+ if (entity.kind === "device") return this.unexposeDevice(instance, entity.deviceId);
93236
+ if (entity.kind === "action") return instance.scenes.unexpose(entity.actionId);
93237
+ throw new Error("export-google: a notification target cannot be exported to Google Home");
93238
+ },
93239
+ getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
93240
+ getDeviceLiveContribution: async () => null,
93241
+ applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
93242
+ };
93243
+ }
93244
+ async exposeDevice(instance, deviceIdRaw) {
92374
93245
  const deviceId = Number.parseInt(deviceIdRaw, 10);
92375
93246
  if (!Number.isFinite(deviceId)) throw new Error(`export-google: deviceId must be numeric — got "${deviceIdRaw}"`);
92376
93247
  const facts = await this.requireGateway().loadFacts(deviceId).catch((err) => {
@@ -92381,47 +93252,38 @@ var ExportGoogleAddon = class extends BaseAddon {
92381
93252
  this.ctx.logger.warn("export-google: refused to expose — no exported capability", {
92382
93253
  tags: { deviceId },
92383
93254
  meta: {
93255
+ instanceId: instance.id,
92384
93256
  deviceType: facts.deviceType,
92385
93257
  capNames: facts.capNames
92386
93258
  }
92387
93259
  });
92388
93260
  throw new Error(`export-google: device ${deviceId} has no capability this addon exports (bound: ${facts.capNames.join(", ") || "none"})`);
92389
93261
  }
92390
- const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
92391
- next.push({
93262
+ const next = instance.devices.filter((e) => e.deviceId !== deviceId);
93263
+ await instance.writeExports({ devices: [...next, {
92392
93264
  deviceId,
92393
93265
  exposedAt: Date.now()
93266
+ }] });
93267
+ this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", {
93268
+ tags: { deviceId },
93269
+ meta: { instanceId: instance.id }
92394
93270
  });
92395
- await this.writeExports({ devices: next });
92396
- this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", { tags: { deviceId } });
92397
93271
  }
92398
- async unexposeDevice(deviceIdRaw) {
93272
+ async unexposeDevice(instance, deviceIdRaw) {
92399
93273
  const deviceId = Number.parseInt(deviceIdRaw, 10);
92400
93274
  if (!Number.isFinite(deviceId)) return;
92401
- const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
92402
- if (next.length === this.exposedDevices.length) return;
92403
- await this.writeExports({ devices: next });
92404
- this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", { tags: { deviceId } });
93275
+ const next = instance.devices.filter((e) => e.deviceId !== deviceId);
93276
+ if (next.length === instance.devices.length) return;
93277
+ await instance.writeExports({ devices: next });
93278
+ this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", {
93279
+ tags: { deviceId },
93280
+ meta: { instanceId: instance.id }
93281
+ });
92405
93282
  }
92406
93283
  requireGateway() {
92407
93284
  if (this.gateway === null) throw new Error("export-google: addon not initialized");
92408
93285
  return this.gateway;
92409
93286
  }
92410
- async recordLink(caller) {
92411
- if (this.config.linkedAccounts.some((account) => account.userId === caller.userId)) return;
92412
- const next = [...this.config.linkedAccounts, {
92413
- userId: caller.userId,
92414
- username: caller.username,
92415
- linkedAt: Date.now()
92416
- }];
92417
- await this.updateGlobalSettings({ linkedAccounts: next });
92418
- this.ctx.logger.info("export-google: recorded linked account", { meta: { userId: caller.userId } });
92419
- }
92420
- async removeLink(userId) {
92421
- const next = this.config.linkedAccounts.filter((account) => account.userId !== userId);
92422
- if (next.length === this.config.linkedAccounts.length) return;
92423
- await this.updateGlobalSettings({ linkedAccounts: next });
92424
- }
92425
93287
  /**
92426
93288
  * The three URLs the operator pastes into the Actions console, plus the
92427
93289
  * linked-account count.
@@ -92431,88 +93293,85 @@ var ExportGoogleAddon = class extends BaseAddon {
92431
93293
  * value still travels in the `getStatus` response — so it would be the wrong
92432
93294
  * tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
92433
93295
  */
92434
- async buildSetupBlock() {
93296
+ async buildSetupBlock(instanceId, linkedAccounts) {
92435
93297
  return buildConsoleSetupFromRole({
92436
93298
  addonId: ADDON_ID,
92437
- linkedAccounts: this.config.linkedAccounts.length,
93299
+ ...instanceId !== void 0 ? { instanceId } : {},
93300
+ linkedAccounts,
92438
93301
  read: () => this.ctx.api.localNetwork.getAddresses.query()
92439
93302
  });
92440
93303
  }
92441
- globalSettingsSchema() {
92442
- return this.schema({ sections: [{
92443
- id: ADDON_ID,
92444
- title: "Connection",
92445
- description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
92446
- columns: 1,
92447
- fields: [{
92448
- type: "info",
92449
- key: "__google-setup-banner",
92450
- label: "Setup overview",
92451
- variant: "info",
92452
- content: [
92453
- "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
92454
- "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
92455
- "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
92456
- ].join("\n")
92457
- }]
92458
- }] });
92459
- }
92460
93304
  /**
92461
- * Per-device "Export" panel. Offered only for devices this addon can actually
92462
- * represent — a toggle on a camera would be a switch that promises something
92463
- * `buildSyncDevice` then refuses.
93305
+ * Per-device "Export" panel: one section per enabled instance. Offered only for devices this
93306
+ * addon can actually represent — a toggle on a camera would be a switch that promises
93307
+ * something `buildSyncDevice` then refuses.
92464
93308
  */
92465
93309
  async buildDeviceSettingsContribution(deviceId) {
92466
93310
  const facts = await this.requireGateway().loadFacts(deviceId).catch(() => null);
92467
93311
  if (facts === null) return null;
92468
93312
  const descriptors = traitsForCaps(facts.capNames);
92469
93313
  if (descriptors.length === 0) return null;
92470
- const enabled = this.isExposed(deviceId);
92471
- const linked = this.config.linkedAccounts.length;
92472
- const enabledKey = `google:${deviceId}:enabled`;
92473
- return {
92474
- tabs: [{
92475
- id: "export",
92476
- label: "Export",
92477
- icon: "share-2",
92478
- order: 80
92479
- }],
92480
- sections: [{
92481
- id: ADDON_ID,
92482
- title: "Google Home Export",
93314
+ const registry = this.requireRegistry();
93315
+ const rows = (await registry.list()).filter((row) => row.body.enabled !== false);
93316
+ const sections = [];
93317
+ for (const row of rows) {
93318
+ const instance = await registry.get(row.id);
93319
+ if (instance === null) continue;
93320
+ const enabled = instance.isExposed(deviceId);
93321
+ const linked = instance.linkedAccounts.length;
93322
+ const statusLabel = enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed";
93323
+ sections.push({
93324
+ id: `${ADDON_ID}:${instance.id}`,
93325
+ title: rows.length === 1 ? "Google Home Export" : `Google Home Export — ${instance.name}`,
92483
93326
  description: "Surface this device to the linked Google Home account.",
92484
93327
  tab: "export",
92485
93328
  columns: 1,
92486
- order: 30,
93329
+ order: 30 + sections.length,
92487
93330
  fields: [{
92488
93331
  type: "info",
92489
- key: "__google-status",
93332
+ key: `__google-status:${instance.id}`,
92490
93333
  label: "Status",
92491
- content: enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed",
93334
+ content: statusLabel,
92492
93335
  variant: "info"
92493
93336
  }, {
92494
93337
  type: "boolean",
92495
- key: enabledKey,
93338
+ key: deviceKey(instance.id, deviceId),
92496
93339
  label: "Expose to Google Home",
92497
93340
  description: "Google picks the change up on its next sync — say \"Hey Google, sync my devices\" to force one.",
92498
93341
  style: "switch",
92499
93342
  value: enabled,
92500
93343
  immediate: true
92501
93344
  }]
92502
- }]
93345
+ });
93346
+ }
93347
+ if (sections.length === 0) return null;
93348
+ return {
93349
+ tabs: [{
93350
+ id: "export",
93351
+ label: "Export",
93352
+ icon: "share-2",
93353
+ order: 80
93354
+ }],
93355
+ sections
92503
93356
  };
92504
93357
  }
92505
93358
  async applyDeviceSettingsPatch(deviceId, patch) {
92506
- const enabledKey = `google:${deviceId}:enabled`;
92507
- if (!(enabledKey in patch)) return { success: true };
92508
- const next = patch[enabledKey];
92509
- if (typeof next !== "boolean") {
92510
- this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", { tags: { deviceId } });
92511
- return { success: true };
93359
+ for (const [key, next] of Object.entries(patch)) {
93360
+ const match = DEVICE_KEY.exec(key);
93361
+ if (match === null || Number(match[2]) !== deviceId) continue;
93362
+ const instanceId = match[1] ?? "";
93363
+ if (typeof next !== "boolean") {
93364
+ this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", {
93365
+ tags: { deviceId },
93366
+ meta: { instanceId }
93367
+ });
93368
+ continue;
93369
+ }
93370
+ const instance = await this.requireInstance(instanceId);
93371
+ if (next === instance.isExposed(deviceId)) continue;
93372
+ if (next) await this.exposeDevice(instance, String(deviceId));
93373
+ else await this.unexposeDevice(instance, String(deviceId));
92512
93374
  }
92513
- if (next === this.isExposed(deviceId)) return { success: true };
92514
- if (next) await this.exposeDevice(String(deviceId));
92515
- else await this.unexposeDevice(String(deviceId));
92516
93375
  return { success: true };
92517
93376
  }
92518
93377
  };