@peers-app/peers-sdk 0.7.2 → 0.7.5

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.
Files changed (58) hide show
  1. package/dist/context/data-context.d.ts +1 -1
  2. package/dist/context/data-context.js +2 -3
  3. package/dist/context/user-context-singleton.js +13 -31
  4. package/dist/context/user-context.d.ts +2 -5
  5. package/dist/context/user-context.js +20 -15
  6. package/dist/data/assistants.d.ts +1 -1
  7. package/dist/data/change-tracking.d.ts +16 -16
  8. package/dist/data/channels.d.ts +1 -1
  9. package/dist/data/data-locks.d.ts +2 -2
  10. package/dist/data/data-locks.test.js +3 -0
  11. package/dist/data/devices.d.ts +4 -4
  12. package/dist/data/embeddings.d.ts +1 -1
  13. package/dist/data/group-members.d.ts +7 -4
  14. package/dist/data/group-members.js +98 -32
  15. package/dist/data/groups.d.ts +7 -3
  16. package/dist/data/groups.js +91 -30
  17. package/dist/data/index.d.ts +1 -0
  18. package/dist/data/index.js +1 -0
  19. package/dist/data/knowledge/knowledge-frames.d.ts +1 -1
  20. package/dist/data/knowledge/knowledge-links.d.ts +1 -1
  21. package/dist/data/knowledge/knowledge-values.d.ts +1 -1
  22. package/dist/data/knowledge/peer-types.d.ts +1 -1
  23. package/dist/data/knowledge/predicates.d.ts +1 -1
  24. package/dist/data/messages.d.ts +4 -4
  25. package/dist/data/orm/client-proxy.data-source.js +8 -18
  26. package/dist/data/orm/decorators.d.ts +1 -1
  27. package/dist/data/orm/decorators.js +7 -6
  28. package/dist/data/packages.d.ts +2 -1
  29. package/dist/data/packages.js +90 -40
  30. package/dist/data/peer-events/peer-event-handlers.d.ts +1 -1
  31. package/dist/data/peer-events/peer-event-types.d.ts +1 -1
  32. package/dist/data/persistent-vars.js +124 -119
  33. package/dist/data/tool-tests.d.ts +1 -1
  34. package/dist/data/tools.d.ts +1 -1
  35. package/dist/data/user-permissions.test.js +7 -10
  36. package/dist/data/user-trust-levels.d.ts +42 -0
  37. package/dist/data/user-trust-levels.js +60 -0
  38. package/dist/data/users.d.ts +7 -7
  39. package/dist/data/users.js +86 -27
  40. package/dist/data/workflow-logs.d.ts +1 -1
  41. package/dist/data/workflow-runs.js +1 -1
  42. package/dist/data/workflows.d.ts +1 -1
  43. package/dist/device/connection.js +2 -2
  44. package/dist/device/get-trust-level.js +10 -6
  45. package/dist/index.d.ts +1 -0
  46. package/dist/index.js +1 -0
  47. package/dist/logging/console-logger.d.ts +10 -0
  48. package/dist/logging/console-logger.js +206 -0
  49. package/dist/logging/console-logs.table.d.ts +48 -0
  50. package/dist/logging/console-logs.table.js +140 -0
  51. package/dist/logging/index.d.ts +2 -0
  52. package/dist/logging/index.js +18 -0
  53. package/dist/rpc-types.d.ts +0 -11
  54. package/dist/rpc-types.js +0 -8
  55. package/dist/types/peer-device.d.ts +10 -0
  56. package/dist/users.query.d.ts +3 -1
  57. package/dist/users.query.js +39 -11
  58. package/package.json +1 -1
@@ -1,11 +1,46 @@
1
1
  "use strict";
