@deveye/types 0.18.3 → 0.19.1
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/package.json +1 -1
- package/src/domain/device.ts +6 -2
- package/src/domain/featureRegistry.ts +16 -0
- package/src/domain/home.ts +5 -3
- package/src/domain/live.ts +3 -3
- package/src/domain/project.ts +56 -0
- package/src/domain/remoteInstance.test.ts +35 -0
- package/src/domain/remoteInstance.ts +70 -0
- package/src/domain/report.ts +34 -2
- package/src/domain/secrecy.ts +3 -0
- package/src/domain/sharing.ts +46 -1
- package/src/domain/twoFactor.ts +7 -3
- package/src/domain/workspace.ts +1 -1
- package/src/domain/workspaceRole.ts +1 -1
- package/src/features/admin.ts +1 -51
- package/src/features/home.ts +1 -1
- package/src/features/links.ts +37 -0
- package/src/features/registry.ts +4 -0
- package/src/features/remote.ts +52 -0
- package/src/features/secrecy.ts +22 -8
- package/src/features/sharing.ts +78 -2
- package/src/features/twoFactor.ts +1 -1
- package/src/features/user.ts +32 -4
- package/src/features/workspace.ts +2 -2
- package/src/http/auth.ts +113 -15
- package/src/http/device.ts +14 -10
- package/src/http/status.ts +2 -0
- package/src/index.ts +89 -12
- package/src/protocol/agent.ts +38 -0
- package/src/protocol/error.ts +3 -0
- package/src/sdk/client-ambient.d.ts +60 -5
- package/src/sdk/client.ts +81 -3
- package/src/sdk/copy.test.ts +374 -0
- package/src/sdk/copy.ts +435 -0
- package/src/sdk/manifest.test.ts +27 -0
- package/src/sdk/manifest.ts +60 -1
- package/src/sdk/providers.ts +102 -0
- package/src/sdk/server.ts +188 -10
- package/src/sdk/testing.test.ts +22 -0
- package/src/sdk/testing.ts +91 -2
package/src/sdk/copy.ts
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import { FeatureError, type MovableCell, type SdkCipher, type SdkQueryable } from './server';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Copying an item to another workspace, of this DevEye or of another one.
|
|
7
|
+
*
|
|
8
|
+
* You DESCRIBE your item as a tree of tables; the engine below does the rest,
|
|
9
|
+
* once, for every feature: reading the rows, opening the encrypted cells,
|
|
10
|
+
* writing them elsewhere under new ids and another key. A copy between two
|
|
11
|
+
* DevEye instances is the same two halves with the user's browser in between:
|
|
12
|
+
* `exportItemTree` runs on the source server, `importItemTree` on the
|
|
13
|
+
* destination, and the two servers never talk to each other.
|
|
14
|
+
*
|
|
15
|
+
* What travels is PLAINTEXT, by design: the destination seals it under its own
|
|
16
|
+
* key, which the source does not know. It only ever exists in the memory of the
|
|
17
|
+
* two servers and of the browser that carries it.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** One table of an item's tree, see {@link ItemTree}. */
|
|
21
|
+
export interface ItemTreeTable {
|
|
22
|
+
table: string;
|
|
23
|
+
/**
|
|
24
|
+
* Primary key. Never copied: the destination gives the row a new one.
|
|
25
|
+
* Absent on a pure link table (two references and nothing else), which
|
|
26
|
+
* nothing points at and which holds no sealed column.
|
|
27
|
+
*/
|
|
28
|
+
idColumn?: string;
|
|
29
|
+
/** `'auto'` (default): AUTO_INCREMENT. `'uuid'`: the engine draws a fresh UUID. */
|
|
30
|
+
idKind?: 'auto' | 'uuid';
|
|
31
|
+
/** Column tying the row to the item. On the root table, the same as `idColumn`. */
|
|
32
|
+
ownerColumn: string;
|
|
33
|
+
/**
|
|
34
|
+
* For a row hanging off the item INDIRECTLY: a SQL subquery selecting the
|
|
35
|
+
* `ownerColumn` values that belong to it, taking the item's id as its only
|
|
36
|
+
* `?`. Interpolated into the query, so a literal written in your module,
|
|
37
|
+
* exactly like `table`. Never build it from input.
|
|
38
|
+
*/
|
|
39
|
+
ownerScope?: string;
|
|
40
|
+
/**
|
|
41
|
+
* Columns of encrypted text: opened with the source key, sealed again with
|
|
42
|
+
* the destination's.
|
|
43
|
+
*
|
|
44
|
+
* ⚠️ Held BY HAND: an encrypted column left out is copied as a blob no key
|
|
45
|
+
* of the destination can open, and moved under the old key, where it becomes
|
|
46
|
+
* unreadable. Nothing can detect it, one encrypted blob being
|
|
47
|
+
* indistinguishable from another. Revisit it whenever you add one.
|
|
48
|
+
*/
|
|
49
|
+
sealed?: readonly string[];
|
|
50
|
+
/**
|
|
51
|
+
* Columns pointing at a row of a table of this tree (this one included),
|
|
52
|
+
* by that table's name: rewritten to the ids the destination handed out. A
|
|
53
|
+
* reference to anything OUTSIDE the tree belongs in `omit`.
|
|
54
|
+
*/
|
|
55
|
+
refs?: Readonly<Record<string, string>>;
|
|
56
|
+
/** Column holding the workspace id, rewritten to the destination's. */
|
|
57
|
+
workspaceColumn?: string;
|
|
58
|
+
/**
|
|
59
|
+
* Column holding the account the row belongs to, rewritten to whoever makes
|
|
60
|
+
* the copy: the original account may not exist where the copy lands. A user
|
|
61
|
+
* reference that is only informative (an assignee) belongs in `omit`.
|
|
62
|
+
*/
|
|
63
|
+
userColumn?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Columns the copy leaves to their default: what means nothing elsewhere (a
|
|
66
|
+
* source of the origin workspace, a folder, a sort order) and what the
|
|
67
|
+
* destination must rebuild by itself (a sync state, a last error).
|
|
68
|
+
*/
|
|
69
|
+
omit?: readonly string[];
|
|
70
|
+
/**
|
|
71
|
+
* Rows the destination rebuilds by itself (a cache of commits, a history of
|
|
72
|
+
* checks): moved with the item, never copied.
|
|
73
|
+
*/
|
|
74
|
+
cache?: boolean;
|
|
75
|
+
/**
|
|
76
|
+
* ROOT only: the column that orders your items within a workspace. The copy
|
|
77
|
+
* lands at the end of the destination's list, whatever rank it had at home.
|
|
78
|
+
* Needs `workspaceColumn`.
|
|
79
|
+
*/
|
|
80
|
+
orderColumn?: string;
|
|
81
|
+
/**
|
|
82
|
+
* ROOT only: the column that makes an item unique within a workspace (the
|
|
83
|
+
* digest of its name, encryption being non-deterministic), and the sentence
|
|
84
|
+
* shown when the destination already holds one. Needs `workspaceColumn`.
|
|
85
|
+
*/
|
|
86
|
+
unique?: { column: string; message: string };
|
|
87
|
+
/**
|
|
88
|
+
* ROOT only, for a feature whose items choose their tier: the column that
|
|
89
|
+
* says which key seals the whole tree, and its two values. Without it every
|
|
90
|
+
* item is open.
|
|
91
|
+
*/
|
|
92
|
+
tier?: { column: string; open: string | number; private: string | number };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Which key seals an item: `'open'`, the workspace's, that the server can
|
|
97
|
+
* always use, or `'private'`, the caller's password-derived one (see
|
|
98
|
+
* `StorageEncryption`).
|
|
99
|
+
*/
|
|
100
|
+
export type ItemTier = 'open' | 'private';
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* An item as a tree of tables: the root first, then every table BEFORE the ones
|
|
104
|
+
* that reference it. The single hand-held description of what an item is made
|
|
105
|
+
* of, for the two gestures that need it: `copy` reads it whole, and `move`
|
|
106
|
+
* derives its cells from it ({@link movableCellsOf}).
|
|
107
|
+
*/
|
|
108
|
+
export type ItemTree = readonly ItemTreeTable[];
|
|
109
|
+
|
|
110
|
+
/** The cells a `move` re-seals: every sealed column of the tree, caches included. */
|
|
111
|
+
export function movableCellsOf(tree: ItemTree): MovableCell[] {
|
|
112
|
+
return tree.flatMap((t) =>
|
|
113
|
+
(t.sealed ?? []).map((column) => ({
|
|
114
|
+
table: t.table,
|
|
115
|
+
// `itemTreeProblem` refuse une table scellée sans identifiant.
|
|
116
|
+
idColumn: t.idColumn ?? '',
|
|
117
|
+
ownerColumn: t.ownerColumn,
|
|
118
|
+
column,
|
|
119
|
+
...(t.ownerScope ? { ownerScope: t.ownerScope } : {})
|
|
120
|
+
}))
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Why a tree cannot be used, or `null`. The host checks it at boot: every name
|
|
128
|
+
* in it ends up interpolated into SQL, and a table listed before the one it
|
|
129
|
+
* references would be written before the id it needs exists.
|
|
130
|
+
*/
|
|
131
|
+
export function itemTreeProblem(tree: ItemTree): string | null {
|
|
132
|
+
const [root] = tree;
|
|
133
|
+
if (!root) return 'the tree is empty';
|
|
134
|
+
if (root.ownerColumn !== root.idColumn) {
|
|
135
|
+
return `${root.table}: the root owns itself, ownerColumn must be idColumn`;
|
|
136
|
+
}
|
|
137
|
+
if (root.cache || root.ownerScope) {
|
|
138
|
+
return `${root.table}: the root is neither a cache nor scoped`;
|
|
139
|
+
}
|
|
140
|
+
const seen = new Set<string>();
|
|
141
|
+
for (const t of tree) {
|
|
142
|
+
const names = [
|
|
143
|
+
t.table,
|
|
144
|
+
...(t.idColumn ? [t.idColumn] : []),
|
|
145
|
+
t.ownerColumn,
|
|
146
|
+
...(t.workspaceColumn ? [t.workspaceColumn] : []),
|
|
147
|
+
...(t.userColumn ? [t.userColumn] : []),
|
|
148
|
+
...(t.orderColumn ? [t.orderColumn] : []),
|
|
149
|
+
...(t.unique ? [t.unique.column] : []),
|
|
150
|
+
...(t.tier ? [t.tier.column] : []),
|
|
151
|
+
...(t.sealed ?? []),
|
|
152
|
+
...(t.omit ?? []),
|
|
153
|
+
...Object.keys(t.refs ?? {})
|
|
154
|
+
];
|
|
155
|
+
const bad = names.find((n) => !IDENTIFIER.test(n));
|
|
156
|
+
if (bad !== undefined) return `${t.table}: "${bad}" is not a plain SQL identifier`;
|
|
157
|
+
if (seen.has(t.table)) return `${t.table}: listed twice`;
|
|
158
|
+
if (t.tier && t !== root) return `${t.table}: only the root chooses the tier`;
|
|
159
|
+
if ((t.orderColumn || t.unique) && (t !== root || !t.workspaceColumn)) {
|
|
160
|
+
return `${t.table}: orderColumn and unique are for a root that names its workspaceColumn`;
|
|
161
|
+
}
|
|
162
|
+
if (
|
|
163
|
+
!t.idColumn &&
|
|
164
|
+
(t === root ||
|
|
165
|
+
(t.sealed ?? []).length > 0 ||
|
|
166
|
+
Object.values(t.refs ?? {}).includes(t.table))
|
|
167
|
+
) {
|
|
168
|
+
return `${t.table}: only a pure link table goes without idColumn`;
|
|
169
|
+
}
|
|
170
|
+
for (const [column, target] of Object.entries(t.refs ?? {})) {
|
|
171
|
+
if (target !== t.table && !seen.has(target)) {
|
|
172
|
+
return `${t.table}.${column}: references ${target}, which must be listed before it`;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (t.ownerScope && t.refs?.[t.ownerColumn] === undefined && !t.cache) {
|
|
176
|
+
return `${t.table}: a scoped table must declare what ${t.ownerColumn} references`;
|
|
177
|
+
}
|
|
178
|
+
seen.add(t.table);
|
|
179
|
+
}
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A row as it travels: column name to a JSON-safe value. */
|
|
184
|
+
export type ItemTreeRow = Record<string, unknown>;
|
|
185
|
+
|
|
186
|
+
/** The rows of an item, per table name. Sealed cells are in the clear. */
|
|
187
|
+
export type ItemTreeRows = Record<string, ItemTreeRow[]>;
|
|
188
|
+
|
|
189
|
+
/** How a value that JSON cannot carry travels. */
|
|
190
|
+
const BINARY_TAG = '$deveye:base64';
|
|
191
|
+
|
|
192
|
+
function ownerFilter(t: ItemTreeTable): string {
|
|
193
|
+
return t.ownerScope ? `${t.ownerColumn} IN (${t.ownerScope})` : `${t.ownerColumn} = ?`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The writable columns of a table, as the database knows them: generated ones are not. */
|
|
197
|
+
async function writableColumns(q: SdkQueryable, table: string): Promise<Set<string>> {
|
|
198
|
+
const rows = await q.query<{ Field: string; Extra: string }>(`SHOW COLUMNS FROM ${table}`);
|
|
199
|
+
// `DEFAULT_GENERATED` n'est qu'une valeur par défaut calculée : la colonne s'écrit.
|
|
200
|
+
return new Set(
|
|
201
|
+
rows.filter((r) => !/(VIRTUAL|STORED) GENERATED/i.test(r.Extra ?? '')).map((r) => r.Field)
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** MySQL wants `YYYY-MM-DD HH:MM:SS`, not the ISO form JSON would give a `Date`. */
|
|
206
|
+
function toWire(value: unknown): unknown {
|
|
207
|
+
if (value instanceof Date) return value.toISOString().slice(0, 19).replace('T', ' ');
|
|
208
|
+
if (typeof value === 'bigint') return value.toString();
|
|
209
|
+
if (value instanceof Uint8Array) return { [BINARY_TAG]: Buffer.from(value).toString('base64') };
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function fromWire(value: unknown): unknown {
|
|
214
|
+
if (value === null || typeof value !== 'object') return value;
|
|
215
|
+
const binary = (value as Record<string, unknown>)[BINARY_TAG];
|
|
216
|
+
if (typeof binary === 'string') return Buffer.from(binary, 'base64');
|
|
217
|
+
// A JSON column, parsed by the driver on the way out.
|
|
218
|
+
return JSON.stringify(value);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The tier of an item still in the database; `null` when it is gone. */
|
|
222
|
+
export async function itemTierOf(
|
|
223
|
+
q: SdkQueryable,
|
|
224
|
+
tree: ItemTree,
|
|
225
|
+
itemId: string | number
|
|
226
|
+
): Promise<ItemTier | null> {
|
|
227
|
+
const root = tree[0];
|
|
228
|
+
const rows = await q.query<Record<string, unknown>>(
|
|
229
|
+
`SELECT ${root.tier ? root.tier.column : root.idColumn} AS tier FROM ${root.table} WHERE ${root.idColumn} = ?`,
|
|
230
|
+
[itemId]
|
|
231
|
+
);
|
|
232
|
+
if (rows.length === 0) return null;
|
|
233
|
+
return root.tier && String(rows[0].tier) === String(root.tier.private) ? 'private' : 'open';
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Reads an item out of the database, sealed cells opened with `cipher`: the
|
|
238
|
+
* one of the item's tier ({@link itemTierOf}).
|
|
239
|
+
*
|
|
240
|
+
* Throws before returning anything if one cell resists: a copy missing a cell
|
|
241
|
+
* would look whole, and nobody would know what it lost.
|
|
242
|
+
*/
|
|
243
|
+
export async function exportItemTree(
|
|
244
|
+
q: SdkQueryable,
|
|
245
|
+
tree: ItemTree,
|
|
246
|
+
itemId: string | number,
|
|
247
|
+
cipher: SdkCipher
|
|
248
|
+
): Promise<ItemTreeRows> {
|
|
249
|
+
const out: ItemTreeRows = {};
|
|
250
|
+
for (const t of tree) {
|
|
251
|
+
if (t.cache) continue;
|
|
252
|
+
const columns = await writableColumns(q, t.table);
|
|
253
|
+
const skipped = new Set(t.omit ?? []);
|
|
254
|
+
if (t.workspaceColumn) skipped.add(t.workspaceColumn);
|
|
255
|
+
if (t.userColumn) skipped.add(t.userColumn);
|
|
256
|
+
if (t.orderColumn) skipped.add(t.orderColumn);
|
|
257
|
+
// The destination decides the tier: it may not have the private one.
|
|
258
|
+
if (t.tier) skipped.add(t.tier.column);
|
|
259
|
+
const sealed = new Set(t.sealed ?? []);
|
|
260
|
+
const rows = await q.query<ItemTreeRow>(
|
|
261
|
+
`SELECT * FROM ${t.table} WHERE ${ownerFilter(t)}${t.idColumn ? ` ORDER BY ${t.idColumn} ASC` : ''}`,
|
|
262
|
+
[itemId]
|
|
263
|
+
);
|
|
264
|
+
out[t.table] = [];
|
|
265
|
+
for (const row of rows) {
|
|
266
|
+
const copy: ItemTreeRow = {};
|
|
267
|
+
for (const [column, value] of Object.entries(row)) {
|
|
268
|
+
if (!columns.has(column) || skipped.has(column)) continue;
|
|
269
|
+
if (sealed.has(column) && typeof value === 'string' && value !== '') {
|
|
270
|
+
const plain = await cipher.tryDecrypt(value);
|
|
271
|
+
if (plain === null) {
|
|
272
|
+
throw new FeatureError(
|
|
273
|
+
'internal',
|
|
274
|
+
`Une ligne de ${t.table} est illisible : copie annulée, rien n’a été écrit.`
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
copy[column] = plain;
|
|
278
|
+
} else copy[column] = toWire(value);
|
|
279
|
+
}
|
|
280
|
+
out[t.table].push(copy);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** How many rows a bundle holds, for a progress bar or a refusal. */
|
|
287
|
+
export function countItemTreeRows(rows: ItemTreeRows): number {
|
|
288
|
+
return Object.values(rows).reduce((n, list) => n + list.length, 0);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Where a copy lands, and as whom. */
|
|
292
|
+
export interface ItemTreeDestination {
|
|
293
|
+
workspaceId: number;
|
|
294
|
+
/** Whoever makes the copy: the account every `userColumn` is rewritten to. */
|
|
295
|
+
userId: number;
|
|
296
|
+
/** The cipher of `tier` in that workspace. */
|
|
297
|
+
cipher: SdkCipher;
|
|
298
|
+
/** Defaults to `'open'`. The root's tier column says so. */
|
|
299
|
+
tier?: ItemTier;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Writes an item into `into.workspaceId`, sealed cells under `into.cipher`, and
|
|
304
|
+
* returns the id of its new root row. `q` MUST be transactional: a tree written
|
|
305
|
+
* halfway is an item that opens on missing pieces.
|
|
306
|
+
*
|
|
307
|
+
* `rows` comes from a browser, possibly from another DevEye: it is validated
|
|
308
|
+
* against the tree and against the database, never trusted. Table names are
|
|
309
|
+
* taken from the tree alone, column names must exist in the table, and every
|
|
310
|
+
* value is bound.
|
|
311
|
+
*/
|
|
312
|
+
export async function importItemTree(
|
|
313
|
+
q: SdkQueryable,
|
|
314
|
+
tree: ItemTree,
|
|
315
|
+
rows: ItemTreeRows,
|
|
316
|
+
into: ItemTreeDestination
|
|
317
|
+
): Promise<string> {
|
|
318
|
+
const { workspaceId: toWorkspaceId, cipher, tier = 'open' } = into;
|
|
319
|
+
const copied = tree.filter((t) => !t.cache);
|
|
320
|
+
const known = new Set(copied.map((t) => t.table));
|
|
321
|
+
for (const table of Object.keys(rows)) {
|
|
322
|
+
if (!known.has(table)) {
|
|
323
|
+
throw new FeatureError('validation', `Table inattendue dans la copie : ${table}.`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const root = copied[0];
|
|
327
|
+
if (!root || (rows[root.table] ?? []).length !== 1) {
|
|
328
|
+
throw new FeatureError('validation', 'La copie doit porter exactement un élément.');
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Old id to new id, per table. */
|
|
332
|
+
const ids = new Map<string, Map<string, string | number>>();
|
|
333
|
+
/** A row pointing at its own table: set once every row of that table has its new id. */
|
|
334
|
+
const selfRefs: { t: ItemTreeTable; newId: string | number; column: string; oldRef: string }[] =
|
|
335
|
+
[];
|
|
336
|
+
const rootOldId = String(rows[root.table][0][root.idColumn!]);
|
|
337
|
+
|
|
338
|
+
for (const t of copied) {
|
|
339
|
+
const columns = await writableColumns(q, t.table);
|
|
340
|
+
const sealed = new Set(t.sealed ?? []);
|
|
341
|
+
const refs = t.refs ?? {};
|
|
342
|
+
const mine = new Map<string, string | number>();
|
|
343
|
+
ids.set(t.table, mine);
|
|
344
|
+
|
|
345
|
+
for (const row of rows[t.table] ?? []) {
|
|
346
|
+
const values: ItemTreeRow = {};
|
|
347
|
+
const pending: { column: string; oldRef: string }[] = [];
|
|
348
|
+
for (const [column, raw] of Object.entries(row)) {
|
|
349
|
+
if (column === t.idColumn) continue;
|
|
350
|
+
if (
|
|
351
|
+
!columns.has(column) ||
|
|
352
|
+
column === t.workspaceColumn ||
|
|
353
|
+
column === t.userColumn ||
|
|
354
|
+
column === t.orderColumn ||
|
|
355
|
+
column === t.tier?.column ||
|
|
356
|
+
(t.omit ?? []).includes(column)
|
|
357
|
+
) {
|
|
358
|
+
throw new FeatureError(
|
|
359
|
+
'validation',
|
|
360
|
+
`Colonne inattendue dans la copie : ${t.table}.${column}.`
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
const target = refs[column];
|
|
364
|
+
if (target !== undefined && raw !== null) {
|
|
365
|
+
if (target === t.table) {
|
|
366
|
+
pending.push({ column, oldRef: String(raw) });
|
|
367
|
+
values[column] = null;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
const mapped = ids.get(target)?.get(String(raw));
|
|
371
|
+
if (mapped === undefined) {
|
|
372
|
+
throw new FeatureError(
|
|
373
|
+
'validation',
|
|
374
|
+
`Référence orpheline dans la copie : ${t.table}.${column}.`
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
values[column] = mapped;
|
|
378
|
+
} else if (sealed.has(column) && typeof raw === 'string' && raw !== '') {
|
|
379
|
+
values[column] = await cipher.encrypt(raw);
|
|
380
|
+
} else values[column] = fromWire(raw);
|
|
381
|
+
}
|
|
382
|
+
if (t.workspaceColumn) values[t.workspaceColumn] = toWorkspaceId;
|
|
383
|
+
if (t.userColumn) values[t.userColumn] = into.userId;
|
|
384
|
+
if (t.unique && t.workspaceColumn) {
|
|
385
|
+
const taken = await q.query<{ n: number }>(
|
|
386
|
+
`SELECT COUNT(*) AS n FROM ${t.table} WHERE ${t.workspaceColumn} = ? AND ${t.unique.column} = ?`,
|
|
387
|
+
[toWorkspaceId, values[t.unique.column] ?? null]
|
|
388
|
+
);
|
|
389
|
+
if (Number(taken[0]?.n ?? 0) > 0) {
|
|
390
|
+
throw new FeatureError('conflict', t.unique.message);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (t.orderColumn && t.workspaceColumn) {
|
|
394
|
+
const last = await q.query<{ next: number }>(
|
|
395
|
+
`SELECT COALESCE(MAX(${t.orderColumn}) + 1, 0) AS next FROM ${t.table} WHERE ${t.workspaceColumn} = ?`,
|
|
396
|
+
[toWorkspaceId]
|
|
397
|
+
);
|
|
398
|
+
values[t.orderColumn] = Number(last[0]?.next ?? 0);
|
|
399
|
+
}
|
|
400
|
+
if (t.tier) values[t.tier.column] = t.tier[tier];
|
|
401
|
+
// Whatever the row said, it hangs off the COPY: left as it came, it
|
|
402
|
+
// would attach itself to the original, or to a stranger's item.
|
|
403
|
+
if (t !== root && refs[t.ownerColumn] === undefined) {
|
|
404
|
+
values[t.ownerColumn] = ids.get(root.table)!.get(rootOldId);
|
|
405
|
+
}
|
|
406
|
+
if (t.idColumn && t.idKind === 'uuid') values[t.idColumn] = randomUUID();
|
|
407
|
+
|
|
408
|
+
const names = Object.keys(values);
|
|
409
|
+
const res = await q.execute(
|
|
410
|
+
`INSERT INTO ${t.table} (${names.join(', ')}) VALUES (${names.map(() => '?').join(', ')})`,
|
|
411
|
+
names.map((n) => values[n])
|
|
412
|
+
);
|
|
413
|
+
if (!t.idColumn) continue;
|
|
414
|
+
const newId = t.idKind === 'uuid' ? (values[t.idColumn] as string) : res.insertId;
|
|
415
|
+
mine.set(String(row[t.idColumn]), newId);
|
|
416
|
+
for (const { column, oldRef } of pending) selfRefs.push({ t, newId, column, oldRef });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
for (const ref of selfRefs) {
|
|
421
|
+
const mapped = ids.get(ref.t.table)?.get(ref.oldRef);
|
|
422
|
+
if (mapped === undefined) {
|
|
423
|
+
throw new FeatureError(
|
|
424
|
+
'validation',
|
|
425
|
+
`Référence orpheline dans la copie : ${ref.t.table}.${ref.column}.`
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
await q.execute(
|
|
429
|
+
`UPDATE ${ref.t.table} SET ${ref.column} = ? WHERE ${ref.t.idColumn!} = ?`,
|
|
430
|
+
[mapped, ref.newId]
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
return String(ids.get(root.table)!.get(rootOldId));
|
|
435
|
+
}
|
package/src/sdk/manifest.test.ts
CHANGED
|
@@ -133,3 +133,30 @@ test('validateManifest refuses a tab id it does not know', () => {
|
|
|
133
133
|
/unknown settings tab/
|
|
134
134
|
);
|
|
135
135
|
});
|
|
136
|
+
|
|
137
|
+
test('validateManifest checks quotas and the account entry', () => {
|
|
138
|
+
const rejects = (patch: Partial<FeatureManifest>, fragment: string) =>
|
|
139
|
+
assert.throws(() => validateManifest({ ...base, ...patch }), new RegExp(fragment));
|
|
140
|
+
assert.doesNotThrow(() =>
|
|
141
|
+
validateManifest({
|
|
142
|
+
...base,
|
|
143
|
+
quotas: [{ key: 'monitors', label: 'monitors' }],
|
|
144
|
+
accountEntry: { label: 'Subscription' },
|
|
145
|
+
accountOnly: true
|
|
146
|
+
})
|
|
147
|
+
);
|
|
148
|
+
rejects({ quotas: [{ key: 'Bad key', label: 'x' }] }, 'invalid quota key');
|
|
149
|
+
rejects(
|
|
150
|
+
{
|
|
151
|
+
quotas: [
|
|
152
|
+
{ key: 'monitors', label: 'a' },
|
|
153
|
+
{ key: 'monitors', label: 'b' }
|
|
154
|
+
]
|
|
155
|
+
},
|
|
156
|
+
'duplicate quota key'
|
|
157
|
+
);
|
|
158
|
+
rejects({ quotas: [{ key: 'monitors', label: ' ' }] }, 'empty label');
|
|
159
|
+
rejects({ accountOnly: true }, 'accountOnly requires accountEntry');
|
|
160
|
+
rejects({ accountOnly: true, accountEntry: { label: 'S' }, tile: {} }, 'no tile');
|
|
161
|
+
rejects({ accountEntry: { label: ' ' } }, 'requires a label');
|
|
162
|
+
});
|
package/src/sdk/manifest.ts
CHANGED
|
@@ -59,6 +59,23 @@ export type ExtraPermissionSpec =
|
|
|
59
59
|
ownerValue: string;
|
|
60
60
|
};
|
|
61
61
|
|
|
62
|
+
/** Hard cap on `quotas`. */
|
|
63
|
+
export const MAX_FEATURE_QUOTAS = 8;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Something your feature creates that an account plan may bound (monitors,
|
|
67
|
+
* paired agents). You count, the host decides: see `SdkQuota`. Without a plan
|
|
68
|
+
* provider installed (a self-hosted DevEye), every quota is unlimited.
|
|
69
|
+
*/
|
|
70
|
+
export interface FeatureQuotaSpec {
|
|
71
|
+
/** Same shape as an extra permission key. The plan names it `<featureId>.<key>`. */
|
|
72
|
+
key: string;
|
|
73
|
+
/** Plural noun, as a limit reads: "5 monitors". For `bytes`, what is measured: "of storage". */
|
|
74
|
+
label: string;
|
|
75
|
+
/** What the number counts. `bytes`: the host writes the limit as a size ("1 GB"). Default: things. */
|
|
76
|
+
unit?: 'bytes';
|
|
77
|
+
}
|
|
78
|
+
|
|
62
79
|
/** Hard cap on `extraPermissions`: keeps role editors legible. */
|
|
63
80
|
export const MAX_EXTRA_PERMISSIONS = 10;
|
|
64
81
|
|
|
@@ -107,7 +124,13 @@ export type NativeCapability =
|
|
|
107
124
|
* of your own. Declared, because it lets a module put bytes on someone
|
|
108
125
|
* else's socket without them asking. See `SdkLive.publish`.
|
|
109
126
|
*/
|
|
110
|
-
| 'live.publish'
|
|
127
|
+
| 'live.publish'
|
|
128
|
+
/**
|
|
129
|
+
* Read accounts (id, email, username, creation date): the caller's own in a
|
|
130
|
+
* handler, any account from a service. For what belongs to an account and
|
|
131
|
+
* not to a workspace (a subscription, a receipt to address).
|
|
132
|
+
*/
|
|
133
|
+
| 'accounts.read';
|
|
111
134
|
|
|
112
135
|
/**
|
|
113
136
|
* Settings tabs the shell can render for you.
|
|
@@ -258,6 +281,23 @@ export interface FeatureManifest<Id extends FeatureId = FeatureId> {
|
|
|
258
281
|
extraPermissions?: readonly ExtraPermissionSpec[];
|
|
259
282
|
/** See {@link NativeCapability}. */
|
|
260
283
|
nativeCapabilities?: readonly NativeCapability[];
|
|
284
|
+
/** See {@link FeatureQuotaSpec}. At most {@link MAX_FEATURE_QUOTAS}. */
|
|
285
|
+
quotas?: readonly FeatureQuotaSpec[];
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* An entry of the user menu, under "Security", drawn with the module's
|
|
289
|
+
* `icon` and opening `FeatureClient.AccountView`. For what belongs to the
|
|
290
|
+
* account, whatever the active workspace. `signupHint`: the view opens by itself right after
|
|
291
|
+
* a sign-up that carried a hint (`/signup?plan=…`), and receives it. One
|
|
292
|
+
* installed module at most may ask for it.
|
|
293
|
+
*/
|
|
294
|
+
accountEntry?: { label: string; signupHint?: boolean };
|
|
295
|
+
/**
|
|
296
|
+
* The module lives in the user menu only: no card, no row in the roles
|
|
297
|
+
* screen, `Widget` and `Full` not required. Requires `accountEntry`, no
|
|
298
|
+
* items, and every command scoped to the account (`access.scope`).
|
|
299
|
+
*/
|
|
300
|
+
accountOnly?: boolean;
|
|
261
301
|
|
|
262
302
|
/**
|
|
263
303
|
* Resource keys this feature owns, `<id>.<name>` (by convention, the
|
|
@@ -388,6 +428,25 @@ export function validateManifest(m: FeatureManifest): void {
|
|
|
388
428
|
}
|
|
389
429
|
}
|
|
390
430
|
|
|
431
|
+
const quotas = m.quotas ?? [];
|
|
432
|
+
if (quotas.length > MAX_FEATURE_QUOTAS) fail(m.id, `more than ${MAX_FEATURE_QUOTAS} quotas`);
|
|
433
|
+
const quotaKeys = new Set<string>();
|
|
434
|
+
for (const quota of quotas) {
|
|
435
|
+
if (!EXTRA_KEY_PATTERN.test(quota.key)) fail(m.id, `invalid quota key « ${quota.key} »`);
|
|
436
|
+
if (quotaKeys.has(quota.key)) fail(m.id, `duplicate quota key « ${quota.key} »`);
|
|
437
|
+
quotaKeys.add(quota.key);
|
|
438
|
+
if (!quota.label.trim()) fail(m.id, `quota « ${quota.key} »: empty label`);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (m.accountEntry && !m.accountEntry.label.trim()) fail(m.id, 'accountEntry requires a label');
|
|
442
|
+
if (m.accountOnly) {
|
|
443
|
+
if (!m.accountEntry) fail(m.id, 'accountOnly requires accountEntry');
|
|
444
|
+
if (m.hasItems) fail(m.id, 'accountOnly modules own no items');
|
|
445
|
+
if (m.tile || m.topbarWidget || m.settings) {
|
|
446
|
+
fail(m.id, 'accountOnly modules have no tile, topbar widget or settings');
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
391
450
|
const extras = m.extraPermissions ?? [];
|
|
392
451
|
if (extras.length > MAX_EXTRA_PERMISSIONS) {
|
|
393
452
|
fail(m.id, `more than ${MAX_EXTRA_PERMISSIONS} extra permissions`);
|
package/src/sdk/providers.ts
CHANGED
|
@@ -94,6 +94,39 @@ export interface DatabaseBackupProvider {
|
|
|
94
94
|
* feature links to: same shape and reason as `UPTIME_ITEMS_PROVIDER`
|
|
95
95
|
* (`project_database_links` is Projects' table).
|
|
96
96
|
*/
|
|
97
|
+
/**
|
|
98
|
+
* Key of the read-only measurement the Projects module consumes for its custom
|
|
99
|
+
* dashboard KPIs: the query goes through the SAME access as the monitoring (SSH
|
|
100
|
+
* tunnel or SOCKS proxy included), and only the Databases feature knows how to
|
|
101
|
+
* decrypt a connection.
|
|
102
|
+
*/
|
|
103
|
+
export const DATABASE_MEASURE_PROVIDER = 'database.measure' as const;
|
|
104
|
+
|
|
105
|
+
/** One measured number, or the reason there is none. */
|
|
106
|
+
export interface DatabaseNumberOutcome {
|
|
107
|
+
value: number | null;
|
|
108
|
+
error: string | null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface DatabaseMeasureProvider {
|
|
112
|
+
/**
|
|
113
|
+
* Measures read-only queries against a database visible from this
|
|
114
|
+
* workspace, in ONE session (tunnel included) whatever the number of
|
|
115
|
+
* queries: opening one per query would cost far more than the figures are
|
|
116
|
+
* worth.
|
|
117
|
+
*
|
|
118
|
+
* Each query must be a single read statement returning exactly one row and
|
|
119
|
+
* one column; one that is refused or faulty yields its error and does not
|
|
120
|
+
* interrupt the others, the way an alert's conditions behave. Answers
|
|
121
|
+
* `null`, never throws, when the database is not visible from there.
|
|
122
|
+
*/
|
|
123
|
+
measure(
|
|
124
|
+
databaseId: number,
|
|
125
|
+
workspaceId: number,
|
|
126
|
+
queries: readonly string[]
|
|
127
|
+
): Promise<readonly DatabaseNumberOutcome[] | null>;
|
|
128
|
+
}
|
|
129
|
+
|
|
97
130
|
export const DATABASE_ITEMS_PROVIDER = 'database.items' as const;
|
|
98
131
|
|
|
99
132
|
export interface DatabaseItemsProvider {
|
|
@@ -284,6 +317,21 @@ export interface ProjectUsage {
|
|
|
284
317
|
status: 'draft' | 'active' | 'paused' | 'done';
|
|
285
318
|
}
|
|
286
319
|
|
|
320
|
+
/**
|
|
321
|
+
* A project an item of another feature can be attached to, in ONE workspace.
|
|
322
|
+
* Open tier and at home only: a guarded project links nothing, and a link is
|
|
323
|
+
* posed in the project's own workspace, never through a projection of it.
|
|
324
|
+
*/
|
|
325
|
+
export interface ProjectLinkTarget {
|
|
326
|
+
projectId: number;
|
|
327
|
+
title: string;
|
|
328
|
+
status: 'draft' | 'active' | 'paused' | 'done';
|
|
329
|
+
/** Filed away: listed only while it still links the item, so the link can be undone. */
|
|
330
|
+
archived: boolean;
|
|
331
|
+
/** This project already links the item asked about. */
|
|
332
|
+
linked: boolean;
|
|
333
|
+
}
|
|
334
|
+
|
|
287
335
|
export interface ProjectsUsageProvider {
|
|
288
336
|
/** The workspace's projects linking this item of this feature, in Projects' display order. */
|
|
289
337
|
usageOf(feature: string, itemId: number, workspaceId: number): Promise<readonly ProjectUsage[]>;
|
|
@@ -301,6 +349,40 @@ export interface ProjectsUsageProvider {
|
|
|
301
349
|
* and zero for a feature that links nothing.
|
|
302
350
|
*/
|
|
303
351
|
detach(feature: string, itemId: number, workspaceId: number): Promise<number>;
|
|
352
|
+
/**
|
|
353
|
+
* The projects of ONE workspace an item of this feature can be attached to,
|
|
354
|
+
* each saying whether it already links it. What the app's settings shell
|
|
355
|
+
* lists on an item, workspace by workspace.
|
|
356
|
+
*
|
|
357
|
+
* Only projects living in that workspace at the open tier: a link is posed
|
|
358
|
+
* at the project's home, and a guarded project links nothing. Filed-away
|
|
359
|
+
* projects appear only while they still hold a link, so a dead link can be
|
|
360
|
+
* undone without unfiling the project.
|
|
361
|
+
*
|
|
362
|
+
* Empty for a feature this provider links nothing of, so a caller never has
|
|
363
|
+
* to know which features are linkable.
|
|
364
|
+
*/
|
|
365
|
+
linkTargets(
|
|
366
|
+
feature: string,
|
|
367
|
+
itemId: number,
|
|
368
|
+
workspaceId: number
|
|
369
|
+
): Promise<readonly ProjectLinkTarget[]>;
|
|
370
|
+
/**
|
|
371
|
+
* Attaches the item to one project of this workspace. Idempotent: the same
|
|
372
|
+
* link declared twice is the same fact, not an error.
|
|
373
|
+
*
|
|
374
|
+
* The caller owns the authorisation (`projects: write` in that workspace)
|
|
375
|
+
* and has checked the item is visible from there; this only refuses what
|
|
376
|
+
* its own tables cannot hold, silently: an unknown or projected project,
|
|
377
|
+
* and a guarded one.
|
|
378
|
+
*/
|
|
379
|
+
link(feature: string, itemId: number, workspaceId: number, projectId: number): Promise<void>;
|
|
380
|
+
/**
|
|
381
|
+
* Drops that one link, and never touches the item itself. Idempotent.
|
|
382
|
+
* Unlike {@link ProjectsUsageProvider.detach}, which drops every link of an
|
|
383
|
+
* item that left the workspace, this answers one screen's single switch.
|
|
384
|
+
*/
|
|
385
|
+
unlink(feature: string, itemId: number, workspaceId: number, projectId: number): Promise<void>;
|
|
304
386
|
/**
|
|
305
387
|
* Writes one line in a project's timeline (a deployment triggered from a
|
|
306
388
|
* project's tab). Open tier only: an event aimed at a guarded project is
|
|
@@ -393,3 +475,23 @@ export interface SentinelAgentConfigProvider {
|
|
|
393
475
|
/** The device's contribution, or null when Sentinel knows nothing about it (probes off). */
|
|
394
476
|
configFor(deviceId: string): Promise<SentinelAgentConfig | null>;
|
|
395
477
|
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* The plan of an account: what bounds the quotas modules declare
|
|
481
|
+
* (`manifest.quotas`). Offered by a billing module. WITHOUT it every quota is
|
|
482
|
+
* unlimited, which is what a self-hosted DevEye is.
|
|
483
|
+
*/
|
|
484
|
+
export const ACCOUNT_PLAN_PROVIDER = 'account.plan';
|
|
485
|
+
|
|
486
|
+
export interface AccountPlan {
|
|
487
|
+
id: string;
|
|
488
|
+
label: string;
|
|
489
|
+
/** `<featureId>.<quotaKey>` to its maximum. An absent key is unlimited. */
|
|
490
|
+
limits: Readonly<Record<string, number>>;
|
|
491
|
+
/** The plan is a trial ending then (ms since the epoch). */
|
|
492
|
+
trialEndsAt?: number;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export interface AccountPlanProvider {
|
|
496
|
+
planFor(userId: number): Promise<AccountPlan>;
|
|
497
|
+
}
|