@mastra/ring-signals 0.0.0 → 0.1.0-alpha.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/LICENSE.md +32 -0
- package/README.md +38 -3
- package/dist/crypto.d.ts +35 -0
- package/dist/crypto.d.ts.map +1 -0
- package/dist/index.cjs +958 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +952 -0
- package/dist/index.js.map +1 -0
- package/dist/ring-api.d.ts +45 -0
- package/dist/ring-api.d.ts.map +1 -0
- package/dist/ring-signals.d.ts +106 -0
- package/dist/ring-signals.d.ts.map +1 -0
- package/dist/types.d.ts +166 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +59 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _mastra_core_server = require("@mastra/core/server");
|
|
3
|
+
let _mastra_core_signals = require("@mastra/core/signals");
|
|
4
|
+
let _mastra_core_tools = require("@mastra/core/tools");
|
|
5
|
+
let zod = require("zod");
|
|
6
|
+
let crypto$1 = require("crypto");
|
|
7
|
+
// src/crypto.ts
|
|
8
|
+
const ALGO_PREFIX = "aes-256-gcm-hkdf";
|
|
9
|
+
const HKDF_INFO = "mastra-ring-encryption";
|
|
10
|
+
/**
|
|
11
|
+
* Encrypt a string with AES-256-GCM using an HKDF-SHA256 derived key.
|
|
12
|
+
* Format: `aes-256-gcm-hkdf:base64(salt):base64(iv):base64(authTag):base64(ciphertext)`
|
|
13
|
+
*/
|
|
14
|
+
function encrypt(plaintext, key) {
|
|
15
|
+
const salt = Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)));
|
|
16
|
+
const derived = Buffer.from((0, crypto$1.hkdfSync)("sha256", key, salt, HKDF_INFO, 32));
|
|
17
|
+
const iv = Buffer.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)));
|
|
18
|
+
const cipher = (0, crypto$1.createCipheriv)("aes-256-gcm", derived, iv);
|
|
19
|
+
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
20
|
+
const authTag = cipher.getAuthTag();
|
|
21
|
+
return `${ALGO_PREFIX}:${salt.toString("base64")}:${iv.toString("base64")}:${authTag.toString("base64")}:${encrypted.toString("base64")}`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Decrypt a value produced by `encrypt()`.
|
|
25
|
+
*/
|
|
26
|
+
function decrypt(ciphertext, key) {
|
|
27
|
+
const [prefix, saltB64, ivB64, authTagB64, encryptedB64] = ciphertext.split(":");
|
|
28
|
+
if (prefix !== ALGO_PREFIX || !saltB64 || !ivB64 || !authTagB64 || encryptedB64 === void 0) throw new Error("[Ring] Invalid encrypted value");
|
|
29
|
+
const salt = Buffer.from(saltB64, "base64");
|
|
30
|
+
const derived = Buffer.from((0, crypto$1.hkdfSync)("sha256", key, salt, HKDF_INFO, 32));
|
|
31
|
+
const decipher = (0, crypto$1.createDecipheriv)("aes-256-gcm", derived, Buffer.from(ivB64, "base64"));
|
|
32
|
+
decipher.setAuthTag(Buffer.from(authTagB64, "base64"));
|
|
33
|
+
return Buffer.concat([decipher.update(Buffer.from(encryptedB64, "base64")), decipher.final()]).toString("utf8");
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Constant-time string comparison.
|
|
37
|
+
*/
|
|
38
|
+
function safeEqual(a, b) {
|
|
39
|
+
const left = Buffer.from(a);
|
|
40
|
+
const right = Buffer.from(b);
|
|
41
|
+
return left.length === right.length && (0, crypto$1.timingSafeEqual)(left, right);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Ring account-linking nonce: `HMAC-SHA256(key, "<time>:<accountId>")`, URL-safe base64 without padding.
|
|
45
|
+
*/
|
|
46
|
+
function computeLinkNonce(hmacKey, time, accountId) {
|
|
47
|
+
return (0, crypto$1.createHmac)("sha256", hmacKey).update(`${time}:${accountId}`).digest("base64url");
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Ring webhook signature: `sha256=` + hex HMAC-SHA256 of the raw request body.
|
|
51
|
+
*/
|
|
52
|
+
function computeWebhookSignature(hmacKey, rawBody) {
|
|
53
|
+
return `sha256=${(0, crypto$1.createHmac)("sha256", hmacKey).update(rawBody).digest("hex")}`;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Whether a value was produced by `encrypt()`.
|
|
57
|
+
*/
|
|
58
|
+
function isEncrypted(value) {
|
|
59
|
+
return value.startsWith(`${ALGO_PREFIX}:`);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Derive the key that signs media URLs from the Ring HMAC key, so the key Ring uses
|
|
63
|
+
* to sign webhooks isn't also used to sign URLs that end up in thread history.
|
|
64
|
+
*/
|
|
65
|
+
function deriveMediaKey(hmacKey) {
|
|
66
|
+
return Buffer.from((0, crypto$1.hkdfSync)("sha256", hmacKey, "", "mastra-ring-media", 32)).toString("hex");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Sign a media URL path and its expiry so the media route can't be used as an open proxy to Ring.
|
|
70
|
+
*/
|
|
71
|
+
function signMediaPath(mediaKey, path, expires) {
|
|
72
|
+
return (0, crypto$1.createHmac)("sha256", mediaKey).update(`media:${path}:${expires}`).digest("base64url");
|
|
73
|
+
}
|
|
74
|
+
// src/ring-api.ts
|
|
75
|
+
const API_BASE_URL = "https://api.amazonvision.com";
|
|
76
|
+
const OAUTH_TOKEN_URL = "https://oauth.ring.com/oauth/token";
|
|
77
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
78
|
+
const MEDIA_TIMEOUT_MS = 3e5;
|
|
79
|
+
var RingApiError = class extends Error {
|
|
80
|
+
status;
|
|
81
|
+
body;
|
|
82
|
+
constructor(message, status, body) {
|
|
83
|
+
super(message);
|
|
84
|
+
this.status = status;
|
|
85
|
+
this.body = body;
|
|
86
|
+
this.name = "RingApiError";
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Thin client for the Ring Partner API.
|
|
91
|
+
* See https://developer.amazon.com/docs/ring/api-documentation.html
|
|
92
|
+
*/
|
|
93
|
+
var RingApiClient = class {
|
|
94
|
+
#options;
|
|
95
|
+
constructor(options) {
|
|
96
|
+
this.#options = options;
|
|
97
|
+
}
|
|
98
|
+
/** Exchange the authorization code Ring posts to the Token Exchange URL. */
|
|
99
|
+
exchangeCode(code) {
|
|
100
|
+
return this.#requestTokens({
|
|
101
|
+
grant_type: "authorization_code",
|
|
102
|
+
code
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/** Refresh an access token. Ring rotates the refresh token on every refresh. */
|
|
106
|
+
refresh(refreshToken) {
|
|
107
|
+
return this.#requestTokens({
|
|
108
|
+
grant_type: "refresh_token",
|
|
109
|
+
refresh_token: refreshToken
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/** Get the Ring account ID for an access token. */
|
|
113
|
+
async getAccountId(auth) {
|
|
114
|
+
return (await this.#json("GET", "/v1/users/me", auth)).data.id;
|
|
115
|
+
}
|
|
116
|
+
/** List the IDs of the devices the account has shared with the app. */
|
|
117
|
+
async listDeviceIds(auth) {
|
|
118
|
+
return ((await this.#json("GET", "/v1/devices", auth)).data ?? []).map((device) => device.id);
|
|
119
|
+
}
|
|
120
|
+
/** Verify the link nonce and mark the integration `completed`. */
|
|
121
|
+
async confirmLink(auth, nonce, accountIdentifier) {
|
|
122
|
+
await this.#json("POST", "/v1/accounts/me/app-integrations", auth, {
|
|
123
|
+
nonce,
|
|
124
|
+
account_identifier: accountIdentifier
|
|
125
|
+
});
|
|
126
|
+
await this.#json("PATCH", "/v1/accounts/me/app-integrations", auth, { status: "completed" });
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Download the latest image in a time range.
|
|
130
|
+
* Returns `undefined` when Ring has no image in the range or the range isn't authorized.
|
|
131
|
+
*/
|
|
132
|
+
async downloadLatestImage(auth, deviceId, startTimestamp, endTimestamp) {
|
|
133
|
+
const response = await this.#media(auth, deviceId, "image", {
|
|
134
|
+
type: "latest_in_range",
|
|
135
|
+
start_timestamp: startTimestamp,
|
|
136
|
+
end_timestamp: endTimestamp,
|
|
137
|
+
image_options: { format: "jpeg" }
|
|
138
|
+
});
|
|
139
|
+
if (!response.ok) return void 0;
|
|
140
|
+
return Buffer.from(await response.arrayBuffer());
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Download a recorded clip. Returns the response so callers can retry `416` and `425`
|
|
144
|
+
* while Ring finishes processing the recording.
|
|
145
|
+
*/
|
|
146
|
+
downloadClip(auth, deviceId, timestamp, durationMs, audio) {
|
|
147
|
+
return this.#media(auth, deviceId, "video", {
|
|
148
|
+
timestamp,
|
|
149
|
+
duration: durationMs,
|
|
150
|
+
audio_options: { audio_enabled: audio }
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
#headers(auth) {
|
|
154
|
+
return {
|
|
155
|
+
Authorization: `Bearer ${auth.accessToken}`,
|
|
156
|
+
"Content-Type": "application/json",
|
|
157
|
+
"User-Agent": this.#options.userAgent,
|
|
158
|
+
Hardware_Id: auth.hardwareId
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
#media(auth, deviceId, kind, body) {
|
|
162
|
+
return fetch(`${API_BASE_URL}/v1/devices/${encodeURIComponent(deviceId)}/media/${kind}/download`, {
|
|
163
|
+
method: "POST",
|
|
164
|
+
headers: this.#headers(auth),
|
|
165
|
+
body: JSON.stringify(body),
|
|
166
|
+
signal: AbortSignal.timeout(MEDIA_TIMEOUT_MS)
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
async #json(method, path, auth, body) {
|
|
170
|
+
const response = await fetch(`${API_BASE_URL}${path}`, {
|
|
171
|
+
method,
|
|
172
|
+
headers: this.#headers(auth),
|
|
173
|
+
...body ? { body: JSON.stringify(body) } : {},
|
|
174
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
175
|
+
});
|
|
176
|
+
const text = await response.text();
|
|
177
|
+
if (!response.ok) throw new RingApiError(`[Ring] ${method} ${path} failed with ${response.status}`, response.status, text);
|
|
178
|
+
return text ? JSON.parse(text) : void 0;
|
|
179
|
+
}
|
|
180
|
+
async #requestTokens(params) {
|
|
181
|
+
const response = await fetch(OAUTH_TOKEN_URL, {
|
|
182
|
+
method: "POST",
|
|
183
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
184
|
+
body: new URLSearchParams({
|
|
185
|
+
...params,
|
|
186
|
+
client_id: this.#options.clientId,
|
|
187
|
+
client_secret: this.#options.clientSecret
|
|
188
|
+
}),
|
|
189
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
190
|
+
});
|
|
191
|
+
const text = await response.text();
|
|
192
|
+
if (!response.ok) throw new RingApiError(`[Ring] ${params.grant_type} token request failed with ${response.status}`, response.status, text);
|
|
193
|
+
const tokens = JSON.parse(text);
|
|
194
|
+
return {
|
|
195
|
+
accessToken: tokens.access_token,
|
|
196
|
+
refreshToken: tokens.refresh_token,
|
|
197
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
// src/ring-signals.ts
|
|
202
|
+
const PLATFORM = "ring";
|
|
203
|
+
/**
|
|
204
|
+
* Guidance added to the agent's system prompt for Ring notifications, covering only the enabled tools.
|
|
205
|
+
* It depends only on config, so it's the same on every request and doesn't invalidate the prompt cache.
|
|
206
|
+
*/
|
|
207
|
+
const buildRingInstructions = (tools) => {
|
|
208
|
+
const steps = [...tools.snapshot ? ["Call ring_snapshot with its deviceId and timestamp, then describe who or what is at the door."] : [], ...tools.clip ? ["Call ring_clip with the same deviceId and timestamp."] : []];
|
|
209
|
+
const lines = ["Ring events arrive as <notification source=\"ring\"> messages with deviceId and timestamp attributes."];
|
|
210
|
+
if (steps.length > 0) lines.push("When a notification has type=\"button_press\":", ...steps.map((step, index) => `${index + 1}. ${step}`), "Don't include snapshot or clip urls in your reply unless a tool result asks you to share one.");
|
|
211
|
+
return lines.join("\n");
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* Default guidance when both tools are enabled.
|
|
215
|
+
*/
|
|
216
|
+
const DEFAULT_RING_INSTRUCTIONS = buildRingInstructions({
|
|
217
|
+
snapshot: true,
|
|
218
|
+
clip: true
|
|
219
|
+
});
|
|
220
|
+
const LINK_WINDOW_MS = 6e5;
|
|
221
|
+
const SNAPSHOT_WINDOW_MS = 15e3;
|
|
222
|
+
const SNAPSHOT_LOOK_BACK_MS = [
|
|
223
|
+
9e5,
|
|
224
|
+
36e5,
|
|
225
|
+
216e5,
|
|
226
|
+
864e5
|
|
227
|
+
];
|
|
228
|
+
const DEFAULT_CLIP_DURATION_MS = 15e3;
|
|
229
|
+
const DEFAULT_MAX_ATTACHMENT_BYTES = 1e7;
|
|
230
|
+
const MEDIA_CACHE_TTL_MS = 6e5;
|
|
231
|
+
const MEDIA_CACHE_MAX_ENTRIES = 20;
|
|
232
|
+
const MAX_CLIP_DURATION_MS = 9e5;
|
|
233
|
+
const DEFAULT_CLIP_PROCESSING_TIMEOUT_MS = 12e4;
|
|
234
|
+
const CLIP_RETRY_MS = 5e3;
|
|
235
|
+
const DEFAULT_MEDIA_URL_TTL_MS = 6048e5;
|
|
236
|
+
/**
|
|
237
|
+
* Default notification for each Ring event type. Unlisted events are disabled.
|
|
238
|
+
*/
|
|
239
|
+
const DEFAULT_RING_EVENTS = {
|
|
240
|
+
button_press: {
|
|
241
|
+
priority: "high",
|
|
242
|
+
summary: "Doorbell was pressed."
|
|
243
|
+
},
|
|
244
|
+
motion_detected: {
|
|
245
|
+
priority: "medium",
|
|
246
|
+
summary: "Motion was detected."
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
const primitiveAttributes = (attributes = {}) => {
|
|
250
|
+
return Object.fromEntries(Object.entries(attributes).filter(([, value]) => value === null || [
|
|
251
|
+
"string",
|
|
252
|
+
"number",
|
|
253
|
+
"boolean"
|
|
254
|
+
].includes(typeof value)));
|
|
255
|
+
};
|
|
256
|
+
const mediaOutputSchema = zod.z.object({
|
|
257
|
+
mediaId: zod.z.string(),
|
|
258
|
+
url: zod.z.string().optional(),
|
|
259
|
+
attached: zod.z.boolean(),
|
|
260
|
+
shareLink: zod.z.boolean()
|
|
261
|
+
});
|
|
262
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
263
|
+
/**
|
|
264
|
+
* Ring signal provider.
|
|
265
|
+
*
|
|
266
|
+
* Links a Ring account to an agent, receives Ring webhooks, and sends each event
|
|
267
|
+
* to an agent thread as a notification signal. Adds `ring_snapshot` and `ring_clip`
|
|
268
|
+
* tools so the agent can fetch media for an event.
|
|
269
|
+
*
|
|
270
|
+
* ```ts
|
|
271
|
+
* const ring = new RingSignals();
|
|
272
|
+
*
|
|
273
|
+
* const agent = new Agent({ signals: [ring], ... });
|
|
274
|
+
*
|
|
275
|
+
* export const mastra = new Mastra({ agents: { agent }, storage });
|
|
276
|
+
* ```
|
|
277
|
+
*
|
|
278
|
+
* Mastra adds the routes from `getRoutes()` to the server when the agent is registered.
|
|
279
|
+
*/
|
|
280
|
+
var RingSignals = class extends _mastra_core_signals.SignalProvider {
|
|
281
|
+
id = "ring-signals";
|
|
282
|
+
name = "Ring Signals";
|
|
283
|
+
#options;
|
|
284
|
+
#api;
|
|
285
|
+
#hmacKey;
|
|
286
|
+
#mediaKey;
|
|
287
|
+
#missingConfig;
|
|
288
|
+
#routePrefix;
|
|
289
|
+
#events;
|
|
290
|
+
#snapshots = /* @__PURE__ */ new Map();
|
|
291
|
+
#clips = /* @__PURE__ */ new Map();
|
|
292
|
+
#mediaCache = /* @__PURE__ */ new Map();
|
|
293
|
+
#warnedPlaintext = false;
|
|
294
|
+
#refreshes = /* @__PURE__ */ new Map();
|
|
295
|
+
constructor(options = {}) {
|
|
296
|
+
super();
|
|
297
|
+
this.#options = options;
|
|
298
|
+
const clientId = options.clientId ?? process.env.RING_CLIENT_ID ?? "";
|
|
299
|
+
const clientSecret = options.clientSecret ?? process.env.RING_CLIENT_SECRET ?? "";
|
|
300
|
+
this.#hmacKey = options.hmacKey ?? process.env.RING_HMAC_KEY ?? "";
|
|
301
|
+
this.#mediaKey = this.#hmacKey ? deriveMediaKey(this.#hmacKey) : "";
|
|
302
|
+
this.#missingConfig = [
|
|
303
|
+
...clientId ? [] : ["clientId (RING_CLIENT_ID)"],
|
|
304
|
+
...clientSecret ? [] : ["clientSecret (RING_CLIENT_SECRET)"],
|
|
305
|
+
...this.#hmacKey ? [] : ["hmacKey (RING_HMAC_KEY)"]
|
|
306
|
+
];
|
|
307
|
+
this.#routePrefix = (options.routePrefix ?? "/ring").replace(/\/$/, "");
|
|
308
|
+
this.#events = {
|
|
309
|
+
...DEFAULT_RING_EVENTS,
|
|
310
|
+
...options.events
|
|
311
|
+
};
|
|
312
|
+
this.#api = new RingApiClient({
|
|
313
|
+
clientId,
|
|
314
|
+
clientSecret,
|
|
315
|
+
userAgent: options.userAgent ?? "MastraRingSignals/1.0"
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Warns when credentials are missing as soon as the agent is added to Mastra.
|
|
320
|
+
* Mastra registers the routes from `getRoutes()` itself.
|
|
321
|
+
*/
|
|
322
|
+
__registerMastra(mastra) {
|
|
323
|
+
super.__registerMastra(mastra);
|
|
324
|
+
if (this.#missingConfig.length > 0) mastra.getLogger()?.warn(`[Ring] RingSignals is missing ${this.#missingConfig.join(", ")}. Account linking, webhooks and media will fail until it's set.`);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Send events from a Ring device to a specific thread.
|
|
328
|
+
* Devices without a subscription use the `target` option.
|
|
329
|
+
*/
|
|
330
|
+
subscribeThread(target, deviceId) {
|
|
331
|
+
return this.subscribe(target, deviceId);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Stop sending events from a Ring device to a thread.
|
|
335
|
+
*
|
|
336
|
+
* @returns `true` if the thread was subscribed.
|
|
337
|
+
*/
|
|
338
|
+
unsubscribeThread(target, deviceId) {
|
|
339
|
+
return this.unsubscribe(target, deviceId);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Verify and handle a Ring webhook. `body` must be the raw request body string,
|
|
343
|
+
* because Ring signs the exact bytes it sent.
|
|
344
|
+
*/
|
|
345
|
+
async handleWebhook(request) {
|
|
346
|
+
this.#assertConfigured();
|
|
347
|
+
const rawBody = typeof request.body === "string" ? request.body : JSON.stringify(request.body);
|
|
348
|
+
const signature = Object.entries(request.headers).find(([name]) => name.toLowerCase() === "x-signature")?.[1];
|
|
349
|
+
if (!signature || !safeEqual(computeWebhookSignature(this.#hmacKey, rawBody), signature)) return {
|
|
350
|
+
status: 401,
|
|
351
|
+
body: { error: "invalid signature" }
|
|
352
|
+
};
|
|
353
|
+
let event;
|
|
354
|
+
try {
|
|
355
|
+
event = JSON.parse(rawBody);
|
|
356
|
+
} catch {
|
|
357
|
+
return {
|
|
358
|
+
status: 400,
|
|
359
|
+
body: { error: "invalid JSON body" }
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
await this.#handleAccountEvent(event);
|
|
363
|
+
const notification = this.#events[event.data.type];
|
|
364
|
+
if (!notification) return {
|
|
365
|
+
status: 200,
|
|
366
|
+
body: { ignored: event.data.type }
|
|
367
|
+
};
|
|
368
|
+
const targets = await this.#resolveTargets(event);
|
|
369
|
+
const { source, source_type: sourceType, timestamp, sub_type: subType } = event.data.attributes;
|
|
370
|
+
for (const target of targets) await this.notify({
|
|
371
|
+
source: "ring",
|
|
372
|
+
kind: event.data.type,
|
|
373
|
+
priority: notification.priority,
|
|
374
|
+
summary: notification.summary,
|
|
375
|
+
attributes: {
|
|
376
|
+
...sourceType === "devices" ? { deviceId: source } : {},
|
|
377
|
+
...timestamp !== void 0 ? { timestamp } : {},
|
|
378
|
+
...event.data.type === "motion_detected" && subType ? { motionType: subType } : {},
|
|
379
|
+
...primitiveAttributes(notification.attributes?.(event))
|
|
380
|
+
},
|
|
381
|
+
payload: event.data,
|
|
382
|
+
dedupeKey: `ring:${event.meta.request_id}:${target.threadId}`,
|
|
383
|
+
...notification.coalesce ? { coalesceKey: `ring:${event.data.type}:${source}` } : {}
|
|
384
|
+
}, target);
|
|
385
|
+
return {
|
|
386
|
+
status: 200,
|
|
387
|
+
body: { delivered: targets.length }
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* API routes for Ring account linking, webhooks and media. Mastra adds them to `server.apiRoutes` automatically.
|
|
392
|
+
*
|
|
393
|
+
* | Ring setting | Route |
|
|
394
|
+
* | ------------------ | ----------------------------- |
|
|
395
|
+
* | Account Link URL | `GET {prefix}/link` |
|
|
396
|
+
* | Token Exchange URL | `POST {prefix}/token` |
|
|
397
|
+
* | Webhook URL | `POST {prefix}/webhook` |
|
|
398
|
+
* | App Homepage URL | `GET {prefix}/home` |
|
|
399
|
+
*/
|
|
400
|
+
getRoutes() {
|
|
401
|
+
const prefix = this.#routePrefix;
|
|
402
|
+
return [
|
|
403
|
+
(0, _mastra_core_server.registerApiRoute)(`${prefix}/token`, {
|
|
404
|
+
method: "POST",
|
|
405
|
+
requiresAuth: false,
|
|
406
|
+
handler: async (context) => {
|
|
407
|
+
const { code } = await context.req.parseBody();
|
|
408
|
+
try {
|
|
409
|
+
await this.#exchangeCode(String(code));
|
|
410
|
+
return context.json({ ok: true });
|
|
411
|
+
} catch (error) {
|
|
412
|
+
this.#logError("token exchange failed", error);
|
|
413
|
+
return context.json({ error: "token exchange failed" }, 500);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}),
|
|
417
|
+
(0, _mastra_core_server.registerApiRoute)(`${prefix}/link`, {
|
|
418
|
+
method: "GET",
|
|
419
|
+
requiresAuth: false,
|
|
420
|
+
handler: async (context) => {
|
|
421
|
+
const { nonce, time } = context.req.query();
|
|
422
|
+
try {
|
|
423
|
+
const failure = await this.#completeLink(nonce ?? "", time ?? "");
|
|
424
|
+
if (failure) {
|
|
425
|
+
this.#logError(`account link failed: ${failure}`);
|
|
426
|
+
return context.text(`Ring account link failed: ${failure}`, 400);
|
|
427
|
+
}
|
|
428
|
+
return context.text("Ring account linked");
|
|
429
|
+
} catch (error) {
|
|
430
|
+
this.#logError("account link failed", error);
|
|
431
|
+
return context.text("Ring account link failed", 500);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}),
|
|
435
|
+
(0, _mastra_core_server.registerApiRoute)(`${prefix}/webhook`, {
|
|
436
|
+
method: "POST",
|
|
437
|
+
requiresAuth: false,
|
|
438
|
+
handler: async (context) => {
|
|
439
|
+
try {
|
|
440
|
+
const result = await this.handleWebhook({
|
|
441
|
+
body: await context.req.text(),
|
|
442
|
+
headers: Object.fromEntries(context.req.raw.headers.entries())
|
|
443
|
+
});
|
|
444
|
+
return context.json(result.body ?? {}, result.status ?? 200);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
this.#logError("webhook failed", error);
|
|
447
|
+
return context.json({ error: "webhook failed" }, 500);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}),
|
|
451
|
+
(0, _mastra_core_server.registerApiRoute)(`${prefix}/home`, {
|
|
452
|
+
method: "GET",
|
|
453
|
+
requiresAuth: false,
|
|
454
|
+
handler: async (context) => context.text(this.name)
|
|
455
|
+
}),
|
|
456
|
+
(0, _mastra_core_server.registerApiRoute)(`${prefix}/media/:kind/:deviceId/:timestamp`, {
|
|
457
|
+
method: "GET",
|
|
458
|
+
requiresAuth: false,
|
|
459
|
+
handler: async (context) => {
|
|
460
|
+
const { kind, deviceId, timestamp } = context.req.param();
|
|
461
|
+
const path = `${kind}/${deviceId}/${timestamp}`;
|
|
462
|
+
const expires = Number(context.req.query("expires"));
|
|
463
|
+
const signature = context.req.query("signature") ?? "";
|
|
464
|
+
if (!this.#mediaKey || !safeEqual(signMediaPath(this.#mediaKey, path, expires), signature)) return context.text("Invalid signature", 403);
|
|
465
|
+
if (!(expires > Date.now())) return context.text("Link expired", 403);
|
|
466
|
+
const media = kind === "clip" ? await this.#getClip(deviceId, Number(timestamp)) : await this.#getSnapshot(deviceId, Number(timestamp));
|
|
467
|
+
if (!media) return context.text("Not found", 404);
|
|
468
|
+
const contentType = kind === "clip" ? "video/mp4" : "image/jpeg";
|
|
469
|
+
const range = /^bytes=(\d*)-(\d*)$/.exec(context.req.header("Range") ?? "");
|
|
470
|
+
if (range) {
|
|
471
|
+
const start = range[1] ? Number(range[1]) : Math.max(media.length - Number(range[2]), 0);
|
|
472
|
+
const end = range[1] && range[2] ? Math.min(Number(range[2]), media.length - 1) : media.length - 1;
|
|
473
|
+
if (start > end || start >= media.length) return context.body(null, 416, { "Content-Range": `bytes */${media.length}` });
|
|
474
|
+
return context.body(new Uint8Array(media.subarray(start, end + 1)), 206, {
|
|
475
|
+
"Content-Type": contentType,
|
|
476
|
+
"Content-Range": `bytes ${start}-${end}/${media.length}`,
|
|
477
|
+
"Accept-Ranges": "bytes"
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
return context.body(new Uint8Array(media), 200, {
|
|
481
|
+
"Content-Type": contentType,
|
|
482
|
+
"Accept-Ranges": "bytes"
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
})
|
|
486
|
+
];
|
|
487
|
+
}
|
|
488
|
+
getInputProcessors() {
|
|
489
|
+
return [this];
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Adds the Ring guidance as a tagged system message. The text never changes, so the
|
|
493
|
+
* system prompt stays identical across requests and the prompt cache stays valid.
|
|
494
|
+
*/
|
|
495
|
+
processInputStep({ messageList }) {
|
|
496
|
+
const instructions = this.#options.instructions ?? buildRingInstructions({
|
|
497
|
+
snapshot: this.#snapshotEnabled(),
|
|
498
|
+
clip: this.#clipOptions() !== void 0
|
|
499
|
+
});
|
|
500
|
+
if (instructions) messageList.addSystem(instructions, "ring-signals");
|
|
501
|
+
return messageList;
|
|
502
|
+
}
|
|
503
|
+
#snapshotEnabled() {
|
|
504
|
+
return this.#options.tools?.snapshot !== false;
|
|
505
|
+
}
|
|
506
|
+
#visibleToModel(tool) {
|
|
507
|
+
const configured = this.#options.tools?.[tool];
|
|
508
|
+
return (typeof configured === "object" ? configured.visibleToModel : void 0) ?? tool === "snapshot";
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Whether to attach media of this size for this tool call. Function options are given the platform
|
|
512
|
+
* stored on the thread by its channel, so they work for runs woken by a Ring signal too.
|
|
513
|
+
*/
|
|
514
|
+
async #shouldAttach(tool, threadId, size) {
|
|
515
|
+
const configured = this.#options.tools?.[tool];
|
|
516
|
+
const options = typeof configured === "object" ? configured : {};
|
|
517
|
+
const platform = await this.#threadPlatform(threadId);
|
|
518
|
+
const attachment = options.attachment ?? true;
|
|
519
|
+
if (!(platform !== void 0 && (Array.isArray(attachment) ? attachment.includes(platform) : attachment))) return {
|
|
520
|
+
attached: false,
|
|
521
|
+
platform
|
|
522
|
+
};
|
|
523
|
+
const maxBytes = (typeof options.maxAttachmentBytes === "object" ? options.maxAttachmentBytes[platform] : options.maxAttachmentBytes) ?? DEFAULT_MAX_ATTACHMENT_BYTES;
|
|
524
|
+
if (size > maxBytes) {
|
|
525
|
+
this.mastra?.getLogger()?.info(`[Ring] Not attaching ${tool} (${size} bytes) on ${platform ?? "this thread"}: over the ${maxBytes} byte limit.`);
|
|
526
|
+
return {
|
|
527
|
+
attached: false,
|
|
528
|
+
platform
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
return {
|
|
532
|
+
attached: true,
|
|
533
|
+
platform
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* What the model is told about a media tool result. On a channel thread the user can't see tool results,
|
|
538
|
+
* so media that wasn't attached has to be shared as a link.
|
|
539
|
+
*/
|
|
540
|
+
#mediaModelText(label, output) {
|
|
541
|
+
if (output.attached) return `The ${label} was sent to the user as an attachment, so don't include its url.`;
|
|
542
|
+
if (!output.url) return `The ${label} was fetched, but there's no link to share with the user.`;
|
|
543
|
+
if (output.shareLink) return label === "clip" ? `This chat can't show tool results, so share the clip as a link in your reply: [Watch clip](${output.url})` : `This chat can't show tool results, so share the snapshot as a link in your reply: [View snapshot](${output.url})`;
|
|
544
|
+
return `The ${label} is shown to the user from this tool result, so don't include its url.`;
|
|
545
|
+
}
|
|
546
|
+
async #threadPlatform(threadId) {
|
|
547
|
+
if (!threadId) return void 0;
|
|
548
|
+
const platform = (await (await this.mastra?.getStorage()?.getStore("memory"))?.getThreadById({ threadId }))?.metadata?.channel_platform;
|
|
549
|
+
return typeof platform === "string" ? platform : void 0;
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Writes the media as a `file` chunk. Mastra's channel layer posts `file` chunks as attachments
|
|
553
|
+
* on every channel platform; other surfaces can ignore them. Returns whether a chunk was written.
|
|
554
|
+
*/
|
|
555
|
+
async #attachFile(writer, data, mimeType, filename) {
|
|
556
|
+
if (!writer?.custom) return false;
|
|
557
|
+
await writer.custom({
|
|
558
|
+
type: "file",
|
|
559
|
+
runId: this.id,
|
|
560
|
+
from: "AGENT",
|
|
561
|
+
payload: {
|
|
562
|
+
data: data.toString("base64"),
|
|
563
|
+
mimeType,
|
|
564
|
+
filename
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
return true;
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Resolved clip settings, or `undefined` when the clip tool is disabled.
|
|
571
|
+
*/
|
|
572
|
+
#clipOptions() {
|
|
573
|
+
const clip = this.#options.tools?.clip ?? true;
|
|
574
|
+
if (clip === false) return void 0;
|
|
575
|
+
const options = clip === true ? {} : clip;
|
|
576
|
+
return {
|
|
577
|
+
audio: options.audio ?? true,
|
|
578
|
+
durationMs: Math.min(options.durationMs ?? DEFAULT_CLIP_DURATION_MS, MAX_CLIP_DURATION_MS),
|
|
579
|
+
processingTimeoutMs: options.processingTimeoutMs ?? DEFAULT_CLIP_PROCESSING_TIMEOUT_MS
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
getTools() {
|
|
583
|
+
const clipOptions = this.#clipOptions();
|
|
584
|
+
const clipSeconds = Math.round((clipOptions?.durationMs ?? DEFAULT_CLIP_DURATION_MS) / 1e3);
|
|
585
|
+
const ringSnapshot = (0, _mastra_core_tools.createTool)({
|
|
586
|
+
id: "ring_snapshot",
|
|
587
|
+
description: "Get a still image from a Ring camera for an event. Uses the latest image after the event, or the most recent image before it if there is none.",
|
|
588
|
+
inputSchema: zod.z.object({
|
|
589
|
+
deviceId: zod.z.string().describe("The deviceId attribute from the Ring notification"),
|
|
590
|
+
timestamp: zod.z.number().describe("The timestamp attribute from the Ring notification, in epoch milliseconds")
|
|
591
|
+
}),
|
|
592
|
+
outputSchema: mediaOutputSchema,
|
|
593
|
+
execute: async ({ deviceId, timestamp }, context) => {
|
|
594
|
+
const image = await this.#getSnapshot(deviceId, timestamp);
|
|
595
|
+
if (!image) throw new Error("Ring has no image for this device in the last 24 hours.");
|
|
596
|
+
const attachment = await this.#shouldAttach("snapshot", context?.agent?.threadId, image.length);
|
|
597
|
+
const { platform } = attachment;
|
|
598
|
+
const attached = attachment.attached && await this.#attachFile(context?.writer, image, "image/jpeg", `snapshot-${timestamp}.jpg`);
|
|
599
|
+
const url = this.#mediaUrl("snapshot", deviceId, timestamp);
|
|
600
|
+
const mediaId = `snapshot:${deviceId}:${timestamp}`;
|
|
601
|
+
if (this.#visibleToModel("snapshot")) this.#snapshots.set(mediaId, image.toString("base64"));
|
|
602
|
+
return {
|
|
603
|
+
mediaId,
|
|
604
|
+
url,
|
|
605
|
+
attached,
|
|
606
|
+
shareLink: platform !== void 0 && !attached && url !== void 0
|
|
607
|
+
};
|
|
608
|
+
},
|
|
609
|
+
toModelOutput: (output) => {
|
|
610
|
+
const image = this.#snapshots.get(output.mediaId);
|
|
611
|
+
this.#snapshots.delete(output.mediaId);
|
|
612
|
+
return {
|
|
613
|
+
type: "content",
|
|
614
|
+
value: [{
|
|
615
|
+
type: "text",
|
|
616
|
+
text: this.#mediaModelText("snapshot", output)
|
|
617
|
+
}, ...image ? [{
|
|
618
|
+
type: "image-data",
|
|
619
|
+
data: image,
|
|
620
|
+
mediaType: "image/jpeg"
|
|
621
|
+
}] : []]
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
});
|
|
625
|
+
const ringClip = (0, _mastra_core_tools.createTool)({
|
|
626
|
+
id: "ring_clip",
|
|
627
|
+
description: `Get a ${clipSeconds} second Ring video clip starting at an event. Waits up to ${Math.round((clipOptions?.processingTimeoutMs ?? DEFAULT_CLIP_PROCESSING_TIMEOUT_MS) / 1e3)} seconds for Ring to process it.`,
|
|
628
|
+
inputSchema: zod.z.object({
|
|
629
|
+
deviceId: zod.z.string().describe("The deviceId attribute from the Ring notification"),
|
|
630
|
+
timestamp: zod.z.number().describe("The timestamp attribute from the Ring notification, in epoch milliseconds")
|
|
631
|
+
}),
|
|
632
|
+
outputSchema: mediaOutputSchema,
|
|
633
|
+
execute: async ({ deviceId, timestamp }, context) => {
|
|
634
|
+
const clip = await this.#getClip(deviceId, timestamp);
|
|
635
|
+
if (!clip) throw new Error("Ring has no recording for this event.");
|
|
636
|
+
const attachment = await this.#shouldAttach("clip", context?.agent?.threadId, clip.length);
|
|
637
|
+
const { platform } = attachment;
|
|
638
|
+
const attached = attachment.attached && await this.#attachFile(context?.writer, clip, "video/mp4", `clip-${timestamp}.mp4`);
|
|
639
|
+
const url = this.#mediaUrl("clip", deviceId, timestamp);
|
|
640
|
+
const mediaId = `clip:${deviceId}:${timestamp}`;
|
|
641
|
+
if (this.#visibleToModel("clip")) this.#clips.set(mediaId, clip.toString("base64"));
|
|
642
|
+
return {
|
|
643
|
+
mediaId,
|
|
644
|
+
url,
|
|
645
|
+
attached,
|
|
646
|
+
shareLink: platform !== void 0 && !attached && url !== void 0
|
|
647
|
+
};
|
|
648
|
+
},
|
|
649
|
+
toModelOutput: (output) => {
|
|
650
|
+
const video = this.#clips.get(output.mediaId);
|
|
651
|
+
this.#clips.delete(output.mediaId);
|
|
652
|
+
return {
|
|
653
|
+
type: "content",
|
|
654
|
+
value: [{
|
|
655
|
+
type: "text",
|
|
656
|
+
text: this.#mediaModelText("clip", output)
|
|
657
|
+
}, ...video ? [{
|
|
658
|
+
type: "file-data",
|
|
659
|
+
data: video,
|
|
660
|
+
mediaType: "video/mp4"
|
|
661
|
+
}] : []]
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
});
|
|
665
|
+
return {
|
|
666
|
+
...this.#snapshotEnabled() ? { ring_snapshot: ringSnapshot } : {},
|
|
667
|
+
...clipOptions ? { ring_clip: ringClip } : {}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
async #resolveTargets(event) {
|
|
671
|
+
const deviceId = event.data.attributes.source;
|
|
672
|
+
const subscriptions = this.getSubscriptionsForResource(deviceId);
|
|
673
|
+
if (subscriptions.length > 0) return subscriptions.map(({ resourceId, threadId }) => ({
|
|
674
|
+
resourceId,
|
|
675
|
+
threadId
|
|
676
|
+
}));
|
|
677
|
+
const { target } = this.#options;
|
|
678
|
+
const resolved = typeof target === "function" ? await target(event) : target ?? {
|
|
679
|
+
resourceId: this.agent?.id ?? "ring",
|
|
680
|
+
threadId: deviceId
|
|
681
|
+
};
|
|
682
|
+
return resolved ? [resolved] : [];
|
|
683
|
+
}
|
|
684
|
+
async #exchangeCode(code) {
|
|
685
|
+
this.#assertConfigured();
|
|
686
|
+
const tokens = await this.#api.exchangeCode(code);
|
|
687
|
+
const hardwareId = this.#options.hardwareId ?? crypto.randomUUID();
|
|
688
|
+
const accountId = await this.#api.getAccountId({
|
|
689
|
+
accessToken: tokens.accessToken,
|
|
690
|
+
hardwareId
|
|
691
|
+
});
|
|
692
|
+
await this.#saveAccount({
|
|
693
|
+
accountId,
|
|
694
|
+
hardwareId,
|
|
695
|
+
deviceIds: [],
|
|
696
|
+
...tokens
|
|
697
|
+
}, "pending");
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Returns a failure reason, or `undefined` when the link completed.
|
|
701
|
+
* A pending account only becomes active once its nonce checks out, so a new token exchange
|
|
702
|
+
* never overwrites a working link.
|
|
703
|
+
*/
|
|
704
|
+
async #completeLink(nonce, time) {
|
|
705
|
+
this.#assertConfigured();
|
|
706
|
+
if (!nonce || !time) return "missing nonce or time";
|
|
707
|
+
if (!(Math.abs(Date.now() - Number(time)) <= LINK_WINDOW_MS)) return "link request expired";
|
|
708
|
+
const pending = (await this.#listInstallations("pending")).map((installation) => this.#readAccount(installation));
|
|
709
|
+
if (pending.length === 0) return "no account saved by the token exchange";
|
|
710
|
+
const account = pending.find((candidate) => safeEqual(computeLinkNonce(this.#hmacKey, time, candidate.accountId), nonce));
|
|
711
|
+
if (!account) return "nonce mismatch";
|
|
712
|
+
await this.#api.confirmLink(account, nonce, account.accountId);
|
|
713
|
+
const deviceIds = await this.#api.listDeviceIds(account).catch(() => []);
|
|
714
|
+
await this.#saveAccount({
|
|
715
|
+
...account,
|
|
716
|
+
deviceIds
|
|
717
|
+
}, "active");
|
|
718
|
+
await (await this.#channelsStorage()).deleteInstallation(this.#installationId(account.accountId, "pending"));
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Keeps stored accounts in sync with Ring: removes an account's tokens when the app is unlinked,
|
|
722
|
+
* and records which account each device belongs to.
|
|
723
|
+
*/
|
|
724
|
+
async #handleAccountEvent(event) {
|
|
725
|
+
const accountId = event.meta.account_id;
|
|
726
|
+
if (!accountId) return;
|
|
727
|
+
if (event.data.type === "app_integration_removed") {
|
|
728
|
+
await this.#deleteAccount(accountId);
|
|
729
|
+
this.mastra?.getLogger()?.info(`[Ring] Ring account unlinked; removed its stored tokens.`);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
if (event.data.type === "subscription_deactivated") {
|
|
733
|
+
this.mastra?.getLogger()?.warn("[Ring] The Ring subscription was deactivated. Snapshots and clips won't be available.");
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
const deviceId = event.data.attributes.source;
|
|
737
|
+
if (event.data.attributes.source_type === "devices" && deviceId) await this.#rememberDevice(accountId, deviceId);
|
|
738
|
+
}
|
|
739
|
+
#assertConfigured() {
|
|
740
|
+
if (this.#missingConfig.length > 0) throw new Error(`[Ring] RingSignals is missing ${this.#missingConfig.join(", ")}.`);
|
|
741
|
+
}
|
|
742
|
+
#logError(message, error) {
|
|
743
|
+
const detail = error instanceof RingApiError ? `${error.message}: ${error.body}` : error instanceof Error ? error.message : "";
|
|
744
|
+
this.mastra?.getLogger()?.error(`[Ring] ${message}${detail ? ` - ${detail}` : ""}`);
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* One record per linked Ring account, so several accounts can be linked to the same agent.
|
|
748
|
+
* The account waiting for `/link` to confirm it is stored separately until then.
|
|
749
|
+
*/
|
|
750
|
+
#installationId(accountId, status) {
|
|
751
|
+
const id = `${PLATFORM}:${this.agent?.id ?? "default"}:${accountId}`;
|
|
752
|
+
return status === "pending" ? `${id}:pending` : id;
|
|
753
|
+
}
|
|
754
|
+
async #channelsStorage() {
|
|
755
|
+
const storage = this.mastra?.getStorage();
|
|
756
|
+
const channels = storage ? await storage.getStore("channels") : void 0;
|
|
757
|
+
if (!channels) throw new Error("[Ring] RingSignals needs Mastra storage with channels support (e.g. LibSQLStore or PostgresStore).");
|
|
758
|
+
return channels;
|
|
759
|
+
}
|
|
760
|
+
async #listInstallations(status) {
|
|
761
|
+
const channels = await this.#channelsStorage();
|
|
762
|
+
const agentId = this.agent?.id ?? "default";
|
|
763
|
+
return (await channels.listInstallations(PLATFORM)).filter((installation) => installation.agentId === agentId && installation.status === status);
|
|
764
|
+
}
|
|
765
|
+
async #saveAccount(account, status) {
|
|
766
|
+
const channels = await this.#channelsStorage();
|
|
767
|
+
const id = this.#installationId(account.accountId, status);
|
|
768
|
+
const existing = await channels.getInstallation(id);
|
|
769
|
+
const now = /* @__PURE__ */ new Date();
|
|
770
|
+
await channels.saveInstallation({
|
|
771
|
+
id,
|
|
772
|
+
platform: PLATFORM,
|
|
773
|
+
agentId: this.agent?.id ?? "default",
|
|
774
|
+
status,
|
|
775
|
+
data: {
|
|
776
|
+
accountId: account.accountId,
|
|
777
|
+
hardwareId: account.hardwareId,
|
|
778
|
+
deviceIds: account.deviceIds,
|
|
779
|
+
accessToken: this.#encrypt(account.accessToken),
|
|
780
|
+
refreshToken: this.#encrypt(account.refreshToken),
|
|
781
|
+
expiresAt: account.expiresAt
|
|
782
|
+
},
|
|
783
|
+
createdAt: existing?.createdAt ?? now,
|
|
784
|
+
updatedAt: now
|
|
785
|
+
});
|
|
786
|
+
if (status === "active") {
|
|
787
|
+
for (const duplicate of await this.#listInstallations("active")) if (duplicate.id !== id && duplicate.data.accountId === account.accountId) await channels.deleteInstallation(duplicate.id);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
async #deleteAccount(accountId) {
|
|
791
|
+
const channels = await this.#channelsStorage();
|
|
792
|
+
for (const status of ["active", "pending"]) for (const installation of await this.#listInstallations(status)) if (installation.data.accountId === accountId) await channels.deleteInstallation(installation.id);
|
|
793
|
+
}
|
|
794
|
+
async #rememberDevice(accountId, deviceId) {
|
|
795
|
+
await this.#refreshes.get(accountId)?.catch(() => void 0);
|
|
796
|
+
const account = await this.#loadAccount(accountId);
|
|
797
|
+
if (!account || account.deviceIds.includes(deviceId)) return;
|
|
798
|
+
await this.#saveAccount({
|
|
799
|
+
...account,
|
|
800
|
+
deviceIds: [...account.deviceIds, deviceId]
|
|
801
|
+
}, "active");
|
|
802
|
+
}
|
|
803
|
+
#readAccount(installation) {
|
|
804
|
+
const data = installation.data;
|
|
805
|
+
return {
|
|
806
|
+
accountId: data.accountId,
|
|
807
|
+
hardwareId: data.hardwareId,
|
|
808
|
+
deviceIds: data.deviceIds ?? [],
|
|
809
|
+
accessToken: this.#decrypt(data.accessToken),
|
|
810
|
+
refreshToken: this.#decrypt(data.refreshToken),
|
|
811
|
+
expiresAt: data.expiresAt
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
async #loadAccount(accountId) {
|
|
815
|
+
const installation = (await this.#listInstallations("active")).find((candidate) => candidate.data.accountId === accountId);
|
|
816
|
+
return installation ? this.#readAccount(installation) : void 0;
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* The linked account that owns a device. Falls back to the only linked account, so a single-account
|
|
820
|
+
* setup works before the device has been seen in a webhook.
|
|
821
|
+
*/
|
|
822
|
+
async #accountForDevice(deviceId) {
|
|
823
|
+
const accounts = (await this.#listInstallations("active")).map((installation) => this.#readAccount(installation));
|
|
824
|
+
const owner = accounts.find((account) => account.deviceIds.includes(deviceId)) ?? (accounts.length === 1 ? accounts[0] : void 0);
|
|
825
|
+
if (!owner) throw new Error(accounts.length === 0 ? "[Ring] No linked Ring account. Link the app from the Ring Appstore first." : "[Ring] Couldn't tell which linked Ring account owns this device.");
|
|
826
|
+
return owner;
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Fresh credentials for the account that owns a device. Ring invalidates the old refresh token on every
|
|
830
|
+
* refresh, so concurrent refreshes in this process share one request, and if another process refreshed
|
|
831
|
+
* first, the tokens it stored are used instead.
|
|
832
|
+
*/
|
|
833
|
+
async #getAuth(deviceId) {
|
|
834
|
+
const account = await this.#accountForDevice(deviceId);
|
|
835
|
+
if (account.expiresAt - Date.now() > 6e4) return account;
|
|
836
|
+
const inFlight = this.#refreshes.get(account.accountId);
|
|
837
|
+
if (inFlight) return inFlight;
|
|
838
|
+
const refresh = (async () => {
|
|
839
|
+
try {
|
|
840
|
+
const tokens = await this.#api.refresh(account.refreshToken);
|
|
841
|
+
const refreshed = {
|
|
842
|
+
...account,
|
|
843
|
+
...tokens
|
|
844
|
+
};
|
|
845
|
+
await this.#saveAccount(refreshed, "active");
|
|
846
|
+
return refreshed;
|
|
847
|
+
} catch (error) {
|
|
848
|
+
const stored = await this.#loadAccount(account.accountId);
|
|
849
|
+
if (stored && stored.refreshToken !== account.refreshToken && stored.expiresAt - Date.now() > 6e4) return stored;
|
|
850
|
+
throw error;
|
|
851
|
+
} finally {
|
|
852
|
+
this.#refreshes.delete(account.accountId);
|
|
853
|
+
}
|
|
854
|
+
})();
|
|
855
|
+
this.#refreshes.set(account.accountId, refresh);
|
|
856
|
+
return refresh;
|
|
857
|
+
}
|
|
858
|
+
#encryptionKey() {
|
|
859
|
+
return this.#options.encryptionKey ?? process.env.MASTRA_ENCRYPTION_KEY;
|
|
860
|
+
}
|
|
861
|
+
#encrypt(value) {
|
|
862
|
+
const key = this.#encryptionKey();
|
|
863
|
+
if (!key && !this.#warnedPlaintext) {
|
|
864
|
+
this.#warnedPlaintext = true;
|
|
865
|
+
this.mastra?.getLogger()?.warn("[Ring] Storing Ring tokens WITHOUT encryption. Set `encryptionKey` on RingSignals or MASTRA_ENCRYPTION_KEY to encrypt them at rest.");
|
|
866
|
+
}
|
|
867
|
+
return key ? encrypt(value, key) : value;
|
|
868
|
+
}
|
|
869
|
+
#decrypt(value) {
|
|
870
|
+
const key = this.#encryptionKey();
|
|
871
|
+
if (!isEncrypted(value)) return value;
|
|
872
|
+
if (!key) throw new Error("[Ring] The stored Ring tokens are encrypted, but no encryption key is configured. Set `encryptionKey` on RingSignals or MASTRA_ENCRYPTION_KEY.");
|
|
873
|
+
return decrypt(value, key);
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* A signed link to the media route, or `undefined` when `baseUrl` isn't set. Ring media needs the account's
|
|
877
|
+
* tokens to download, so links point at this server, which fetches the media from Ring when opened.
|
|
878
|
+
*/
|
|
879
|
+
#mediaUrl(kind, deviceId, timestamp) {
|
|
880
|
+
this.#assertConfigured();
|
|
881
|
+
const baseUrl = this.#options.baseUrl ?? process.env.RING_BASE_URL;
|
|
882
|
+
if (!baseUrl) return void 0;
|
|
883
|
+
const path = `${kind}/${deviceId}/${timestamp}`;
|
|
884
|
+
const expires = Date.now() + (this.#options.mediaUrlTtlMs ?? DEFAULT_MEDIA_URL_TTL_MS);
|
|
885
|
+
const signature = signMediaPath(this.#mediaKey, path, expires);
|
|
886
|
+
return `${baseUrl.replace(/\/$/, "")}${this.#routePrefix}/media/${path}?expires=${expires}&signature=${signature}`;
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Media is cached briefly so a tool call and the link it returns share one download, and so every
|
|
890
|
+
* byte-range request a video player makes reads the same file instead of downloading the clip again.
|
|
891
|
+
*/
|
|
892
|
+
#cachedMedia(key, download) {
|
|
893
|
+
const now = Date.now();
|
|
894
|
+
for (const [cachedKey, entry] of this.#mediaCache) if (entry.expiresAt <= now) this.#mediaCache.delete(cachedKey);
|
|
895
|
+
const cached = this.#mediaCache.get(key);
|
|
896
|
+
if (cached) return cached.data;
|
|
897
|
+
const data = download().then((media) => {
|
|
898
|
+
if (!media) this.#mediaCache.delete(key);
|
|
899
|
+
return media;
|
|
900
|
+
}, (error) => {
|
|
901
|
+
this.#mediaCache.delete(key);
|
|
902
|
+
throw error;
|
|
903
|
+
});
|
|
904
|
+
this.#mediaCache.set(key, {
|
|
905
|
+
data,
|
|
906
|
+
expiresAt: now + MEDIA_CACHE_TTL_MS
|
|
907
|
+
});
|
|
908
|
+
while (this.#mediaCache.size > MEDIA_CACHE_MAX_ENTRIES) {
|
|
909
|
+
const oldest = this.#mediaCache.keys().next().value;
|
|
910
|
+
if (oldest === void 0) break;
|
|
911
|
+
this.#mediaCache.delete(oldest);
|
|
912
|
+
}
|
|
913
|
+
return data;
|
|
914
|
+
}
|
|
915
|
+
#getSnapshot(deviceId, timestamp) {
|
|
916
|
+
return this.#cachedMedia(`snapshot:${deviceId}:${timestamp}`, () => this.#downloadSnapshot(deviceId, timestamp));
|
|
917
|
+
}
|
|
918
|
+
#getClip(deviceId, timestamp) {
|
|
919
|
+
return this.#cachedMedia(`clip:${deviceId}:${timestamp}`, () => this.#downloadClip(deviceId, timestamp));
|
|
920
|
+
}
|
|
921
|
+
async #downloadSnapshot(deviceId, timestamp) {
|
|
922
|
+
const endTimestamp = Math.min(timestamp + SNAPSHOT_WINDOW_MS, Date.now() + SNAPSHOT_WINDOW_MS);
|
|
923
|
+
const waitMs = endTimestamp - Date.now();
|
|
924
|
+
if (waitMs > 0) await sleep(waitMs);
|
|
925
|
+
const auth = await this.#getAuth(deviceId);
|
|
926
|
+
const afterEvent = await this.#api.downloadLatestImage(auth, deviceId, timestamp, endTimestamp);
|
|
927
|
+
if (afterEvent) return afterEvent;
|
|
928
|
+
for (const lookBack of SNAPSHOT_LOOK_BACK_MS) {
|
|
929
|
+
const beforeEvent = await this.#api.downloadLatestImage(auth, deviceId, timestamp - lookBack, endTimestamp);
|
|
930
|
+
if (beforeEvent) return beforeEvent;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
async #downloadClip(deviceId, timestamp) {
|
|
934
|
+
const clipOptions = this.#clipOptions() ?? {
|
|
935
|
+
audio: true,
|
|
936
|
+
durationMs: DEFAULT_CLIP_DURATION_MS,
|
|
937
|
+
processingTimeoutMs: DEFAULT_CLIP_PROCESSING_TIMEOUT_MS
|
|
938
|
+
};
|
|
939
|
+
const deadline = Date.now() + clipOptions.processingTimeoutMs;
|
|
940
|
+
let partial;
|
|
941
|
+
while (true) {
|
|
942
|
+
const response = await this.#api.downloadClip(await this.#getAuth(deviceId), deviceId, timestamp, clipOptions.durationMs, clipOptions.audio);
|
|
943
|
+
if (response.status === 200) return Buffer.from(await response.arrayBuffer());
|
|
944
|
+
if (response.status === 206) partial = Buffer.from(await response.arrayBuffer());
|
|
945
|
+
else if (![416, 425].includes(response.status)) return partial;
|
|
946
|
+
if (Date.now() > deadline) return partial;
|
|
947
|
+
await sleep(CLIP_RETRY_MS);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
exports.DEFAULT_RING_EVENTS = DEFAULT_RING_EVENTS;
|
|
952
|
+
exports.DEFAULT_RING_INSTRUCTIONS = DEFAULT_RING_INSTRUCTIONS;
|
|
953
|
+
exports.RingApiClient = RingApiClient;
|
|
954
|
+
exports.RingApiError = RingApiError;
|
|
955
|
+
exports.RingSignals = RingSignals;
|
|
956
|
+
exports.buildRingInstructions = buildRingInstructions;
|
|
957
|
+
|
|
958
|
+
//# sourceMappingURL=index.cjs.map
|