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