2
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
3
+ var useValue = arguments.length > 2;
4
+ for (var i = 0; i < initializers.length; i++) {
5
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
6
+ }
7
+ return useValue ? value : void 0;
8
+ };
9
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
10
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
11
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
12
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
13
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
14
+ var _, done = false;
15
+ for (var i = decorators.length - 1; i >= 0; i--) {
16
+ var context = {};
17
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
18
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
19
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
20
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
21
+ if (kind === "accessor") {
22
+ if (result === void 0) continue;
23
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
24
+ if (_ = accept(result.get)) descriptor.get = _;
25
+ if (_ = accept(result.set)) descriptor.set = _;
26
+ if (_ = accept(result.init)) initializers.unshift(_);
27
+ }
28
+ else if (_ = accept(result)) {
29
+ if (kind === "field") initializers.unshift(_);
30
+ else descriptor[key] = _;
31
+ }
32
+ }
33
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
34
+ done = true;
35
+ };
2
36
  Object.defineProperty(exports, "__esModule", { value: true });
3
37
  exports.reloadPackagesOnPageRefresh = exports.packagesRootDir = exports.PackagesTable = void 0;
4
38
  exports.Packages = Packages;
5
39
  const zod_1 = require("zod");
6
40
  const context_1 = require("../context");
7
41
  const app_nav_1 = require("../types/app-nav");
8
- const orm_1 = require("./orm");
42
+ const decorators_1 = require("./orm/decorators");
43
+ const table_1 = require("./orm/table");
9
44
  const table_definitions_system_1 = require("./orm/table-definitions.system");
10
45
  const types_1 = require("./orm/types");
11
46
  const package_permissions_1 = require("./package-permissions");
@@ -34,52 +69,67 @@ const metaData = {
34
69
  iconClassName: 'bi bi-box-fill',
35
70
  fields: (0, types_1.schemaToFields)(schema),
36
71
  };
