@jdcpuwiz/zoo-kit 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -229,6 +229,7 @@ export const POST = devices.revokeHandler();
229
229
  |---|---|
230
230
  | valid key | 200, cached 60 s (`status: "fresh"` then `"cached"`) |
231
231
  | revoke push arrived | the very next call is 401, even inside the 60 s (and an answer in flight when it landed is not re-cached) |
232
+ | app switched back on after a revoke push (1.5.1) | admitted on the next call: a 200 to a question asked AFTER the push clears the tombstone (the grant id is stable across off/on) |
232
233
  | zoo-people says `unknown-or-revoked` | 401, cache + last-known-good dropped |
233
234
  | zoo-people down, key answered valid in the last 7 days | 200 (`status: "stale"`) |
234
235
  | zoo-people down, key unknown | refused — **503 by default**, never 401 (zoo-health-ios forgets its key on a 401). `outageStatus: 401` opts out. |
@@ -374,3 +375,6 @@ npm pack --dry-run # dist/, README.md, LICENSE, package.json only
374
375
  npm run test:tarball # pack, install in a temp dir: require, import, tsc
375
376
  node scripts/tarball-test.mjs @jdcpuwiz/zoo-kit@X.Y.Z # the same three checks on a published version
376
377
  ```
378
+
379
+ ### devices.swap() (1.6.0, C2016)
380
+ `devices.swap(legacyKey)` trades a live legacy per-app key (hs_, zq_, …) for the device's shared `zd_` key on the SAME physical device (zoo-people ≥0.27, `POST /api/v1/devices/swap`). One-shot to the primary only. Returns `{ok:true, key, physicalDeviceId, deviceName, deviceId, granted, appRole, rotated, person}` or `{ok:false, status, error}` (401 = the legacy key, its device or person is not live). Hand `key` to the phone once; the legacy key keeps working. Python: `create_devices().swap_key(legacy_key)` (py 1.3.0).
@@ -4,6 +4,7 @@ export declare const DEVICES_PATHS: {
4
4
  readonly redeem: "/api/v1/devices/redeem";
5
5
  readonly resolve: "/api/v1/devices/resolve";
6
6
  readonly selfRevoke: "/api/v1/devices/self-revoke";
7
+ readonly swap: "/api/v1/devices/swap";
7
8
  };
8
9
  /** The conventional path an app mounts revokeHandler() on. */
9
10
  export declare const DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
@@ -88,6 +89,26 @@ export type RedeemResult = {
88
89
  status: number;
89
90
  error: string;
90
91
  };
92
+ /** devices.swap(): a live legacy per-app key traded for the device's shared `zd_` key (C2016). */
93
+ export type SwapResult = {
94
+ ok: true;
95
+ /** The raw `zd_` key — hand it to the phone ONCE, never log or store it. */
96
+ key: string;
97
+ keyPrefix: string;
98
+ physicalDeviceId: string;
99
+ deviceName: string;
100
+ /** This app's grant id on the device (null when this app is not switched on there). */
101
+ deviceId: string | null;
102
+ granted: boolean;
103
+ appRole: string | null;
104
+ /** How many older shared keys this swap retired (one live `zd_` per device). */
105
+ rotated: number;
106
+ person: DevicePerson;
107
+ } | {
108
+ ok: false;
109
+ status: number;
110
+ error: string;
111
+ };
91
112
  export interface DevicesOptions extends FailoverOptions {
92
113
  /** This app's slug; when set, an answer for another app's device is refused. */
93
114
  app?: string;
@@ -117,6 +138,8 @@ export interface Devices {
117
138
  ok: boolean;
118
139
  status: number;
119
140
  }>;
141
+ /** Trade a live legacy per-app key for the device's shared `zd_` key (zoo-people ≥0.27). Never throws. */
142
+ swap(legacyKey: string): Promise<SwapResult>;
120
143
  /** Drop every cached answer for this device and refuse it from now on. */
121
144
  evict(deviceId: string): boolean;
122
145
  /** The route handler for zoo-people's revoke push (mount on DEVICE_REVOKE_PATH). */
@@ -39,6 +39,7 @@ exports.DEVICES_PATHS = {
39
39
  redeem: "/api/v1/devices/redeem",
40
40
  resolve: "/api/v1/devices/resolve",
41
41
  selfRevoke: "/api/v1/devices/self-revoke",
42
+ swap: "/api/v1/devices/swap",
42
43
  };
43
44
  /** The conventional path an app mounts revokeHandler() on. */
44
45
  exports.DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
@@ -174,6 +175,7 @@ function createDevices(options = {}) {
174
175
  }
175
176
  // Primary-first failover is safe for resolve (read-only). Redeem is one-shot
176
177
  // and goes to the primary only: a redeem that timed out may have landed.
178
+ // Swap is one-shot too (it mints a key and may rotate the older one).
177
179
  const urls = path === exports.DEVICES_PATHS.resolve ? c.urls : c.urls.slice(0, 1);
178
180
  const out = await (0, http_js_1.failoverFetch)(urls, path, { method: "POST", headers: { Authorization: `Bearer ${c.key}`, "Content-Type": "application/json" }, body: JSON.stringify(body) }, failover);
179
181
  if (out.kind === "failed")
@@ -187,6 +189,7 @@ function createDevices(options = {}) {
187
189
  }
188
190
  return refuse(o.outageStatus, `zoo-people unavailable (${why}) and key not cached`);
189
191
  };
192
+ const askedAt = now();
190
193
  const res = await post(exports.DEVICES_PATHS.resolve, { key });
191
194
  if (res.kind === "failed")
192
195
  return outage(res.error);
@@ -196,8 +199,17 @@ function createDevices(options = {}) {
196
199
  if (!identity)
197
200
  return outage("malformed answer");
198
201
  if (revoked(identity.device.id)) {
199
- cache.delete(h);
200
- return refuse(401, "device revoked");
202
+ // The tombstone exists to stop an answer that was IN FLIGHT when the
203
+ // revoke push landed from re-caching. A 200 to a question asked AFTER
204
+ // the push is zoo-people's current word — the app was switched back on
205
+ // (BP#149 P3: the grant id is stable, so without this a re-granted app
206
+ // answered 401 for 10 minutes and a phone could forget its key).
207
+ const t = tombstones.get(identity.device.id) ?? 0;
208
+ if (t >= askedAt) {
209
+ cache.delete(h);
210
+ return refuse(401, "device revoked");
211
+ }
212
+ tombstones.delete(identity.device.id);
201
213
  }
202
214
  if (options.app && identity.app !== options.app) {
203
215
  cache.delete(h);
@@ -305,6 +317,31 @@ function createDevices(options = {}) {
305
317
  cache.delete(sha256(key));
306
318
  return { ok: res.status === 200, status: res.status };
307
319
  },
320
+ async swap(legacyKey) {
321
+ if (!legacyKey)
322
+ return { ok: false, status: 401, error: "no key" };
323
+ const res = await post(exports.DEVICES_PATHS.swap, { key: legacyKey });
324
+ if (res.kind === "failed")
325
+ return { ok: false, status: 503, error: res.error === "unconfigured" ? "unconfigured" : "unavailable" };
326
+ const j = (res.json ?? {});
327
+ if (res.status !== 200)
328
+ return { ok: false, status: res.status, error: str(j.error) || `HTTP ${res.status}` };
329
+ const person = toPersonPart(j.person);
330
+ if (!person || !str(j.key) || !str(j.physicalDeviceId))
331
+ return { ok: false, status: 503, error: "malformed answer" };
332
+ return {
333
+ ok: true,
334
+ key: str(j.key),
335
+ keyPrefix: str(j.keyPrefix),
336
+ physicalDeviceId: str(j.physicalDeviceId),
337
+ deviceName: str(j.deviceName),
338
+ deviceId: str(j.deviceId) || null,
339
+ granted: j.granted === true,
340
+ appRole: typeof j.appRole === "string" ? j.appRole : null,
341
+ rotated: typeof j.rotated === "number" ? j.rotated : 0,
342
+ person,
343
+ };
344
+ },
308
345
  evict,
309
346
  revokeHandler() {
310
347
  const callers = options.revokeCallers ?? ["zoo-people"];
@@ -1,5 +1,5 @@
1
1
  /** The kit's own version — reported as `kit` by the health handler. */
2
- export declare const KIT_VERSION = "1.5.0";
2
+ export declare const KIT_VERSION = "1.6.0";
3
3
  /** The exact keys a v1 Person may carry; anything else is dropped. */
4
4
  export declare const PERSON_KEYS: readonly ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
5
5
  export declare const NOTIFY_PRIORITIES: readonly ["passive", "active", "time-sensitive", "critical"];
@@ -4,7 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.SLUG_PATTERN = exports.NOTIFY_PRIORITIES = exports.PERSON_KEYS = exports.KIT_VERSION = void 0;
6
6
  /** The kit's own version — reported as `kit` by the health handler. */
7
- exports.KIT_VERSION = "1.5.0";
7
+ exports.KIT_VERSION = "1.6.0";
8
8
  /** The exact keys a v1 Person may carry; anything else is dropped. */
9
9
  exports.PERSON_KEYS = ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
10
10
  exports.NOTIFY_PRIORITIES = ["passive", "active", "time-sensitive", "critical"];
@@ -13,7 +13,7 @@ export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type
13
13
  export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, type CategoryAlias, type CategoryInput, type CustomCategory, type NotifyCategory, } from "./categories.js";
14
14
  export { NOTIFY_DEFAULTS, NOTIFY_PATH, dedupeKey, notify, notifyConfigured, type NotifyAction, type NotifyDryRun, type NotifyFailed, type NotifyInput, type NotifyOptions, type NotifyPriority, type NotifyResult, type NotifySent, } from "./notify.js";
15
15
  export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, type Contact, type Contacts, type ContactsResult, type ContactsStatus, type People, type PeopleClient, type SignatureResult, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
16
- export { DEVICES_DEFAULTS, DEVICES_PATHS, DEVICE_REVOKE_PATH, createDevices, devices, type DeviceIdentity, type DeviceInfo, type DevicePerson, type DeviceStatus, type DeviceVerdict, type Devices, type DevicesOptions, type RedeemOptions, type RedeemResult, } from "./devices.js";
16
+ export { DEVICES_DEFAULTS, DEVICES_PATHS, DEVICE_REVOKE_PATH, createDevices, devices, type DeviceIdentity, type DeviceInfo, type DevicePerson, type DeviceStatus, type DeviceVerdict, type Devices, type DevicesOptions, type RedeemOptions, type RedeemResult, type SwapResult, } from "./devices.js";
17
17
  export { ZooKitAuthError, cameThroughGate, gateSecretOk, readAuthentikUsername, requireApp, requirePerson, whoami, type Anonymous, type AuthentikOptions, type DeviceAnswer, type Identity, type PersonIdentity, type SessionAnswer, type WhoamiOptions, } from "./whoami.js";
18
18
  export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, type AppIdentity, type AppVerdict, type CallAppOptions, type HeaderBag, type RequestLike, } from "./keys.js";
19
19
  export { healthBody, healthHandler, type CheckFn, type CheckResult, type HealthBody, type HealthOptions } from "./health.js";
package/dist/devices.d.ts CHANGED
@@ -4,6 +4,7 @@ export declare const DEVICES_PATHS: {
4
4
  readonly redeem: "/api/v1/devices/redeem";
5
5
  readonly resolve: "/api/v1/devices/resolve";
6
6
  readonly selfRevoke: "/api/v1/devices/self-revoke";
7
+ readonly swap: "/api/v1/devices/swap";
7
8
  };
8
9
  /** The conventional path an app mounts revokeHandler() on. */
9
10
  export declare const DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
@@ -88,6 +89,26 @@ export type RedeemResult = {
88
89
  status: number;
89
90
  error: string;
90
91
  };
92
+ /** devices.swap(): a live legacy per-app key traded for the device's shared `zd_` key (C2016). */
93
+ export type SwapResult = {
94
+ ok: true;
95
+ /** The raw `zd_` key — hand it to the phone ONCE, never log or store it. */
96
+ key: string;
97
+ keyPrefix: string;
98
+ physicalDeviceId: string;
99
+ deviceName: string;
100
+ /** This app's grant id on the device (null when this app is not switched on there). */
101
+ deviceId: string | null;
102
+ granted: boolean;
103
+ appRole: string | null;
104
+ /** How many older shared keys this swap retired (one live `zd_` per device). */
105
+ rotated: number;
106
+ person: DevicePerson;
107
+ } | {
108
+ ok: false;
109
+ status: number;
110
+ error: string;
111
+ };
91
112
  export interface DevicesOptions extends FailoverOptions {
92
113
  /** This app's slug; when set, an answer for another app's device is refused. */
93
114
  app?: string;
@@ -117,6 +138,8 @@ export interface Devices {
117
138
  ok: boolean;
118
139
  status: number;
119
140
  }>;
141
+ /** Trade a live legacy per-app key for the device's shared `zd_` key (zoo-people ≥0.27). Never throws. */
142
+ swap(legacyKey: string): Promise<SwapResult>;
120
143
  /** Drop every cached answer for this device and refuse it from now on. */
121
144
  evict(deviceId: string): boolean;
122
145
  /** The route handler for zoo-people's revoke push (mount on DEVICE_REVOKE_PATH). */
package/dist/devices.js CHANGED
@@ -35,6 +35,7 @@ export const DEVICES_PATHS = {
35
35
  redeem: "/api/v1/devices/redeem",
36
36
  resolve: "/api/v1/devices/resolve",
37
37
  selfRevoke: "/api/v1/devices/self-revoke",
38
+ swap: "/api/v1/devices/swap",
38
39
  };
39
40
  /** The conventional path an app mounts revokeHandler() on. */
40
41
  export const DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
@@ -170,6 +171,7 @@ export function createDevices(options = {}) {
170
171
  }
171
172
  // Primary-first failover is safe for resolve (read-only). Redeem is one-shot
172
173
  // and goes to the primary only: a redeem that timed out may have landed.
174
+ // Swap is one-shot too (it mints a key and may rotate the older one).
173
175
  const urls = path === DEVICES_PATHS.resolve ? c.urls : c.urls.slice(0, 1);
174
176
  const out = await failoverFetch(urls, path, { method: "POST", headers: { Authorization: `Bearer ${c.key}`, "Content-Type": "application/json" }, body: JSON.stringify(body) }, failover);
175
177
  if (out.kind === "failed")
@@ -183,6 +185,7 @@ export function createDevices(options = {}) {
183
185
  }
184
186
  return refuse(o.outageStatus, `zoo-people unavailable (${why}) and key not cached`);
185
187
  };
188
+ const askedAt = now();
186
189
  const res = await post(DEVICES_PATHS.resolve, { key });
187
190
  if (res.kind === "failed")
188
191
  return outage(res.error);
@@ -192,8 +195,17 @@ export function createDevices(options = {}) {
192
195
  if (!identity)
193
196
  return outage("malformed answer");
194
197
  if (revoked(identity.device.id)) {
195
- cache.delete(h);
196
- return refuse(401, "device revoked");
198
+ // The tombstone exists to stop an answer that was IN FLIGHT when the
199
+ // revoke push landed from re-caching. A 200 to a question asked AFTER
200
+ // the push is zoo-people's current word — the app was switched back on
201
+ // (BP#149 P3: the grant id is stable, so without this a re-granted app
202
+ // answered 401 for 10 minutes and a phone could forget its key).
203
+ const t = tombstones.get(identity.device.id) ?? 0;
204
+ if (t >= askedAt) {
205
+ cache.delete(h);
206
+ return refuse(401, "device revoked");
207
+ }
208
+ tombstones.delete(identity.device.id);
197
209
  }
198
210
  if (options.app && identity.app !== options.app) {
199
211
  cache.delete(h);
@@ -301,6 +313,31 @@ export function createDevices(options = {}) {
301
313
  cache.delete(sha256(key));
302
314
  return { ok: res.status === 200, status: res.status };
303
315
  },
316
+ async swap(legacyKey) {
317
+ if (!legacyKey)
318
+ return { ok: false, status: 401, error: "no key" };
319
+ const res = await post(DEVICES_PATHS.swap, { key: legacyKey });
320
+ if (res.kind === "failed")
321
+ return { ok: false, status: 503, error: res.error === "unconfigured" ? "unconfigured" : "unavailable" };
322
+ const j = (res.json ?? {});
323
+ if (res.status !== 200)
324
+ return { ok: false, status: res.status, error: str(j.error) || `HTTP ${res.status}` };
325
+ const person = toPersonPart(j.person);
326
+ if (!person || !str(j.key) || !str(j.physicalDeviceId))
327
+ return { ok: false, status: 503, error: "malformed answer" };
328
+ return {
329
+ ok: true,
330
+ key: str(j.key),
331
+ keyPrefix: str(j.keyPrefix),
332
+ physicalDeviceId: str(j.physicalDeviceId),
333
+ deviceName: str(j.deviceName),
334
+ deviceId: str(j.deviceId) || null,
335
+ granted: j.granted === true,
336
+ appRole: typeof j.appRole === "string" ? j.appRole : null,
337
+ rotated: typeof j.rotated === "number" ? j.rotated : 0,
338
+ person,
339
+ };
340
+ },
304
341
  evict,
305
342
  revokeHandler() {
306
343
  const callers = options.revokeCallers ?? ["zoo-people"];
@@ -1,5 +1,5 @@
1
1
  /** The kit's own version — reported as `kit` by the health handler. */
2
- export declare const KIT_VERSION = "1.5.0";
2
+ export declare const KIT_VERSION = "1.6.0";
3
3
  /** The exact keys a v1 Person may carry; anything else is dropped. */
4
4
  export declare const PERSON_KEYS: readonly ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
5
5
  export declare const NOTIFY_PRIORITIES: readonly ["passive", "active", "time-sensitive", "critical"];
@@ -1,7 +1,7 @@
1
1
  // GENERATED by packages/zoo-kit/scripts/generate.mjs from contracts/v1/*.v1.yaml + packages/zoo-kit/package.json.
2
2
  // Do not edit — change the contract and run `npm run gen`.
3
3
  /** The kit's own version — reported as `kit` by the health handler. */
4
- export const KIT_VERSION = "1.5.0";
4
+ export const KIT_VERSION = "1.6.0";
5
5
  /** The exact keys a v1 Person may carry; anything else is dropped. */
6
6
  export const PERSON_KEYS = ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
7
7
  export const NOTIFY_PRIORITIES = ["passive", "active", "time-sensitive", "critical"];
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type
13
13
  export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, type CategoryAlias, type CategoryInput, type CustomCategory, type NotifyCategory, } from "./categories.js";
14
14
  export { NOTIFY_DEFAULTS, NOTIFY_PATH, dedupeKey, notify, notifyConfigured, type NotifyAction, type NotifyDryRun, type NotifyFailed, type NotifyInput, type NotifyOptions, type NotifyPriority, type NotifyResult, type NotifySent, } from "./notify.js";
15
15
  export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, type Contact, type Contacts, type ContactsResult, type ContactsStatus, type People, type PeopleClient, type SignatureResult, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
16
- export { DEVICES_DEFAULTS, DEVICES_PATHS, DEVICE_REVOKE_PATH, createDevices, devices, type DeviceIdentity, type DeviceInfo, type DevicePerson, type DeviceStatus, type DeviceVerdict, type Devices, type DevicesOptions, type RedeemOptions, type RedeemResult, } from "./devices.js";
16
+ export { DEVICES_DEFAULTS, DEVICES_PATHS, DEVICE_REVOKE_PATH, createDevices, devices, type DeviceIdentity, type DeviceInfo, type DevicePerson, type DeviceStatus, type DeviceVerdict, type Devices, type DevicesOptions, type RedeemOptions, type RedeemResult, type SwapResult, } from "./devices.js";
17
17
  export { ZooKitAuthError, cameThroughGate, gateSecretOk, readAuthentikUsername, requireApp, requirePerson, whoami, type Anonymous, type AuthentikOptions, type DeviceAnswer, type Identity, type PersonIdentity, type SessionAnswer, type WhoamiOptions, } from "./whoami.js";
18
18
  export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, type AppIdentity, type AppVerdict, type CallAppOptions, type HeaderBag, type RequestLike, } from "./keys.js";
19
19
  export { healthBody, healthHandler, type CheckFn, type CheckResult, type HealthBody, type HealthOptions } from "./health.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jdcpuwiz/zoo-kit",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Thin, pinned server-side client for the homelab's shared services: notify, whoami, people, health, app keys.",
5
5
  "license": "MIT",
6
6
  "type": "module",