@mentra/sdk 1.1.19
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 +102 -0
- package/dist/constants/index.d.ts +14 -0
- package/dist/constants/index.d.ts.map +1 -0
- package/dist/constants/index.js +16 -0
- package/dist/examples/rtmp-streaming-example.d.ts +2 -0
- package/dist/examples/rtmp-streaming-example.d.ts.map +1 -0
- package/dist/examples/rtmp-streaming-example.js +102 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +33 -0
- package/dist/logging/logger.d.ts +3 -0
- package/dist/logging/logger.d.ts.map +1 -0
- package/dist/logging/logger.js +79 -0
- package/dist/tpa/index.d.ts +6 -0
- package/dist/tpa/index.d.ts.map +1 -0
- package/dist/tpa/index.js +24 -0
- package/dist/tpa/server/index.d.ts +193 -0
- package/dist/tpa/server/index.d.ts.map +1 -0
- package/dist/tpa/server/index.js +436 -0
- package/dist/tpa/session/api-client.d.ts +49 -0
- package/dist/tpa/session/api-client.d.ts.map +1 -0
- package/dist/tpa/session/api-client.js +101 -0
- package/dist/tpa/session/dashboard.d.ts +52 -0
- package/dist/tpa/session/dashboard.d.ts.map +1 -0
- package/dist/tpa/session/dashboard.js +149 -0
- package/dist/tpa/session/events.d.ts +178 -0
- package/dist/tpa/session/events.d.ts.map +1 -0
- package/dist/tpa/session/events.js +294 -0
- package/dist/tpa/session/index.d.ts +391 -0
- package/dist/tpa/session/index.d.ts.map +1 -0
- package/dist/tpa/session/index.js +1452 -0
- package/dist/tpa/session/layouts.d.ts +150 -0
- package/dist/tpa/session/layouts.d.ts.map +1 -0
- package/dist/tpa/session/layouts.js +282 -0
- package/dist/tpa/session/modules/streaming.d.ts +100 -0
- package/dist/tpa/session/modules/streaming.d.ts.map +1 -0
- package/dist/tpa/session/modules/streaming.js +270 -0
- package/dist/tpa/session/settings.d.ts +202 -0
- package/dist/tpa/session/settings.d.ts.map +1 -0
- package/dist/tpa/session/settings.js +361 -0
- package/dist/tpa/token/index.d.ts +7 -0
- package/dist/tpa/token/index.d.ts.map +1 -0
- package/dist/tpa/token/index.js +22 -0
- package/dist/tpa/token/utils.d.ts +69 -0
- package/dist/tpa/token/utils.d.ts.map +1 -0
- package/dist/tpa/token/utils.js +144 -0
- package/dist/tpa/webview/index.d.ts +47 -0
- package/dist/tpa/webview/index.d.ts.map +1 -0
- package/dist/tpa/webview/index.js +344 -0
- package/dist/types/dashboard/index.d.ts +128 -0
- package/dist/types/dashboard/index.d.ts.map +1 -0
- package/dist/types/dashboard/index.js +12 -0
- package/dist/types/enums.d.ts +57 -0
- package/dist/types/enums.d.ts.map +1 -0
- package/dist/types/enums.js +72 -0
- package/dist/types/index.d.ts +38 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +87 -0
- package/dist/types/layouts.d.ts +51 -0
- package/dist/types/layouts.d.ts.map +1 -0
- package/dist/types/layouts.js +3 -0
- package/dist/types/message-types.d.ts +109 -0
- package/dist/types/message-types.d.ts.map +1 -0
- package/dist/types/message-types.js +189 -0
- package/dist/types/messages/base.d.ts +12 -0
- package/dist/types/messages/base.d.ts.map +1 -0
- package/dist/types/messages/base.js +3 -0
- package/dist/types/messages/cloud-to-glasses.d.ts +126 -0
- package/dist/types/messages/cloud-to-glasses.d.ts.map +1 -0
- package/dist/types/messages/cloud-to-glasses.js +60 -0
- package/dist/types/messages/cloud-to-tpa.d.ts +228 -0
- package/dist/types/messages/cloud-to-tpa.d.ts.map +1 -0
- package/dist/types/messages/cloud-to-tpa.js +61 -0
- package/dist/types/messages/glasses-to-cloud.d.ts +219 -0
- package/dist/types/messages/glasses-to-cloud.d.ts.map +1 -0
- package/dist/types/messages/glasses-to-cloud.js +88 -0
- package/dist/types/messages/tpa-to-cloud.d.ts +146 -0
- package/dist/types/messages/tpa-to-cloud.d.ts.map +1 -0
- package/dist/types/messages/tpa-to-cloud.js +67 -0
- package/dist/types/models.d.ts +165 -0
- package/dist/types/models.d.ts.map +1 -0
- package/dist/types/models.js +84 -0
- package/dist/types/rtmp-stream.d.ts +68 -0
- package/dist/types/rtmp-stream.d.ts.map +1 -0
- package/dist/types/rtmp-stream.js +3 -0
- package/dist/types/streams.d.ts +138 -0
- package/dist/types/streams.d.ts.map +1 -0
- package/dist/types/streams.js +251 -0
- package/dist/types/token.d.ts +41 -0
- package/dist/types/token.d.ts.map +1 -0
- package/dist/types/token.js +7 -0
- package/dist/types/user-session.d.ts +73 -0
- package/dist/types/user-session.d.ts.map +1 -0
- package/dist/types/user-session.js +17 -0
- package/dist/types/webhooks.d.ts +107 -0
- package/dist/types/webhooks.d.ts.map +1 -0
- package/dist/types/webhooks.js +55 -0
- package/dist/utils/resource-tracker.d.ts +94 -0
- package/dist/utils/resource-tracker.d.ts.map +1 -0
- package/dist/utils/resource-tracker.js +153 -0
- package/package.json +50 -0
@@ -0,0 +1,361 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
exports.SettingsManager = void 0;
|
7
|
+
/**
|
8
|
+
* 🔧 Settings Manager Module
|
9
|
+
*
|
10
|
+
* Manages TPA settings with automatic synchronization and change notifications.
|
11
|
+
* Provides type-safe access to settings with default values.
|
12
|
+
*/
|
13
|
+
const events_1 = __importDefault(require("events"));
|
14
|
+
const api_client_1 = require("./api-client");
|
15
|
+
// import { logger } from '@mentra/utils'; // Ensure logger is available
|
16
|
+
// Note(Isaiah): Let's not import @mentra/utils in the SDK to avoid circular dependencies. Also i'm deprecating it in favor of the new logging system.
|
17
|
+
const logger_1 = require("../../logging/logger"); // Adjust import path as needed
|
18
|
+
/**
|
19
|
+
* Internal event names
|
20
|
+
*/
|
21
|
+
var SettingsEvents;
|
22
|
+
(function (SettingsEvents) {
|
23
|
+
SettingsEvents["CHANGE"] = "settings:change";
|
24
|
+
SettingsEvents["VALUE_CHANGE"] = "settings:value:";
|
25
|
+
})(SettingsEvents || (SettingsEvents = {}));
|
26
|
+
/**
|
27
|
+
* 🔧 Settings Manager
|
28
|
+
*
|
29
|
+
* Provides a type-safe interface for accessing and reacting to TPA settings.
|
30
|
+
* Automatically synchronizes with AugmentOS Cloud.
|
31
|
+
*/
|
32
|
+
class SettingsManager {
|
33
|
+
/**
|
34
|
+
* Create a new settings manager
|
35
|
+
*
|
36
|
+
* @param initialSettings Initial settings values (if available)
|
37
|
+
* @param packageName Package name for the TPA
|
38
|
+
* @param wsUrl WebSocket URL (for deriving HTTP API URL)
|
39
|
+
* @param userId User ID (for authenticated requests)
|
40
|
+
* @param subscribeFn Optional function to call to subscribe to streams
|
41
|
+
*/
|
42
|
+
constructor(initialSettings = [], packageName, wsUrl, userId, subscribeFn // Added parameter
|
43
|
+
) {
|
44
|
+
// Current settings values
|
45
|
+
this.settings = [];
|
46
|
+
// Event emitter for change notifications
|
47
|
+
this.emitter = new events_1.default();
|
48
|
+
// --- AugmentOS settings event system ---
|
49
|
+
this.augmentosSettings = {};
|
50
|
+
this.augmentosEmitter = new events_1.default();
|
51
|
+
this.settings = [...initialSettings];
|
52
|
+
this.subscribeFn = subscribeFn; // Store the subscribe function
|
53
|
+
// Create API client if we have enough information
|
54
|
+
if (packageName) {
|
55
|
+
this.apiClient = new api_client_1.ApiClient(packageName, wsUrl, userId);
|
56
|
+
}
|
57
|
+
}
|
58
|
+
/**
|
59
|
+
* Configure the API client
|
60
|
+
*
|
61
|
+
* @param packageName Package name for the TPA
|
62
|
+
* @param wsUrl WebSocket URL
|
63
|
+
* @param userId User ID
|
64
|
+
*/
|
65
|
+
configureApiClient(packageName, wsUrl, userId) {
|
66
|
+
if (!this.apiClient) {
|
67
|
+
this.apiClient = new api_client_1.ApiClient(packageName, wsUrl, userId);
|
68
|
+
}
|
69
|
+
else {
|
70
|
+
this.apiClient.setWebSocketUrl(wsUrl);
|
71
|
+
this.apiClient.setUserId(userId);
|
72
|
+
}
|
73
|
+
}
|
74
|
+
/**
|
75
|
+
* Update the current settings
|
76
|
+
* This is called internally when settings are loaded or changed
|
77
|
+
*
|
78
|
+
* @param newSettings New settings values
|
79
|
+
* @returns Map of changed settings
|
80
|
+
*/
|
81
|
+
updateSettings(newSettings) {
|
82
|
+
const changes = {};
|
83
|
+
// Copy the new settings
|
84
|
+
const updatedSettings = [...newSettings];
|
85
|
+
// Detect changes comparing old and new settings
|
86
|
+
for (const newSetting of updatedSettings) {
|
87
|
+
const oldSetting = this.settings.find(s => s.key === newSetting.key);
|
88
|
+
// Skip if value hasn't changed
|
89
|
+
if (oldSetting && this.areEqual(oldSetting.value, newSetting.value)) {
|
90
|
+
continue;
|
91
|
+
}
|
92
|
+
// Record change
|
93
|
+
changes[newSetting.key] = {
|
94
|
+
oldValue: oldSetting?.value,
|
95
|
+
newValue: newSetting.value
|
96
|
+
};
|
97
|
+
}
|
98
|
+
// Check for removed settings
|
99
|
+
for (const oldSetting of this.settings) {
|
100
|
+
const stillExists = updatedSettings.some(s => s.key === oldSetting.key);
|
101
|
+
if (!stillExists) {
|
102
|
+
changes[oldSetting.key] = {
|
103
|
+
oldValue: oldSetting.value,
|
104
|
+
newValue: undefined
|
105
|
+
};
|
106
|
+
}
|
107
|
+
}
|
108
|
+
// If there are changes, update the settings and emit events
|
109
|
+
if (Object.keys(changes).length > 0) {
|
110
|
+
this.settings = updatedSettings;
|
111
|
+
this.emitChanges(changes);
|
112
|
+
}
|
113
|
+
return changes;
|
114
|
+
}
|
115
|
+
/**
|
116
|
+
* Check if two setting values are equal
|
117
|
+
*
|
118
|
+
* @param a First value
|
119
|
+
* @param b Second value
|
120
|
+
* @returns True if the values are equal
|
121
|
+
*/
|
122
|
+
areEqual(a, b) {
|
123
|
+
// Simple equality check - for objects, this won't do a deep equality check
|
124
|
+
// but for most setting values (strings, numbers, booleans) it works
|
125
|
+
return a === b;
|
126
|
+
}
|
127
|
+
/**
|
128
|
+
* Emit change events for updated settings
|
129
|
+
*
|
130
|
+
* @param changes Map of changed settings
|
131
|
+
*/
|
132
|
+
emitChanges(changes) {
|
133
|
+
// Emit the general change event
|
134
|
+
this.emitter.emit(SettingsEvents.CHANGE, changes);
|
135
|
+
// Emit individual value change events
|
136
|
+
for (const [key, change] of Object.entries(changes)) {
|
137
|
+
this.emitter.emit(`${SettingsEvents.VALUE_CHANGE}${key}`, change.newValue, change.oldValue);
|
138
|
+
}
|
139
|
+
}
|
140
|
+
/**
|
141
|
+
* 🔄 Listen for changes to any setting
|
142
|
+
*
|
143
|
+
* @param handler Function to call when settings change
|
144
|
+
* @returns Function to remove the listener
|
145
|
+
*
|
146
|
+
* @example
|
147
|
+
* ```typescript
|
148
|
+
* settings.onChange((changes) => {
|
149
|
+
* console.log('Settings changed:', changes);
|
150
|
+
* });
|
151
|
+
* ```
|
152
|
+
*/
|
153
|
+
onChange(handler) {
|
154
|
+
this.emitter.on(SettingsEvents.CHANGE, handler);
|
155
|
+
return () => this.emitter.off(SettingsEvents.CHANGE, handler);
|
156
|
+
}
|
157
|
+
/**
|
158
|
+
* 🔄 Listen for changes to a specific setting
|
159
|
+
*
|
160
|
+
* @param key Setting key to monitor
|
161
|
+
* @param handler Function to call when the setting changes
|
162
|
+
* @returns Function to remove the listener
|
163
|
+
*
|
164
|
+
* @example
|
165
|
+
* ```typescript
|
166
|
+
* settings.onValueChange('transcribe_language', (newValue, oldValue) => {
|
167
|
+
* console.log(`Language changed from ${oldValue} to ${newValue}`);
|
168
|
+
* });
|
169
|
+
* ```
|
170
|
+
*/
|
171
|
+
onValueChange(key, handler) {
|
172
|
+
const eventName = `${SettingsEvents.VALUE_CHANGE}${key}`;
|
173
|
+
this.emitter.on(eventName, handler);
|
174
|
+
return () => this.emitter.off(eventName, handler);
|
175
|
+
}
|
176
|
+
/**
|
177
|
+
* 🔍 Check if a setting exists
|
178
|
+
*
|
179
|
+
* @param key Setting key to check
|
180
|
+
* @returns True if the setting exists
|
181
|
+
*/
|
182
|
+
has(key) {
|
183
|
+
return this.settings.some(s => s.key === key);
|
184
|
+
}
|
185
|
+
/**
|
186
|
+
* 🔍 Get all settings
|
187
|
+
*
|
188
|
+
* @returns Copy of all settings
|
189
|
+
*/
|
190
|
+
getAll() {
|
191
|
+
return [...this.settings];
|
192
|
+
}
|
193
|
+
/**
|
194
|
+
* 🔍 Get a setting value with type safety
|
195
|
+
*
|
196
|
+
* @param key Setting key to get
|
197
|
+
* @param defaultValue Default value if setting doesn't exist or is undefined
|
198
|
+
* @returns Setting value or default value
|
199
|
+
*
|
200
|
+
* @example
|
201
|
+
* ```typescript
|
202
|
+
* const lineWidth = settings.get<number>('line_width', 30);
|
203
|
+
* const language = settings.get<string>('transcribe_language', 'English');
|
204
|
+
* ```
|
205
|
+
*/
|
206
|
+
get(key, defaultValue) {
|
207
|
+
const setting = this.settings.find(s => s.key === key);
|
208
|
+
if (setting && setting.value !== undefined) {
|
209
|
+
return setting.value;
|
210
|
+
}
|
211
|
+
return defaultValue;
|
212
|
+
}
|
213
|
+
/**
|
214
|
+
* 🎛️ Get an AugmentOS system setting value with optional default
|
215
|
+
*
|
216
|
+
* @param key AugmentOS setting key (e.g., 'metricSystemEnabled', 'brightness')
|
217
|
+
* @param defaultValue Default value to return if the setting is not found
|
218
|
+
* @returns The setting value or the default value
|
219
|
+
*
|
220
|
+
* @example
|
221
|
+
* ```typescript
|
222
|
+
* const isMetric = settings.getAugmentOS<boolean>('metricSystemEnabled', false);
|
223
|
+
* const brightness = settings.getAugmentOS<number>('brightness', 50);
|
224
|
+
* ```
|
225
|
+
*/
|
226
|
+
getAugmentOS(key, defaultValue) {
|
227
|
+
const value = this.augmentosSettings[key];
|
228
|
+
if (value !== undefined) {
|
229
|
+
return value;
|
230
|
+
}
|
231
|
+
return defaultValue;
|
232
|
+
}
|
233
|
+
/**
|
234
|
+
* 🔍 Find a setting by key
|
235
|
+
*
|
236
|
+
* @param key Setting key to find
|
237
|
+
* @returns Setting object or undefined
|
238
|
+
*/
|
239
|
+
getSetting(key) {
|
240
|
+
return this.settings.find(s => s.key === key);
|
241
|
+
}
|
242
|
+
/**
|
243
|
+
* 🔄 Fetch settings from the cloud
|
244
|
+
* This is generally not needed since settings are automatically kept in sync,
|
245
|
+
* but can be used to force a refresh if needed.
|
246
|
+
*
|
247
|
+
* @returns Promise that resolves to the updated settings
|
248
|
+
* @throws Error if the API client is not configured or the request fails
|
249
|
+
*/
|
250
|
+
async fetch() {
|
251
|
+
if (!this.apiClient) {
|
252
|
+
throw new Error('Settings API client is not configured');
|
253
|
+
}
|
254
|
+
try {
|
255
|
+
const newSettings = await this.apiClient.fetchSettings();
|
256
|
+
this.updateSettings(newSettings);
|
257
|
+
return this.settings;
|
258
|
+
}
|
259
|
+
catch (error) {
|
260
|
+
console.error('Error fetching settings:', error);
|
261
|
+
throw error;
|
262
|
+
}
|
263
|
+
}
|
264
|
+
/**
|
265
|
+
* 🎛️ Listen for changes to a specific AugmentOS setting (e.g., metricSystemEnabled)
|
266
|
+
*
|
267
|
+
* @param key The augmentosSettings key to listen for (e.g., 'metricSystemEnabled')
|
268
|
+
* @param handler Function to call when the value changes
|
269
|
+
* @returns Function to remove the listener
|
270
|
+
*
|
271
|
+
* @example
|
272
|
+
* ```typescript
|
273
|
+
* settings.onAugmentOSChange('metricSystemEnabled', (isMetric, wasMetric) => {
|
274
|
+
* console.log(`Units changed: ${wasMetric ? 'metric' : 'imperial'} → ${isMetric ? 'metric' : 'imperial'}`);
|
275
|
+
* });
|
276
|
+
* ```
|
277
|
+
*/
|
278
|
+
onAugmentOSChange(key, handler) {
|
279
|
+
return this.onAugmentosSettingChange(key, handler);
|
280
|
+
}
|
281
|
+
/**
|
282
|
+
* Listen for changes to a specific AugmentOS setting (e.g., metricSystemEnabled)
|
283
|
+
* This is a convenience wrapper for onValueChange for well-known augmentosSettings keys.
|
284
|
+
* @param key The augmentosSettings key to listen for (e.g., 'metricSystemEnabled')
|
285
|
+
* @param handler Function to call when the value changes
|
286
|
+
* @returns Function to remove the listener
|
287
|
+
* @deprecated Use onAugmentOSChange instead
|
288
|
+
*/
|
289
|
+
onAugmentosSettingsChange(key, handler) {
|
290
|
+
return this.onAugmentosSettingChange(key, handler);
|
291
|
+
}
|
292
|
+
/**
|
293
|
+
* Update the current AugmentOS settings
|
294
|
+
* Compares new and old values, emits per-key events, and updates stored values.
|
295
|
+
* @param newSettings The new AugmentOS settings object
|
296
|
+
*/
|
297
|
+
updateAugmentosSettings(newSettings) {
|
298
|
+
const oldSettings = this.augmentosSettings;
|
299
|
+
logger_1.logger.debug(`[SettingsManager] Updating AugmentOS settings. New settings:`, newSettings);
|
300
|
+
for (const key of Object.keys(newSettings)) {
|
301
|
+
const oldValue = oldSettings[key];
|
302
|
+
const newValue = newSettings[key];
|
303
|
+
if (oldValue !== newValue) {
|
304
|
+
logger_1.logger.info(`[SettingsManager] AugmentOS setting '${key}' changed: ${oldValue} -> ${newValue}. Emitting event.`);
|
305
|
+
this.augmentosEmitter.emit(`augmentos:value:${key}`, newValue, oldValue);
|
306
|
+
}
|
307
|
+
}
|
308
|
+
// Also handle keys that might have been removed from newSettings but existed in oldSettings
|
309
|
+
for (const key of Object.keys(oldSettings)) {
|
310
|
+
if (!(key in newSettings)) {
|
311
|
+
logger_1.logger.info(`[SettingsManager] AugmentOS setting '${key}' removed. Old value: ${oldSettings[key]}. Emitting event with undefined newValue.`);
|
312
|
+
this.augmentosEmitter.emit(`augmentos:value:${key}`, undefined, oldSettings[key]);
|
313
|
+
}
|
314
|
+
}
|
315
|
+
this.augmentosSettings = { ...newSettings };
|
316
|
+
logger_1.logger.debug(`[SettingsManager] Finished updating AugmentOS settings. Current state:`, this.augmentosSettings);
|
317
|
+
}
|
318
|
+
/**
|
319
|
+
* Subscribe to changes for a specific AugmentOS setting (e.g., 'metricSystemEnabled')
|
320
|
+
* @param key The AugmentOS setting key to listen for
|
321
|
+
* @param handler Function to call when the value changes (newValue, oldValue)
|
322
|
+
* @returns Function to remove the listener
|
323
|
+
*/
|
324
|
+
onAugmentosSettingChange(key, handler) {
|
325
|
+
const eventName = `augmentos:value:${key}`;
|
326
|
+
logger_1.logger.info(`[SettingsManager] Registering handler for AugmentOS setting '${key}' on event '${eventName}'.`);
|
327
|
+
this.augmentosEmitter.on(eventName, (...args) => {
|
328
|
+
logger_1.logger.info(`[SettingsManager] AugmentOS setting '${key}' event fired. Args:`, args);
|
329
|
+
handler(...args);
|
330
|
+
});
|
331
|
+
if (this.subscribeFn) {
|
332
|
+
const subscriptionKey = `augmentos:${key}`;
|
333
|
+
logger_1.logger.info(`[SettingsManager] Calling subscribeFn for stream '${subscriptionKey}'.`);
|
334
|
+
this.subscribeFn([subscriptionKey])
|
335
|
+
.then(() => {
|
336
|
+
logger_1.logger.info(`[SettingsManager] subscribeFn resolved for stream '${subscriptionKey}'.`);
|
337
|
+
})
|
338
|
+
.catch(err => {
|
339
|
+
logger_1.logger.error(`[SettingsManager] subscribeFn failed for stream '${subscriptionKey}':`, err);
|
340
|
+
});
|
341
|
+
}
|
342
|
+
else {
|
343
|
+
logger_1.logger.warn(`[SettingsManager] 'subscribeFn' not provided. Cannot auto-subscribe for AugmentOS setting '${key}'. Manual TPA subscription might be required.`);
|
344
|
+
}
|
345
|
+
return () => {
|
346
|
+
logger_1.logger.info(`[SettingsManager] Unregistering handler for AugmentOS setting '${key}' from event '${eventName}'.`);
|
347
|
+
this.augmentosEmitter.off(eventName, handler);
|
348
|
+
};
|
349
|
+
}
|
350
|
+
/**
|
351
|
+
* Get the current value of an AugmentOS setting
|
352
|
+
*/
|
353
|
+
getAugmentosSetting(key, defaultValue) {
|
354
|
+
console.log(`[SettingsManager] Getting AugmentOS setting '${key}' with settings:`, this.augmentosSettings);
|
355
|
+
if (key in this.augmentosSettings) {
|
356
|
+
return this.augmentosSettings[key];
|
357
|
+
}
|
358
|
+
return defaultValue;
|
359
|
+
}
|
360
|
+
}
|
361
|
+
exports.SettingsManager = SettingsManager;
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/tpa/token/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,cAAc,SAAS,CAAC"}
|
@@ -0,0 +1,22 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
+
if (k2 === undefined) k2 = k;
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
7
|
+
}
|
8
|
+
Object.defineProperty(o, k2, desc);
|
9
|
+
}) : (function(o, m, k, k2) {
|
10
|
+
if (k2 === undefined) k2 = k;
|
11
|
+
o[k2] = m[k];
|
12
|
+
}));
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
15
|
+
};
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
17
|
+
/**
|
18
|
+
* 🔐 TPA Token Module
|
19
|
+
*
|
20
|
+
* Provides utilities for working with TPA tokens.
|
21
|
+
*/
|
22
|
+
__exportStar(require("./utils"), exports);
|
@@ -0,0 +1,69 @@
|
|
1
|
+
import { TpaTokenPayload, TokenValidationResult, TokenConfig } from '../../types/token';
|
2
|
+
/**
|
3
|
+
* Create a TPA token for a user session
|
4
|
+
*
|
5
|
+
* @param payload - Token payload data
|
6
|
+
* @param config - Token configuration
|
7
|
+
* @returns JWT token string
|
8
|
+
*
|
9
|
+
* @example
|
10
|
+
* ```typescript
|
11
|
+
* const token = createToken(
|
12
|
+
* {
|
13
|
+
* userId: 'user123',
|
14
|
+
* packageName: 'org.example.myapp',
|
15
|
+
* sessionId: 'session789'
|
16
|
+
* },
|
17
|
+
* { secretKey: 'your_secret_key' }
|
18
|
+
* );
|
19
|
+
* ```
|
20
|
+
*/
|
21
|
+
export declare function createToken(payload: Omit<TpaTokenPayload, 'iat' | 'exp'>, config: TokenConfig): string;
|
22
|
+
/**
|
23
|
+
* Validate and decode a TPA token
|
24
|
+
*
|
25
|
+
* @param token - JWT token string
|
26
|
+
* @param secretKey - Secret key used for validation
|
27
|
+
* @returns Token validation result
|
28
|
+
*
|
29
|
+
* @example
|
30
|
+
* ```typescript
|
31
|
+
* const result = validateToken('eyJhbGciOiJIUzI1...', 'your_secret_key');
|
32
|
+
* if (result.valid) {
|
33
|
+
* // Use result.payload
|
34
|
+
* }
|
35
|
+
* ```
|
36
|
+
*/
|
37
|
+
export declare function validateToken(token: string, secretKey: string): TokenValidationResult;
|
38
|
+
/**
|
39
|
+
* Generate a webview URL with an embedded TPA token
|
40
|
+
*
|
41
|
+
* @param baseUrl - Base URL of the webview
|
42
|
+
* @param token - JWT token string
|
43
|
+
* @returns Full URL with token parameter
|
44
|
+
*
|
45
|
+
* @example
|
46
|
+
* ```typescript
|
47
|
+
* const url = generateWebviewUrl(
|
48
|
+
* 'https://example.com/webview',
|
49
|
+
* 'eyJhbGciOiJIUzI1...'
|
50
|
+
* );
|
51
|
+
* // Returns: https://example.com/webview?token=eyJhbGciOiJIUzI1...
|
52
|
+
* ```
|
53
|
+
*/
|
54
|
+
export declare function generateWebviewUrl(baseUrl: string, token: string): string;
|
55
|
+
/**
|
56
|
+
* Extract a TPA token from a URL
|
57
|
+
*
|
58
|
+
* @param url - URL string containing a token parameter
|
59
|
+
* @returns Token string or null if not found
|
60
|
+
*
|
61
|
+
* @example
|
62
|
+
* ```typescript
|
63
|
+
* const token = extractTokenFromUrl(
|
64
|
+
* 'https://example.com/webview?token=eyJhbGciOiJIUzI1...'
|
65
|
+
* );
|
66
|
+
* ```
|
67
|
+
*/
|
68
|
+
export declare function extractTokenFromUrl(url: string): string | null;
|
69
|
+
//# sourceMappingURL=utils.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/tpa/token/utils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAOxF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,IAAI,CAAC,eAAe,EAAE,KAAK,GAAG,KAAK,CAAC,EAC7C,MAAM,EAAE,WAAW,GAClB,MAAM,CAMR;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAChB,qBAAqB,CAavB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAIzE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAO9D"}
|
@@ -0,0 +1,144 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
+
if (k2 === undefined) k2 = k;
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
7
|
+
}
|
8
|
+
Object.defineProperty(o, k2, desc);
|
9
|
+
}) : (function(o, m, k, k2) {
|
10
|
+
if (k2 === undefined) k2 = k;
|
11
|
+
o[k2] = m[k];
|
12
|
+
}));
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
15
|
+
}) : function(o, v) {
|
16
|
+
o["default"] = v;
|
17
|
+
});
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
19
|
+
var ownKeys = function(o) {
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
21
|
+
var ar = [];
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
23
|
+
return ar;
|
24
|
+
};
|
25
|
+
return ownKeys(o);
|
26
|
+
};
|
27
|
+
return function (mod) {
|
28
|
+
if (mod && mod.__esModule) return mod;
|
29
|
+
var result = {};
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
31
|
+
__setModuleDefault(result, mod);
|
32
|
+
return result;
|
33
|
+
};
|
34
|
+
})();
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
36
|
+
exports.createToken = createToken;
|
37
|
+
exports.validateToken = validateToken;
|
38
|
+
exports.generateWebviewUrl = generateWebviewUrl;
|
39
|
+
exports.extractTokenFromUrl = extractTokenFromUrl;
|
40
|
+
/**
|
41
|
+
* 🔐 TPA Token Utilities
|
42
|
+
*
|
43
|
+
* Provides utilities for working with TPA tokens.
|
44
|
+
*/
|
45
|
+
const jwt = __importStar(require("jsonwebtoken"));
|
46
|
+
/**
|
47
|
+
* Default token expiration (1 day)
|
48
|
+
*/
|
49
|
+
const DEFAULT_EXPIRATION = 60 * 60 * 24; // seconds * minutes * hours (1 day).
|
50
|
+
/**
|
51
|
+
* Create a TPA token for a user session
|
52
|
+
*
|
53
|
+
* @param payload - Token payload data
|
54
|
+
* @param config - Token configuration
|
55
|
+
* @returns JWT token string
|
56
|
+
*
|
57
|
+
* @example
|
58
|
+
* ```typescript
|
59
|
+
* const token = createToken(
|
60
|
+
* {
|
61
|
+
* userId: 'user123',
|
62
|
+
* packageName: 'org.example.myapp',
|
63
|
+
* sessionId: 'session789'
|
64
|
+
* },
|
65
|
+
* { secretKey: 'your_secret_key' }
|
66
|
+
* );
|
67
|
+
* ```
|
68
|
+
*/
|
69
|
+
function createToken(payload, config) {
|
70
|
+
return jwt.sign(payload, config.secretKey, { expiresIn: config.expiresIn || DEFAULT_EXPIRATION });
|
71
|
+
}
|
72
|
+
/**
|
73
|
+
* Validate and decode a TPA token
|
74
|
+
*
|
75
|
+
* @param token - JWT token string
|
76
|
+
* @param secretKey - Secret key used for validation
|
77
|
+
* @returns Token validation result
|
78
|
+
*
|
79
|
+
* @example
|
80
|
+
* ```typescript
|
81
|
+
* const result = validateToken('eyJhbGciOiJIUzI1...', 'your_secret_key');
|
82
|
+
* if (result.valid) {
|
83
|
+
* // Use result.payload
|
84
|
+
* }
|
85
|
+
* ```
|
86
|
+
*/
|
87
|
+
function validateToken(token, secretKey) {
|
88
|
+
try {
|
89
|
+
const decoded = jwt.verify(token, secretKey);
|
90
|
+
return {
|
91
|
+
valid: true,
|
92
|
+
payload: decoded
|
93
|
+
};
|
94
|
+
}
|
95
|
+
catch (error) {
|
96
|
+
return {
|
97
|
+
valid: false,
|
98
|
+
error: error instanceof Error ? error.message : 'Unknown error'
|
99
|
+
};
|
100
|
+
}
|
101
|
+
}
|
102
|
+
/**
|
103
|
+
* Generate a webview URL with an embedded TPA token
|
104
|
+
*
|
105
|
+
* @param baseUrl - Base URL of the webview
|
106
|
+
* @param token - JWT token string
|
107
|
+
* @returns Full URL with token parameter
|
108
|
+
*
|
109
|
+
* @example
|
110
|
+
* ```typescript
|
111
|
+
* const url = generateWebviewUrl(
|
112
|
+
* 'https://example.com/webview',
|
113
|
+
* 'eyJhbGciOiJIUzI1...'
|
114
|
+
* );
|
115
|
+
* // Returns: https://example.com/webview?token=eyJhbGciOiJIUzI1...
|
116
|
+
* ```
|
117
|
+
*/
|
118
|
+
function generateWebviewUrl(baseUrl, token) {
|
119
|
+
const url = new URL(baseUrl);
|
120
|
+
url.searchParams.append('token', token);
|
121
|
+
return url.toString();
|
122
|
+
}
|
123
|
+
/**
|
124
|
+
* Extract a TPA token from a URL
|
125
|
+
*
|
126
|
+
* @param url - URL string containing a token parameter
|
127
|
+
* @returns Token string or null if not found
|
128
|
+
*
|
129
|
+
* @example
|
130
|
+
* ```typescript
|
131
|
+
* const token = extractTokenFromUrl(
|
132
|
+
* 'https://example.com/webview?token=eyJhbGciOiJIUzI1...'
|
133
|
+
* );
|
134
|
+
* ```
|
135
|
+
*/
|
136
|
+
function extractTokenFromUrl(url) {
|
137
|
+
try {
|
138
|
+
const parsedUrl = new URL(url);
|
139
|
+
return parsedUrl.searchParams.get('token');
|
140
|
+
}
|
141
|
+
catch (error) {
|
142
|
+
return null;
|
143
|
+
}
|
144
|
+
}
|
@@ -0,0 +1,47 @@
|
|
1
|
+
import { Response, NextFunction } from 'express';
|
2
|
+
import { AuthenticatedRequest } from '../../types';
|
3
|
+
/**
|
4
|
+
* Extracts the temporary token from a URL string.
|
5
|
+
* @param url The URL string, typically window.location.href.
|
6
|
+
* @returns The token string or null if not found.
|
7
|
+
*/
|
8
|
+
export declare function extractTempToken(url: string): string | null;
|
9
|
+
/**
|
10
|
+
* Exchanges a temporary token for a user ID with the AugmentOS Cloud.
|
11
|
+
* This should be called from the TPA's backend server.
|
12
|
+
* @param cloudApiUrl The base URL of the AugmentOS Cloud API.
|
13
|
+
* @param tempToken The temporary token obtained from the webview URL.
|
14
|
+
* @param apiKey Your TPA's secret API key.
|
15
|
+
* @returns A Promise that resolves with an object containing the userId.
|
16
|
+
* @throws Throws an error if the exchange fails (e.g., invalid token, expired, network error).
|
17
|
+
*/
|
18
|
+
export declare function exchangeToken(cloudApiUrl: string, tempToken: string, apiKey: string, packageName: string): Promise<{
|
19
|
+
userId: string;
|
20
|
+
}>;
|
21
|
+
/**
|
22
|
+
* Express middleware for automatically handling the token exchange.
|
23
|
+
* Assumes API key and Cloud URL are available (e.g., via environment variables).
|
24
|
+
* Adds `req.authUserId` if successful.
|
25
|
+
*
|
26
|
+
* @param options Configuration options.
|
27
|
+
* @param options.cloudApiUrl The base URL of the AugmentOS Cloud API.
|
28
|
+
* @param options.apiKey Your TPA's secret API key.
|
29
|
+
* @param options.tokenQueryParam The name of the query parameter containing the token (default: 'aos_temp_token').
|
30
|
+
* @param options.cookieName The name of the cookie to store the session token (default: 'aos_session').
|
31
|
+
* @param options.cookieSecret Secret key used to sign the session cookie. MUST be provided and kept secure.
|
32
|
+
* @param options.cookieOptions Options for the session cookie (default: { httpOnly: true, secure: process.env.NODE_ENV === 'production' }).
|
33
|
+
*/
|
34
|
+
export declare function createAuthMiddleware(options: {
|
35
|
+
apiKey: string;
|
36
|
+
packageName: string;
|
37
|
+
cookieName?: string;
|
38
|
+
cookieSecret: string;
|
39
|
+
cookieOptions?: {
|
40
|
+
httpOnly?: boolean;
|
41
|
+
secure?: boolean;
|
42
|
+
maxAge?: number;
|
43
|
+
sameSite?: boolean | 'lax' | 'strict' | 'none';
|
44
|
+
path?: string;
|
45
|
+
};
|
46
|
+
}): (req: AuthenticatedRequest, res: Response, next: NextFunction) => Promise<void>;
|
47
|
+
//# sourceMappingURL=index.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/tpa/webview/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAUnD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAQ3D;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CACjC,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAmC7B;AAsID;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE;QACd,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,MAAM,CAAC,EAAE,OAAO,CAAC;QACjB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,OAAO,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;QAC/C,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,CAAC;CACH,IAuBe,KAAK,oBAAoB,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,mBAkG3E"}
|