@mdjhnson/homebridge-yoto 0.1.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.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @param {unknown} error
3
+ * @returns {string}
4
+ */
5
+ export function formatError (error) {
6
+ const base = error instanceof Error ? (error.stack || error.message) : String(error)
7
+ if (!error || typeof error !== 'object') return base
8
+
9
+ const err = /** @type {Record<string, unknown>} */ (error)
10
+ const extra = []
11
+ const jsonBody = 'jsonBody' in err ? err['jsonBody'] : null
12
+ const textBody = 'textBody' in err ? err['textBody'] : null
13
+
14
+ if (jsonBody) {
15
+ try {
16
+ extra.push(JSON.stringify(jsonBody))
17
+ } catch {
18
+ extra.push(String(jsonBody))
19
+ }
20
+ }
21
+
22
+ if (typeof textBody === 'string' && textBody.length) {
23
+ if (typeof jsonBody !== 'string' || textBody !== jsonBody) {
24
+ extra.push(textBody)
25
+ }
26
+ }
27
+
28
+ return extra.length ? `${base}\n${extra.join('\n')}` : base
29
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @param {unknown} value
3
+ * @param {boolean} fallback
4
+ * @returns {boolean}
5
+ */
6
+ export function getBooleanSetting (value, fallback) {
7
+ return typeof value === 'boolean' ? value : fallback
8
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @param {unknown} value
3
+ * @returns {string}
4
+ */
5
+ export function getTrimmedString (value) {
6
+ return typeof value === 'string' ? value.trim() : ''
7
+ }
@@ -0,0 +1,45 @@
1
+ /** @import { EventEmitter } from 'node:events' */
2
+
3
+ /**
4
+ * Tracks listeners registered on a shared emitter so they can be removed
5
+ * without disturbing listeners added by other owners.
6
+ *
7
+ * Several accessories share one YotoDeviceModel, so `removeAllListeners`
8
+ * would also strip the other accessories' (and the platform's) handlers.
9
+ *
10
+ * @template {Record<keyof TEvents, unknown[]>} TEvents
11
+ */
12
+ export class ListenerGroup {
13
+ /** @type {EventEmitter} */ #emitter
14
+ /** @type {Array<[string, Parameters<EventEmitter['on']>[1]]>} */ #entries = []
15
+
16
+ /**
17
+ * @param {EventEmitter<TEvents>} emitter
18
+ */
19
+ constructor (emitter) {
20
+ this.#emitter = /** @type {EventEmitter} */ (/** @type {unknown} */ (emitter))
21
+ }
22
+
23
+ /**
24
+ * @template {keyof TEvents & string} K
25
+ * @param {K} event
26
+ * @param {(...args: TEvents[K]) => void} listener
27
+ * @returns {this}
28
+ */
29
+ on (event, listener) {
30
+ this.#emitter.on(event, listener)
31
+ this.#entries.push([event, listener])
32
+ return this
33
+ }
34
+
35
+ /**
36
+ * Remove every listener registered through this group.
37
+ * @returns {void}
38
+ */
39
+ removeAll () {
40
+ for (const [event, listener] of this.#entries) {
41
+ this.#emitter.off(event, listener)
42
+ }
43
+ this.#entries = []
44
+ }
45
+ }
@@ -0,0 +1,70 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+
3
+ /**
4
+ * @typedef {Object} PkcePair
5
+ * @property {string} codeVerifier - Secret kept by the plugin until the code exchange
6
+ * @property {string} codeChallenge - S256 challenge sent in the authorize URL
7
+ */
8
+
9
+ /**
10
+ * Create a PKCE verifier/challenge pair (RFC 7636, S256).
11
+ * @returns {PkcePair}
12
+ */
13
+ export function createPkcePair () {
14
+ const codeVerifier = randomBytes(32).toString('base64url')
15
+ const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url')
16
+ return { codeVerifier, codeChallenge }
17
+ }
18
+
19
+ /**
20
+ * Random opaque value used as the OAuth `state` parameter.
21
+ * @returns {string}
22
+ */
23
+ export function createOAuthState () {
24
+ return randomBytes(16).toString('base64url')
25
+ }
26
+
27
+ /**
28
+ * @typedef {Object} AuthorizationResponse
29
+ * @property {string} [code] - Authorization code
30
+ * @property {string} [state] - State echoed back by the server
31
+ * @property {string} [error] - OAuth error code (e.g. access_denied)
32
+ * @property {string} [errorDescription] - Human-readable error
33
+ */
34
+
35
+ /**
36
+ * Parse what the user pasted after signing in: the full redirect URL
37
+ * (http://127.0.0.1:8787/callback?code=...&state=...), just its query string,
38
+ * or the bare authorization code.
39
+ * @param {string} input
40
+ * @returns {AuthorizationResponse}
41
+ */
42
+ export function parseAuthorizationResponse (input) {
43
+ const value = input.trim()
44
+ if (!value) return {}
45
+
46
+ const looksLikeQuery = value.includes('code=') || value.includes('error=')
47
+ if (!looksLikeQuery) {
48
+ return { code: value }
49
+ }
50
+
51
+ let params
52
+ try {
53
+ params = new URL(value).searchParams
54
+ } catch {
55
+ const queryStart = value.indexOf('?')
56
+ params = new URLSearchParams(queryStart >= 0 ? value.slice(queryStart + 1) : value)
57
+ }
58
+
59
+ /** @type {AuthorizationResponse} */
60
+ const result = {}
61
+ const code = params.get('code')
62
+ const state = params.get('state')
63
+ const error = params.get('error')
64
+ const errorDescription = params.get('error_description')
65
+ if (code) result.code = code
66
+ if (state) result.state = state
67
+ if (error) result.error = error
68
+ if (errorDescription) result.errorDescription = errorDescription
69
+ return result
70
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @fileoverview Utility functions for the plugin
3
+ *
4
+ * Includes code adapted from `homebridge-plugin-utils`:
5
+ * - Source: https://github.com/hjdhjd/homebridge-plugin-utils/blob/main/src/util.ts
6
+ *
7
+ * ISC License
8
+ * ===========
9
+ *
10
+ * Copyright (c) 2017-2025, HJD https://github.com/hjdhjd
11
+ *
12
+ * Permission to use, copy, modify, and/or distribute this software for any purpose
13
+ * with or without fee is hereby granted, provided that the above copyright notice
14
+ * and this permission notice appear in all copies.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
18
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
20
+ * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
21
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
22
+ * THIS SOFTWARE.
23
+ */
24
+
25
+ /**
26
+ * Sanitize an accessory/service name according to HomeKit naming conventions.
27
+ *
28
+ * Starts and ends with a letter or number. Exception: may end with a period.
29
+ * May have the following special characters: -"',.#&.
30
+ * Must not include emojis.
31
+ *
32
+ * @param {string} name - The name to sanitize
33
+ * @returns {string} The HomeKit-sanitized version of the name
34
+ */
35
+ export function sanitizeName (name) {
36
+ return name
37
+ // Replace any disallowed char (including emojis) with a space.
38
+ .replace(/[^\p{L}\p{N}\-"'.,#&\s]/gu, ' ')
39
+ // Collapse multiple spaces to one.
40
+ .replace(/\s+/g, ' ')
41
+ // Trim spaces at the beginning and end of the string.
42
+ .trim()
43
+ // Strip any leading non-letter/number.
44
+ .replace(/^[^\p{L}\p{N}]+/u, '')
45
+ // Collapse two or more trailing periods into one.
46
+ .replace(/\.{2,}$/g, '.')
47
+ // Remove any other trailing char that's not letter/number/period.
48
+ .replace(/[^\p{L}\p{N}.]$/u, '')
49
+ }
@@ -0,0 +1,22 @@
1
+ /** @import { YotoDeviceModel } from 'yoto-nodejs-client' */
2
+
3
+ import { stepsToDevicePercent } from './volume.js'
4
+
5
+ /**
6
+ * Set a player's volume in steps (0-16).
7
+ *
8
+ * yoto-nodejs-client's setVolume() rounds steps to the nearest percent, which
9
+ * the player then floors, making steps 1, 5, 9 and 13 unreachable (step 1 even
10
+ * mutes). Send a rounded-up percentage over MQTT instead.
11
+ * @param {YotoDeviceModel} deviceModel
12
+ * @param {number} steps
13
+ * @returns {Promise<void>}
14
+ */
15
+ export async function setDeviceVolume (deviceModel, steps) {
16
+ const mqttClient = deviceModel.mqttClient
17
+ if (mqttClient) {
18
+ await mqttClient.setVolume(stepsToDevicePercent(steps))
19
+ return
20
+ }
21
+ await deviceModel.setVolume(steps)
22
+ }
@@ -0,0 +1,48 @@
1
+ /** @import { YotoClient } from 'yoto-nodejs-client' */
2
+ /** @import { YotoDeviceStatusResponse } from 'yoto-nodejs-client/lib/api-endpoints/devices.js' */
3
+
4
+ /**
5
+ * Whether an API error means the token lacks a required scope.
6
+ * @param {unknown} error
7
+ * @returns {boolean}
8
+ */
9
+ export function isMissingScopeError (error) {
10
+ if (!error || typeof error !== 'object') return false
11
+ const err = /** @type {{ statusCode?: unknown, jsonBody?: { error?: { code?: unknown, message?: unknown } } }} */ (error)
12
+ const message = err.jsonBody?.error?.message
13
+ return err.statusCode === 403 &&
14
+ err.jsonBody?.error?.code === 'forbidden' &&
15
+ typeof message === 'string' &&
16
+ message.includes('scope')
17
+ }
18
+
19
+ /**
20
+ * Make the device status endpoint optional.
21
+ *
22
+ * GET /device-v2/:id/status requires a `family:device-status:view` scope that the
23
+ * Yoto developer dashboard does not currently offer. yoto-nodejs-client treats a
24
+ * failed status fetch as fatal and never opens MQTT, so the players can't be
25
+ * controlled. Status is also delivered by the config endpoint and MQTT, so on a
26
+ * missing-scope error return an empty status response instead.
27
+ *
28
+ * @param {YotoClient} client
29
+ * @param {(message: string) => void} logDebug
30
+ * @returns {void}
31
+ */
32
+ export function tolerateMissingStatusScope (client, logDebug) {
33
+ const getDeviceStatus = client.getDeviceStatus.bind(client)
34
+ let logged = false
35
+
36
+ client.getDeviceStatus = async (options) => {
37
+ try {
38
+ return await getDeviceStatus(options)
39
+ } catch (error) {
40
+ if (!isMissingScopeError(error)) throw error
41
+ if (!logged) {
42
+ logged = true
43
+ logDebug('Device status endpoint not permitted for this app; using config and MQTT status instead.')
44
+ }
45
+ return /** @type {YotoDeviceStatusResponse} */ (/** @type {unknown} */ ({ deviceId: options.deviceId }))
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @typedef {Object} TokenConfigUpdate
3
+ * @property {string} platform - Platform name to match (e.g. 'Yoto')
4
+ * @property {string} accessToken - New access token
5
+ * @property {string} refreshToken - New refresh token (may be rotated)
6
+ * @property {number} tokenExpiresAt - Expiry as a unix timestamp in milliseconds
7
+ * @property {string} [prevAccessToken] - Previous access token, used to pick the right block
8
+ * @property {string} [prevRefreshToken] - Previous refresh token, used to pick the right block
9
+ */
10
+
11
+ /**
12
+ * Apply refreshed tokens to the contents of a Homebridge config.json.
13
+ *
14
+ * Returns the updated file contents, or null when no matching platform block exists
15
+ * or the file cannot be parsed. When previous tokens are given, only the block that
16
+ * still holds them is updated: if none does, the tokens were changed elsewhere (a new
17
+ * sign-in or a logout in the UI) and must not be overwritten.
18
+ *
19
+ * @param {string} configContents - Raw config.json contents
20
+ * @param {TokenConfigUpdate} update
21
+ * @returns {string | null}
22
+ */
23
+ export function applyTokenUpdate (configContents, update) {
24
+ /** @type {unknown} */
25
+ let parsed
26
+ try {
27
+ parsed = JSON.parse(configContents)
28
+ } catch {
29
+ return null
30
+ }
31
+
32
+ if (!parsed || typeof parsed !== 'object') return null
33
+ const platforms = /** @type {Record<string, unknown>} */ (parsed)['platforms']
34
+ if (!Array.isArray(platforms)) return null
35
+
36
+ /** @type {Record<string, unknown>[]} */
37
+ const candidates = platforms.filter(
38
+ entry => entry && typeof entry === 'object' && entry.platform === update.platform
39
+ )
40
+ if (candidates.length === 0) return null
41
+
42
+ // Update the block holding the tokens being replaced. Only fall back to the single
43
+ // block when there are no previous tokens to match against.
44
+ const hasPrevTokens = Boolean(update.prevRefreshToken || update.prevAccessToken)
45
+ const block = hasPrevTokens
46
+ ? candidates.find(entry =>
47
+ (update.prevRefreshToken && entry['refreshToken'] === update.prevRefreshToken) ||
48
+ (update.prevAccessToken && entry['accessToken'] === update.prevAccessToken)
49
+ )
50
+ : (candidates.length === 1 ? candidates[0] : undefined)
51
+ if (!block) return null
52
+
53
+ block['accessToken'] = update.accessToken
54
+ block['refreshToken'] = update.refreshToken
55
+ block['tokenExpiresAt'] = update.tokenExpiresAt
56
+
57
+ // Homebridge writes config.json with 4-space indentation
58
+ return JSON.stringify(parsed, null, 4)
59
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @fileoverview Volume scaling helpers for converting between steps and percents.
3
+ */
4
+
5
+ export const DEFAULT_VOLUME_STEPS = 16
6
+
7
+ /**
8
+ * Clamp a percent value to 0-100 (rounded).
9
+ * @param {number} value
10
+ * @returns {number}
11
+ */
12
+ export function clampPercent (value) {
13
+ const normalized = Number.isFinite(value) ? value : 0
14
+ return Math.max(0, Math.min(Math.round(normalized), 100))
15
+ }
16
+
17
+ /**
18
+ * Clamp a steps value to 0-maxSteps (preserves fractional input).
19
+ * @param {number} value
20
+ * @param {number} [maxSteps=DEFAULT_VOLUME_STEPS]
21
+ * @returns {number}
22
+ */
23
+ export function clampSteps (value, maxSteps = DEFAULT_VOLUME_STEPS) {
24
+ const normalized = Number.isFinite(value) ? value : 0
25
+ return Math.max(0, Math.min(normalized, maxSteps))
26
+ }
27
+
28
+ /**
29
+ * Convert steps to percent.
30
+ * @param {number} steps
31
+ * @param {number} [maxSteps=DEFAULT_VOLUME_STEPS]
32
+ * @returns {number}
33
+ */
34
+ export function stepsToPercent (steps, maxSteps = DEFAULT_VOLUME_STEPS) {
35
+ const clampedSteps = clampSteps(steps, maxSteps)
36
+ return Math.round((clampedSteps / maxSteps) * 100)
37
+ }
38
+
39
+ /**
40
+ * Convert percent to steps.
41
+ * @param {number} percent
42
+ * @param {number} [maxSteps=DEFAULT_VOLUME_STEPS]
43
+ * @returns {number}
44
+ */
45
+ export function percentToSteps (percent, maxSteps = DEFAULT_VOLUME_STEPS) {
46
+ const normalizedPercent = clampPercent(percent)
47
+ return Math.round((normalizedPercent / 100) * maxSteps)
48
+ }
49
+
50
+ /**
51
+ * Normalize a volume value that may be in steps or percent into steps.
52
+ * @param {number} value
53
+ * @param {number} [maxSteps=DEFAULT_VOLUME_STEPS]
54
+ * @returns {number}
55
+ */
56
+ export function stepsFromVolumeValue (value, maxSteps = DEFAULT_VOLUME_STEPS) {
57
+ const normalized = Number.isFinite(value) ? value : 0
58
+
59
+ if (normalized <= maxSteps) {
60
+ return Math.round(clampSteps(normalized, maxSteps))
61
+ }
62
+
63
+ return percentToSteps(normalized, maxSteps)
64
+ }
65
+
66
+ /**
67
+ * Convert volume steps to the percentage to send to the player.
68
+ *
69
+ * Players floor the percentage back to a step, so round up: step 5 must be sent
70
+ * as 32% (5/16 = 31.25%), because 31% lands on step 4.
71
+ * @param {number} steps
72
+ * @param {number} [maxSteps]
73
+ * @returns {number}
74
+ */
75
+ export function stepsToDevicePercent (steps, maxSteps = DEFAULT_VOLUME_STEPS) {
76
+ const clampedSteps = Math.round(clampSteps(steps, maxSteps))
77
+ return Math.min(100, Math.ceil((clampedSteps * 100) / maxSteps))
78
+ }
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@mdjhnson/homebridge-yoto",
3
+ "description": "Control your Yoto players through Apple HomeKit with real-time MQTT updates",
4
+ "version": "0.1.0",
5
+ "author": "mdjhnson (https://github.com/mdjhnson)",
6
+ "contributors": [
7
+ "Bret Comnes <bcomnes@gmail.com> (https://bret.io)"
8
+ ],
9
+ "bugs": {
10
+ "url": "https://github.com/mdjhnson/homebridge-yoto/issues"
11
+ },
12
+ "dependencies": {
13
+ "@homebridge/plugin-ui-utils": "^2.2.6",
14
+ "color-convert": "3.1.3",
15
+ "yoto-nodejs-client": "^0.0.11"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^25.9.8",
19
+ "@voxpelli/tsconfig": "^16.2.1",
20
+ "auto-changelog": "^2.0.0",
21
+ "c8": "^10.0.0",
22
+ "eslint": "^9.39.2",
23
+ "globals": "^17.12.0",
24
+ "homebridge": "^2.4.0",
25
+ "neostandard": "^0.12.0",
26
+ "npm-run-all2": "^8.0.1",
27
+ "typescript": "~5.9.3"
28
+ },
29
+ "engines": {
30
+ "node": ">=22",
31
+ "npm": ">=10",
32
+ "homebridge": "^1.8.0 || ^2.0.0"
33
+ },
34
+ "homepage": "https://github.com/mdjhnson/homebridge-yoto",
35
+ "keywords": [
36
+ "homebridge-plugin",
37
+ "yoto"
38
+ ],
39
+ "license": "MIT",
40
+ "type": "module",
41
+ "module": "index.js",
42
+ "main": "index.js",
43
+ "types": "index.d.ts",
44
+ "files": [
45
+ "index.js",
46
+ "config.schema.json",
47
+ "config.schema.cjs",
48
+ "lib/",
49
+ "!lib/**/*.test.js",
50
+ "homebridge-ui/",
51
+ "README.md",
52
+ "LICENSE"
53
+ ],
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "repository": {
58
+ "type": "git",
59
+ "url": "git+https://github.com/mdjhnson/homebridge-yoto.git"
60
+ },
61
+ "scripts": {
62
+ "test": "run-s test:*",
63
+ "test:lint": "eslint",
64
+ "test:tsc": "tsc",
65
+ "test:node-test": "c8 node --test --test-reporter spec",
66
+ "version": "run-s version:*",
67
+ "version:changelog": "auto-changelog -p --template keepachangelog auto-changelog --breaking-pattern 'BREAKING CHANGE:'",
68
+ "version:git": "git add CHANGELOG.md"
69
+ },
70
+ "c8": {
71
+ "reporter": [
72
+ "lcov",
73
+ "text"
74
+ ]
75
+ }
76
+ }