37
- class PackagesTable extends orm_1.Table {
38
- static isPassthrough = false;
39
- async insert(packageObj, opts) {
40
- return this.save(packageObj, opts);
41
- }
42
- async update(packageObj, opts) {
43
- return this.save(packageObj, opts);
44
- }
45
- async save(packageObj, opts) {
46
- if (PackagesTable.isPassthrough) {
72
+ let PackagesTable = (() => {
73
+ let _classSuper = table_1.Table;
74
+ let _instanceExtraInitializers = [];
75
+ let _signAndSave_decorators;
76
+ return class PackagesTable extends _classSuper {
77
+ static {
78
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
79
+ _signAndSave_decorators = [(0, decorators_1.ProxyClientTableMethodCalls)()];
80
+ __esDecorate(this, null, _signAndSave_decorators, { kind: "method", name: "signAndSave", static: false, private: false, access: { has: obj => "signAndSave" in obj, get: obj => obj.signAndSave }, metadata: _metadata }, null, _instanceExtraInitializers);
81
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
82
+ }
83
+ static isPassthrough = false;
84
+ async insert(packageObj, opts) {
85
+ return this.save(packageObj, opts);
86
+ }
87
+ async update(packageObj, opts) {
88
+ return this.save(packageObj, opts);
89
+ }
90
+ async save(packageObj, opts) {
91
+ if (PackagesTable.isPassthrough) {
92
+ return super.save(packageObj, opts);
93
+ }
94
+ if (!this.groupId) {
95
+ // users can do whatever they want to packages in their personal space
96
+ return super.save(packageObj, opts);
97
+ }
98
+ try {
99
+ await (0, package_permissions_1.verifyPackageSignature)(packageObj, this.groupId);
100
+ }
101
+ catch (err) {
102
+ throw new Error('Package verification failed. Did you mean to call `signAndSave`?', { cause: err });
103
+ }
47
104
  return super.save(packageObj, opts);
48
105
  }
49
- if (!this.groupId) {
50
- // users can do whatever they want to packages in their personal space
106
+ async signAndSave(packageObj, opts) {
107
+ if (!PackagesTable.addSignatureToPackage) {
108
+ throw new Error('Package signing is not enabled. Call PackagesTable.enablePackageSigning(fn) to enable it.');
109
+ }
110
+ packageObj = await PackagesTable.addSignatureToPackage(packageObj);
51
111
  return super.save(packageObj, opts);
52
112
  }
53
- try {
54
- await (0, package_permissions_1.verifyPackageSignature)(packageObj, this.groupId);
113
+ static addSignatureToPackage = undefined;
114
+ static enablePackageSigning(fn) {
115
+ this.addSignatureToPackage = fn;
55
116
  }
56
- catch (err) {
57
- throw new Error('Package verification failed. Did you mean to call `signAndSave`?', { cause: err });
117
+ async delete(packageId) {
118
+ // anyone (with write permissions) can delete packages since that isn't a security risk (unless something else is relying on a package to be present?)
119
+ return super.delete(packageId);
120
+ // const userContext = await getUserContext();
121
+ // const userContextPackages = Packages(userContext.userDataContext);
122
+ // if (userContextPackages === this) {
123
+ // return super.delete(packageId);
124
+ // }
125
+ // throw new Error('Only deleting packages from the user context Packages table is allowed');
58
126
  }
59
- return super.save(packageObj, opts);
60
- }
61
- async signAndSave(packageObj, opts) {
62
- if (!PackagesTable.addSignatureToPackage) {
63
- throw new Error('Package signing is not enabled. Call PackagesTable.enablePackageSigning(fn) to enable it.');
127
+ constructor() {
128
+ super(...arguments);
129
+ __runInitializers(this, _instanceExtraInitializers);
64
130
  }
65
- packageObj = await PackagesTable.addSignatureToPackage(packageObj);
66
- return super.save(packageObj, opts);
67
- }
68
- static addSignatureToPackage = undefined;
69
- static enablePackageSigning(fn) {
70
- this.addSignatureToPackage = fn;
71
- }
72
- async delete(packageId) {
73
- // anyone (with write permissions) can delete packages since that isn't a security risk (unless something else is relying on a package to be present?)
74
- return super.delete(packageId);
75
- // const userContext = await getUserContext();
76
- // const userContextPackages = Packages(userContext.userDataContext);
77
- // if (userContextPackages === this) {
78
- // return super.delete(packageId);
79
- // }
80
- // throw new Error('Only deleting packages from the user context Packages table is allowed');
81
- }
82
- }
131
+ };
132
+ })();
83
133
  exports.PackagesTable = PackagesTable;
84
134
  (0, table_definitions_system_1.registerSystemTableDefinition)(metaData, schema, PackagesTable);
85
135
  function Packages(dataContext) {
@@ -14,7 +14,7 @@ export declare const peerEventHandlerSchema: z.ZodObject<{
14
14
  handlerWorkflowId: string;
15
15
  }>;
16
16
  export type IPeerEventHandler = z.infer<typeof peerEventHandlerSchema>;
17
- export declare function PeerEventHandlers(dataContext?: DataContext): import("../..").Table<{
17
+ export declare function PeerEventHandlers(dataContext?: DataContext): import("../orm").Table<{
18
18
  peerEventTypeId: string;
19
19
  peerEventHandlerId: string;
20
20
  handlerWorkflowId: string;
@@ -97,7 +97,7 @@ export declare const peerEventTypeSchema: z.ZodObject<{
97
97
  nextScheduledTime?: number | undefined;
98
98
  }>;
99
99
  export type IPeerEventType = z.infer<typeof peerEventTypeSchema>;
100
- export declare function PeerEventTypes(dataContext?: DataContext): import("../..").Table<{
100
+ export declare function PeerEventTypes(dataContext?: DataContext): import("../orm").Table<{
101
101
  name: string;
102
102
  description: string;
103
103
  schema: {
@@ -136,145 +136,150 @@ function persistentVarFactory(name, opts) {
136
136
  let isSecret = opts.isSecret;
137
137
  let rec = undefined;
138
138
  persistentVar.loadingPromise = new Promise(async (resolve) => {
139
- const userContext = opts?.userContext || await (0, user_context_singleton_1.getUserContext)();
140
- function getDataContext() {
141
- if (opts?.dataContext) {
142
- return opts.dataContext;
143
- }
144
- if (scope === 'group') {
145
- return userContext.defaultDataContext();
146
- }
147
- else {
148
- return userContext.userDataContext;
149
- }
150
- }
151
- function getVarNameInDb() {
152
- if (scope === 'groupDevice' || scope === 'groupUser') {
153
- const dc = opts?.dataContext || userContext.defaultDataContext();
154
- // if it's a group var saved in the user's personal db, it's postfixed with the dataContextId to make it unique
155
- return name + `_` + dc.dataContextId;
156
- }
157
- return name;
158
- }
159
- async function loadRecFromDb() {
160
- const dc = getDataContext();
161
- const table = PersistentVars(dc);
162
- const name = getVarNameInDb();
163
- let dbRec = await table.findOne({ name });
164
- if (dbRec) {
165
- if (dbRec.scope !== scope) {
166
- console.warn(`${name}: deleting old persistent var record because scopes don't match. If this is unexpected there could be two different persistent variables using the same name`);
167
- await table.delete(dbRec);
168
- dbRec = undefined;
139
+ try {
140
+ const userContext = opts?.userContext || await (0, user_context_singleton_1.getUserContext)();
141
+ function getDataContext() {
142
+ if (opts?.dataContext) {
143
+ return opts.dataContext;
144
+ }
145
+ if (scope === 'group') {
146
+ return userContext.defaultDataContext();
147
+ }
148
+ else {
149
+ return userContext.userDataContext;
169
150
  }
170
151
  }
171
- if (!dbRec) {
172
- dbRec = {
173
- persistentVarId: '',
174
- name,
175
- scope,
176
- isSecret,
177
- value: { value: defaultValue },
178
- };
179
- }
180
- // if the db says it's secret but the caller didn't specify, assume it's secret
181
- if (dbRec.isSecret !== undefined && opts.isSecret === undefined) {
182
- isSecret = dbRec.isSecret;
183
- }
184
- return dbRec;
185
- }
186
- async function reactToValueChanged(value) {
187
- if (name === 'colorModePreference')
188
- console.log(`colorModePreferences pvar value set: ${value}`);
189
- if (!rec?.persistentVarId && value === defaultValue) {
190
- return;
191
- }
192
- if (!rec?.persistentVarId) {
193
- rec = await loadRecFromDb();
194
- }
195
- const oldValue = rec.value.value;
196
- if ((0, lodash_1.isEqual)(value, oldValue)) {
197
- return;
152
+ function getVarNameInDb() {
153
+ if (scope === 'groupDevice' || scope === 'groupUser') {
154
+ const dc = opts?.dataContext || userContext.defaultDataContext();
155
+ // if it's a group var saved in the user's personal db, it's postfixed with the dataContextId to make it unique
156
+ return name + `_` + dc.dataContextId;
157
+ }
158
+ return name;
198
159
  }
199
- rec.value.value = value;
200
- const dc = getDataContext();
201
- const table = PersistentVars(dc);
202
- // delete if value equals default value
203
- if ((0, lodash_1.isEqual)(rec.value.value, defaultValue)) {
204
- if (rec.persistentVarId) {
205
- if (name === 'colorModePreference') {
206
- console.log(`deleted persistent var ${name} from db:`, rec.value.value);
160
+ async function loadRecFromDb() {
161
+ const dc = getDataContext();
162
+ const table = PersistentVars(dc);
163
+ const name = getVarNameInDb();
164
+ let dbRec = await table.findOne({ name });
165
+ if (dbRec) {
166
+ if (dbRec.scope !== scope) {
167
+ console.warn(`${name}: deleting old persistent var record because scopes don't match. If this is unexpected there could be two different persistent variables using the same name`);
168
+ await table.delete(dbRec);
169
+ dbRec = undefined;
207
170
  }
208
- await table.delete(rec);
209
171
  }
210
- rec = undefined;
172
+ if (!dbRec) {
173
+ dbRec = {
174
+ persistentVarId: '',
175
+ name,
176
+ scope,
177
+ isSecret,
178
+ value: { value: defaultValue },
179
+ };
180
+ }
181
+ // if the db says it's secret but the caller didn't specify, assume it's secret
182
+ if (dbRec.isSecret !== undefined && opts.isSecret === undefined) {
183
+ isSecret = dbRec.isSecret;
184
+ }
185
+ return dbRec;
211
186
  }
212
- else {
213
- try {
214
- await table.save(rec);
215
- if (name === 'colorModePreference') {
216
- console.log(`Saved var ${name} to db:`, rec.value.value);
187
+ async function reactToValueChanged(value) {
188
+ if (name === 'colorModePreference')
189
+ console.log(`colorModePreferences pvar value set: ${value}`);
190
+ if (!rec?.persistentVarId && value === defaultValue) {
191
+ return;
192
+ }
193
+ if (!rec?.persistentVarId) {
194
+ rec = await loadRecFromDb();
195
+ }
196
+ const oldValue = rec.value.value;
197
+ if ((0, lodash_1.isEqual)(value, oldValue)) {
198
+ return;
199
+ }
200
+ rec.value.value = value;
201
+ const dc = getDataContext();
202
+ const table = PersistentVars(dc);
203
+ // delete if value equals default value
204
+ if ((0, lodash_1.isEqual)(rec.value.value, defaultValue)) {
205
+ if (rec.persistentVarId) {
206
+ if (name === 'colorModePreference') {
207
+ console.log(`deleted persistent var ${name} from db:`, rec.value.value);
208
+ }
209
+ await table.delete(rec);
217
210
  }
211
+ rec = undefined;
218
212
  }
219
- catch (err) {
220
- const errMsg = err?.message || String(err) || '';
221
- if (errMsg.includes('UNIQUE constraint failed')) {
222
- console.warn(`Detected UNIQUE constraint failed error when saving persistent var, reloading and retrying: ${name}`);
223
- rec = await loadRecFromDb();
224
- persistentVar(rec.value.value);
213
+ else {
214
+ try {
215
+ await table.save(rec);
216
+ if (name === 'colorModePreference') {
217
+ console.log(`Saved var ${name} to db:`, rec.value.value);
218
+ }
225
219
  }
226
- else {
227
- console.error('Error saving persistent var', { name, value, rec, err });
228
- throw err;
220
+ catch (err) {
221
+ const errMsg = err?.message || String(err) || '';
222
+ if (errMsg.includes('UNIQUE constraint failed')) {
223
+ console.warn(`Detected UNIQUE constraint failed error when saving persistent var, reloading and retrying: ${name}`);
224
+ rec = await loadRecFromDb();
225
+ persistentVar(rec.value.value);
226
+ }
227
+ else {
228
+ console.error('Error saving persistent var', { name, value, rec, err });
229
+ throw err;
230
+ }
229
231
  }
230
232
  }
231
233
  }
232
- }
233
- // subscribe to db changes
234
- userContext.subscribeToDataChangedAcrossAllGroups(PersistentVars(), async (evt) => {
235
- const dbRec = evt.data.dataObject;
236
- const dbName = getVarNameInDb();
237
- if (!rec?.persistentVarId && dbRec.name === dbName) {
238
- rec = dbRec;
239
- }
240
- if (dbRec.persistentVarId === rec?.persistentVarId) {
241
- if (evt.data.op === 'delete') {
242
- rec = undefined;
243
- if (defaultValue !== undefined) {
244
- persistentVar(defaultValue);
245
- }
246
- }
247
- else {
234
+ // subscribe to db changes
235
+ userContext.subscribeToDataChangedAcrossAllGroups(exports.persistentVarsMetaData.name, async (evt) => {
236
+ const dbRec = evt.data.dataObject;
237
+ const dbName = getVarNameInDb();
238
+ if (!rec?.persistentVarId && dbRec.name === dbName) {
248
239
  rec = dbRec;
249
- if (!(0, lodash_1.isEqual)(persistentVar(), rec.value.value)) {
250
- persistentVar(rec.value.value);
240
+ }
241
+ if (dbRec.persistentVarId === rec?.persistentVarId) {
242
+ if (evt.data.op === 'delete') {
243
+ rec = undefined;
244
+ if (defaultValue !== undefined) {
245
+ persistentVar(defaultValue);
246
+ }
247
+ }
248
+ else {
249
+ rec = dbRec;
250
+ if (!(0, lodash_1.isEqual)(persistentVar(), rec.value.value)) {
251
+ persistentVar(rec.value.value);
252
+ }
251
253
  }
252
254
  }
255
+ });
256
+ // update group-dependent variables if group context changes and it hasn't been pinned to a specific data context
257
+ const groupDependentScopes = ['group', 'groupDevice', 'groupUser'];
258
+ if (!opts?.dataContext && groupDependentScopes.includes(scope)) {
259
+ userContext.defaultDataContext.subscribe(async () => {
260
+ rec = await loadRecFromDb();
261
+ persistentVar(rec.value.value);
262
+ });
253
263
  }
254
- });
255
- // update group-dependent variables if group context changes and it hasn't been pinned to a specific data context
256
- const groupDependentScopes = ['group', 'groupDevice', 'groupUser'];
257
- if (!opts?.dataContext && groupDependentScopes.includes(scope)) {
258
- userContext.defaultDataContext.subscribe(async () => {
264
+ if (!setWithDbValue) {
259
265
  rec = await loadRecFromDb();
260
- persistentVar(rec.value.value);
261
- });
262
- }
263
- if (!setWithDbValue) {
264
- rec = await loadRecFromDb();
265
- if (!(0, lodash_1.isEqual)(rec.value.value, persistentVar())) {
266
- if (name === 'colorModePreference') {
267
- console.log(`Loaded persistent var ${name} from db:`, rec.value.value);
266
+ if (!(0, lodash_1.isEqual)(rec.value.value, persistentVar())) {
267
+ if (name === 'colorModePreference') {
268
+ console.log(`Loaded persistent var ${name} from db:`, rec.value.value);
269
+ }
270
+ persistentVar(rec.value.value);
268
271
  }
269
- persistentVar(rec.value.value);
270
272
  }
271
- }
272
- persistentVar.subscribe(newValue => {
273
- persistentVar.loadingPromise = persistentVar.loadingPromise.then(async () => {
274
- await reactToValueChanged(newValue);
275
- return persistentVar;
273
+ persistentVar.subscribe(newValue => {
274
+ persistentVar.loadingPromise = persistentVar.loadingPromise.then(async () => {
275
+ await reactToValueChanged(newValue);
276
+ return persistentVar;
277
+ });
276
278
  });
277
- });
279
+ }
280
+ catch (err) {
281
+ console.error(`an unexpected occurred while loading a persistent var: ${name}`, err);
282
+ }
278
283
  resolve(persistentVar);
279
284
  });
280
285
  return persistentVar;
@@ -26,7 +26,7 @@ export declare const toolTestSchema: z.ZodObject<{
26
26
  mocks?: any;
27
27
  }>;
28
28
  export type IToolTest = z.infer<typeof toolTestSchema>;
29
- export declare function ToolTests(dataContext?: DataContext): import("..").Table<{
29
+ export declare function ToolTests(dataContext?: DataContext): import("./orm").Table<{
30
30
  code: string;
31
31
  description: string;
32
32
  toolId: string;
@@ -311,7 +311,7 @@ export interface IToolInstance {
311
311
  inputSchema?: z.ZodObject<any>;
312
312
  outputSchema?: z.ZodObject<any>;
313
313
  }
314
- export declare function Tools(dataContext?: DataContext): import("..").Table<{
314
+ export declare function Tools(dataContext?: DataContext): import("./orm").Table<{
315
315
  code: string;
316
316
  name: string;
317
317
  toolId: string;
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const keys_1 = require("../keys");
4
4
  const user_permissions_1 = require("./user-permissions");
5
- const socket_type_1 = require("../device/socket.type");
6
5
  // Test the user permissions logic directly without ORM dependencies
7
6
  describe('User Permissions Logic', () => {
8
7
  let testUser;
@@ -16,7 +15,6 @@ describe('User Permissions Logic', () => {
16
15
  name: 'Test User',
17
16
  publicKey: userKeys.publicKey,
18
17
  publicBoxKey: userKeys.publicBoxKey,
19
- trustLevel: socket_type_1.TrustLevel.Trusted,
20
18
  signature: ''
21
19
  };
22
20
  });
@@ -144,11 +142,11 @@ describe('User Permissions Logic', () => {
144
142
  const signedUpdatedUser = (0, user_permissions_1.signUserObject)(updatedUser, userKeys.secretKey);
145
143
  expect(() => (0, user_permissions_1.verifyUserSignature)(signedUpdatedUser, originalUser)).toThrow();
146
144
  });
147
- it('should allow trust level changes with valid signature in group context', () => {
148
- const originalUser = (0, user_permissions_1.signUserObject)({ ...testUser, trustLevel: socket_type_1.TrustLevel.Unknown }, userKeys.secretKey);
145
+ it('should allow changes with valid signature', () => {
146
+ const originalUser = (0, user_permissions_1.signUserObject)({ ...testUser }, userKeys.secretKey);
149
147
  const updatedUser = {
150
148
  ...originalUser,
151
- trustLevel: socket_type_1.TrustLevel.Trusted,
149
+ name: 'Updated Name',
152
150
  signature: ''
153
151
  };
154
152
  const signedUpdatedUser = (0, user_permissions_1.signUserObject)(updatedUser, userKeys.secretKey);
@@ -193,12 +191,12 @@ describe('User Permissions Logic', () => {
193
191
  const signedUpdatedUser = (0, user_permissions_1.signUserObject)(updatedUser, userKeys.secretKey);
194
192
  expect(() => (0, user_permissions_1.verifyUserSignature)(signedUpdatedUser, originalUser)).toThrow();
195
193
  });
196
- it('should handle complex trust level enum values', () => {
197
- const userWithComplexTrust = {
194
+ it('should handle various user values', () => {
195
+ const userWithValues = {
198
196
  ...testUser,
199
- trustLevel: socket_type_1.TrustLevel.Malicious
197
+ name: 'Complex Name'
200
198
  };
201
- const signedUser = (0, user_permissions_1.signUserObject)(userWithComplexTrust, userKeys.secretKey);
199
+ const signedUser = (0, user_permissions_1.signUserObject)(userWithValues, userKeys.secretKey);
202
200
  expect(() => (0, user_permissions_1.verifyUserSignature)(signedUser, undefined)).not.toThrow();
203
201
  });
204
202
  });
@@ -210,7 +208,6 @@ describe('User Permissions Logic', () => {
210
208
  name: 'Victim User',
211
209
  publicKey: userKeys.publicKey, // Victim's public key
212
210
  publicBoxKey: userKeys.publicBoxKey,
213
- trustLevel: socket_type_1.TrustLevel.Trusted,
214
211
  signature: ''
215
212
  };
216
213
  const maliciousSignedUser = (0, user_permissions_1.signUserObject)(victimUser, otherUserKeys.secretKey); // Signed with attacker's key
@@ -0,0 +1,42 @@
1
+ import { z } from "zod";
2
+ import type { DataContext } from "../context/data-context";
3
+ import { TrustLevel } from "../device/socket.type";
4
+ /**
5
+ * UserTrustLevels table allows different users/groups to assign their own trust levels
6
+ * to users without modifying the user's signed record.
7
+ *
8
+ * The trustLevel is scoped to the current DataContext (either user or group).
9
+ * Each context can maintain its own trust assessment of other users.
10
+ */
11
+ export declare const userTrustLevelSchema: z.ZodObject<{
12
+ userId: z.ZodString;
13
+ trustLevel: z.ZodNativeEnum<typeof TrustLevel>;
14
+ assignedAt: z.ZodOptional<z.ZodDate>;
15
+ notes: z.ZodOptional<z.ZodString>;
16
+ }, "strip", z.ZodTypeAny, {
17
+ userId: string;
18
+ trustLevel: TrustLevel;
19
+ assignedAt?: Date | undefined;
20
+ notes?: string | undefined;
21
+ }, {
22
+ userId: string;
23
+ trustLevel: TrustLevel;
24
+ assignedAt?: Date | undefined;
25
+ notes?: string | undefined;
26
+ }>;
27
+ export type IUserTrustLevel = z.infer<typeof userTrustLevelSchema>;
28
+ export declare function UserTrustLevels(dataContext?: DataContext): import("./orm").Table<{
29
+ userId: string;
30
+ trustLevel: TrustLevel;
31
+ assignedAt?: Date | undefined;
32
+ notes?: string | undefined;
33
+ }>;
34
+ /**
35
+ * Get the trust level for a specific user in the given context.
36
+ * Returns TrustLevel.Unknown if no trust level has been assigned.
37
+ */
38
+ export declare function getUserTrustLevel(dataContext: DataContext, userId: string): Promise<TrustLevel>;
39
+ /**
40
+ * Set the trust level for a specific user in the given context.
41
+ */
42
+ export declare function setUserTrustLevel(userId: string, trustLevel: TrustLevel, dataContext?: DataContext, notes?: string): Promise<void>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.userTrustLevelSchema = void 0;
4
+ exports.UserTrustLevels = UserTrustLevels;
5
+ exports.getUserTrustLevel = getUserTrustLevel;
6
+ exports.setUserTrustLevel = setUserTrustLevel;
7
+ const zod_1 = require("zod");
8
+ const user_context_singleton_1 = require("../context/user-context-singleton");
9
+ const socket_type_1 = require("../device/socket.type");
10
+ const table_definitions_system_1 = require("./orm/table-definitions.system");
11
+ const types_1 = require("./orm/types");
12
+ /**
13
+ * UserTrustLevels table allows different users/groups to assign their own trust levels
14
+ * to users without modifying the user's signed record.
15
+ *
16
+ * The trustLevel is scoped to the current DataContext (either user or group).
17
+ * Each context can maintain its own trust assessment of other users.
18
+ */
19
+ exports.userTrustLevelSchema = zod_1.z.object({
20
+ userId: zod_1.z.string().describe('The user being assigned a trust level'),
21
+ trustLevel: zod_1.z.nativeEnum(socket_type_1.TrustLevel).describe('The trust level assigned to this user in this context'),
22
+ assignedAt: zod_1.z.date().optional().describe('When the trust level was assigned'),
23
+ notes: zod_1.z.string().optional().describe('Optional notes about why this trust level was assigned'),
24
+ });
25
+ const metaData = {
26
+ name: 'UserTrustLevels',
27
+ description: 'Trust levels assigned to users by the current context (user or group)',
28
+ primaryKeyName: 'userId',
29
+ fields: (0, types_1.schemaToFields)(exports.userTrustLevelSchema),
30
+ indexes: [
31
+ { fields: ['trustLevel'] },
32
+ ]
33
+ };
34
+ (0, table_definitions_system_1.registerSystemTableDefinition)(metaData, exports.userTrustLevelSchema);
35
+ function UserTrustLevels(dataContext) {
36
+ return (0, user_context_singleton_1.getTableContainer)(dataContext).getTable(metaData, exports.userTrustLevelSchema);
37
+ }
38
+ /**
39
+ * Get the trust level for a specific user in the given context.
40
+ * Returns TrustLevel.Unknown if no trust level has been assigned.
41
+ */
42
+ async function getUserTrustLevel(dataContext, userId) {
43
+ const userContext = await (0, user_context_singleton_1.getUserContext)();
44
+ if (dataContext === userContext.userDataContext && userContext.userId === userId) {
45
+ return socket_type_1.TrustLevel.Self;
46
+ }
47
+ const trustLevelRecord = await UserTrustLevels(dataContext).get(userId);
48
+ return trustLevelRecord?.trustLevel ?? socket_type_1.TrustLevel.Unknown;
49
+ }
50
+ /**
51
+ * Set the trust level for a specific user in the given context.
52
+ */
53
+ async function setUserTrustLevel(userId, trustLevel, dataContext, notes) {
54
+ await UserTrustLevels(dataContext).save({
55
+ userId,
56
+ trustLevel,
57
+ assignedAt: new Date(),
58
+ notes,
59
+ });
60
+ }