@deveye/types 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sdk/server.ts CHANGED
@@ -9,6 +9,7 @@ import type { LogLevelName } from '../domain/logs';
9
9
  import type { ItemAccess } from '../domain/sharing';
10
10
  import type { AuthWindow, DeviceReport, IntegrityReport, ReportProcess } from '../domain/report';
11
11
  import type { ContainerEngine, DockerAction, DockerInventory } from '../domain/deviceDocker';
12
+ import type { PackageInventory } from '../protocol/agent';
12
13
  import type { PathExclusion } from '../domain/pathExclusions';
13
14
  import type { AgentManifest } from '../http/device';
14
15
  import type { MetricSnapshot } from '../domain/metrics';
@@ -769,6 +770,11 @@ export interface AgentsFacade {
769
770
  ): Promise<{ ok: boolean; error?: string }>;
770
771
  /** The device's containers, images and volumes; `null` when its agent does not answer in time. */
771
772
  dockerInventory(deviceId: string, timeoutMs?: number): Promise<DockerInventory | null>;
773
+ /**
774
+ * The system packages installed on the device; `null` when its agent does
775
+ * not answer in time, or is older than `AGENT_PKG_INVENTORY_PROBE`.
776
+ */
777
+ packageInventory(deviceId: string, timeoutMs?: number): Promise<PackageInventory | null>;
772
778
  /**
773
779
  * The `.tar.gz` of one of the device's folders, built by its agent and
774
780
  * pulled at the consumer's pace: the agent sends no more than the
@@ -1096,6 +1102,63 @@ export interface SdkSharing {
1096
1102
  setOrder(itemId: string, order: number): Promise<void>;
1097
1103
  }
1098
1104
 
1105
+ /** What a service says of a long operation when it opens it. */
1106
+ export interface SdkTaskOpening {
1107
+ /** The account the operation runs for: the member who asked for it. Only that account sees it. */
1108
+ userId: number;
1109
+ workspaceId: number;
1110
+ /** What is being done, as a noun phrase: "Sauvegarde", "Conversion". */
1111
+ title: string;
1112
+ /** What it acts on (a name), to tell two operations with the same title apart. */
1113
+ subject?: string;
1114
+ /** The item it targets: "Ouvrir" leads there, and the screens of your feature filter on it. */
1115
+ itemId?: string | number;
1116
+ /**
1117
+ * The kind of operation. With a `key`, opening the same
1118
+ * `(workspaceId, itemId, key)` again for the same account returns the
1119
+ * operation already running instead of a second one: call `open` each
1120
+ * time you find the work again (a queue you poll, a restart).
1121
+ */
1122
+ key?: string;
1123
+ /**
1124
+ * Offers "Annuler" in the account's area. Called once, when the person
1125
+ * asks; stop the work, then call `cancelled()`.
1126
+ */
1127
+ cancel?: () => void | Promise<void>;
1128
+ }
1129
+
1130
+ /** A long operation a service runs, see {@link SdkTasks}. Every call after the first ending is ignored. */
1131
+ export interface SdkTask {
1132
+ readonly id: string;
1133
+ /** How far it is: at most four updates a second leave, the last one always. */
1134
+ progress(update: CommandProgress): void;
1135
+ /** It succeeded; `note` is the sentence of the outcome ("Terminé." without it). */
1136
+ done(note?: string): void;
1137
+ /**
1138
+ * It failed; `message` is the sentence to show. `code` decides whether the
1139
+ * person is offered to report it: `internal` (the default) for what the
1140
+ * instance must fix, `conflict` for what their side explains.
1141
+ */
1142
+ fail(message: string, code?: ErrorCode): void;
1143
+ /** It stopped because the person asked: it leaves the area without an outcome. */
1144
+ cancelled(): void;
1145
+ }
1146
+
1147
+ /**
1148
+ * The operations area of an account, from a service: the work a member
1149
+ * launched and that goes on without their command (a backup, a deployment, a
1150
+ * conversion). The host stamps your feature and shows the operation to that
1151
+ * account only, in every tab, once it has checked the account still reads
1152
+ * your feature in that workspace; a restart of the server forgets it, so open
1153
+ * it again when your service resumes the work.
1154
+ *
1155
+ * Not for what runs on its own (a schedule, a reconciliation): nobody asked
1156
+ * for it, so it belongs to your screens, not to someone's area.
1157
+ */
1158
+ export interface SdkTasks {
1159
+ open(opening: SdkTaskOpening): SdkTask;
1160
+ }
1161
+
1099
1162
  /** Live invalidation from a background service, which writes without a command. */
1100
1163
  export interface SdkLive {
1101
1164
  /**
@@ -1327,7 +1390,9 @@ export interface SdkFeatureContext<Repo = unknown> {
1327
1390
  * Report how far this command has got, to its caller only. Best effort, at
1328
1391
  * most 4 frames a second (the last one always goes out); each frame re-arms
1329
1392
  * the caller's timeout, so a long command that keeps reporting never times
1330
- * out. Steps are user-facing sentences.
1393
+ * out. Steps are user-facing sentences: when the caller runs the command
1394
+ * as a long operation (`runTask`), they also show in the operations area of
1395
+ * the account, in every tab.
1331
1396
  */
1332
1397
  progress(update: CommandProgress): void;
1333
1398
  /** The server key derivations, the same `keys` a service gets. */
@@ -1713,6 +1778,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
1713
1778
  geo: SdkGeo;
1714
1779
  /** Live invalidation of your feature's resources, from a service. */
1715
1780
  live: SdkLive;
1781
+ /** The long operations a member launched and your service runs. */
1782
+ tasks: SdkTasks;
1716
1783
  /**
1717
1784
  * Audit line recorded as the SYSTEM (no session). `userId` attributes the
1718
1785
  * line to a user when the work concerns their data.
@@ -39,6 +39,24 @@ test('createTestContext follows the manifest for extras, and records what handle
39
39
  assert.equal(member.store.rows.get('k')?.mode, 'private');
40
40
  });
41
41
 
42
+ test('notify refuses, as the host does, a manifest without the capability', async () => {
43
+ const manifest = { nativeCapabilities: ['members.read' as const] };
44
+ const ctx = createTestContext({ manifest });
45
+ await assert.rejects(ctx.deveye.notify.send({ subject: 's', body: 'b' }), {
46
+ code: 'forbidden'
47
+ });
48
+ await assert.rejects(ctx.deveye.notify.hasRoute(), { code: 'forbidden' });
49
+ assert.deepEqual(ctx.recorded.notifications, []);
50
+
51
+ const deps = createTestServiceDeps({ manifest });
52
+ await assert.rejects(deps.deveyeFor(1).notify.send({ subject: 's', body: 'b' }), {
53
+ code: 'forbidden'
54
+ });
55
+
56
+ const declared = createTestContext({ manifest: { nativeCapabilities: ['notify' as const] } });
57
+ assert.equal(await declared.deveye.notify.send({ subject: 's', body: 'b' }), true);
58
+ });
59
+
42
60
  test('createTestServiceDeps: one store per workspace, hand-driven tickers, a wrapper that round-trips', async () => {
43
61
  const deps = createTestServiceDeps({
44
62
  workspaceIds: [1, 2],
@@ -3,11 +3,12 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
 
5
5
  import type { ZodType } from 'zod';
6
+ import type { ErrorCode } from '../protocol/error';
6
7
  import { DEFAULT_METRIC_INTERVAL_SECONDS } from '../domain/device';
7
8
  import type { ItemAccess } from '../domain/sharing';
8
9
  import type { PathExclusion } from '../domain/pathExclusions';
9
10
  import { normaliseDomainHost } from './domains';
10
- import { resolveExtras, type FeatureManifest } from './manifest';
11
+ import { resolveExtras, type FeatureManifest, type NativeCapability } from './manifest';
11
12
  import {
12
13
  FeatureError,
13
14
  type AgentFolderArchive,
@@ -33,6 +34,7 @@ import {
33
34
  type SdkPlanPauses,
34
35
  type SdkProviders,
35
36
  type SdkQuota,
37
+ type SdkTaskOpening,
36
38
  type SdkTelemetry,
37
39
  type SdkTelemetrySnapshot,
38
40
  type StorageEncryption,
@@ -162,12 +164,26 @@ function recordingNotify(
162
164
  recorded: RecordedCalls,
163
165
  hasRoute: boolean,
164
166
  accepted: boolean,
165
- liveChannels: readonly number[]
167
+ liveChannels: readonly number[],
168
+ capabilities: readonly NativeCapability[] | undefined
166
169
  ): DevEyeFacade['notify'] {
167
170
  let posted = 0;
171
+ // The host refuses every notify call of a module that did not declare the
172
+ // capability: a test that hands its manifest gets the same refusal.
173
+ const refused = (): Promise<never> | null =>
174
+ capabilities && !capabilities.includes('notify')
175
+ ? Promise.reject(
176
+ new FeatureError(
177
+ 'forbidden',
178
+ "Declare 'notify' in the manifest's nativeCapabilities"
179
+ )
180
+ )
181
+ : null;
168
182
  return {
169
- hasRoute: () => Promise.resolve(hasRoute),
183
+ hasRoute: () => refused() ?? Promise.resolve(hasRoute),
170
184
  send(alert, opts) {
185
+ const refusal = refused();
186
+ if (refusal) return refusal;
171
187
  recorded.notifications.push({
172
188
  subject: alert.subject,
173
189
  body: alert.body,
@@ -182,8 +198,10 @@ function recordingNotify(
182
198
  // answers false, so a test sees what the module does with it.
183
199
  return Promise.resolve(accepted);
184
200
  },
185
- liveChannels: () => Promise.resolve(liveChannels.map((id) => ({ id }))),
201
+ liveChannels: () => refused() ?? Promise.resolve(liveChannels.map((id) => ({ id }))),
186
202
  postLive(channelId, message, messageId) {
203
+ const refusal = refused();
204
+ if (refusal) return refusal;
187
205
  recorded.liveMessages.push({
188
206
  channelId,
189
207
  messageId: messageId ?? null,
@@ -259,6 +277,7 @@ export interface TestFolderArchive {
259
277
  interface TestAgents {
260
278
  dockerRun?: DevEyeFacade['agents']['dockerRun'];
261
279
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
280
+ packageInventory?: DevEyeFacade['agents']['packageInventory'];
262
281
  /** By device id. A device without an entry answers nothing: its stream throws. */
263
282
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
264
283
  openTcp?: DevEyeFacade['agents']['openTcp'];
@@ -352,6 +371,10 @@ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevE
352
371
  docker.dockerInventory
353
372
  ? docker.dockerInventory(deviceId, timeoutMs)
354
373
  : Promise.resolve(null),
374
+ packageInventory: (deviceId, timeoutMs) =>
375
+ docker.packageInventory
376
+ ? docker.packageInventory(deviceId, timeoutMs)
377
+ : Promise.resolve(null),
355
378
  archiveFolder(deviceId, request) {
356
379
  recorded.agentRequests.push({ method: 'archiveFolder', deviceId });
357
380
  recorded.archiveRequests.push({ deviceId, ...request });
@@ -484,10 +507,12 @@ export interface TestContextOverrides<Repo> {
484
507
  extras?: Record<string, boolean | string>;
485
508
  /**
486
509
  * Your manifest: `canExtra` / `extraValue` then follow the exact runtime
487
- * rules ({@link resolveExtras}). Without it no extra is declared, so
488
- * every key answers `false` / `''`, owner or not.
510
+ * rules ({@link resolveExtras}), and `deveye.notify` refuses, as the host
511
+ * does, a module that did not declare `'notify'`. Without it no extra is
512
+ * declared, so every key answers `false` / `''`, owner or not, and no
513
+ * capability is checked.
489
514
  */
490
- manifest?: Pick<FeatureManifest, 'extraPermissions'>;
515
+ manifest?: Pick<FeatureManifest, 'extraPermissions' | 'nativeCapabilities'>;
491
516
  /** What `deveye.notify.hasRoute` answers. Default true. */
492
517
  hasRoute?: boolean;
493
518
  /** What `deveye.notify.send` resolves (no usable channel: false). Default true; recorded either way. */
@@ -507,6 +532,8 @@ export interface TestContextOverrides<Repo> {
507
532
  dockerRun?: DevEyeFacade['agents']['dockerRun'];
508
533
  /** What `deveye.agents.dockerInventory` resolves. Default null (no answer). */
509
534
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
535
+ /** What `deveye.agents.packageInventory` resolves. Default null (no answer). */
536
+ packageInventory?: DevEyeFacade['agents']['packageInventory'];
510
537
  /** What `deveye.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
511
538
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
512
539
  /** What `deveye.agents.openTcp` resolves. Default a rejection, as for an offline device. */
@@ -565,7 +592,8 @@ export function createTestContext<Repo = undefined>(
565
592
  recorded,
566
593
  overrides.hasRoute ?? true,
567
594
  overrides.notifyAccepted ?? true,
568
- overrides.liveChannels ?? []
595
+ overrides.liveChannels ?? [],
596
+ overrides.manifest?.nativeCapabilities
569
597
  ),
570
598
  mail: { listAccounts: () => Promise.resolve([]) },
571
599
  members: {
@@ -792,6 +820,21 @@ export interface RecordedServiceCalls extends RecordedCalls {
792
820
  mails: { userId: number; to: string; message: SdkAccountMailMessage }[];
793
821
  /** What `alertInstance` raised, in order, keys as the module gave them. */
794
822
  instanceAlerts: SdkInstanceAlert[];
823
+ /** The operations opened through `tasks.open`, in order, each with what the service then said of it. */
824
+ tasks: RecordedTask[];
825
+ }
826
+
827
+ /** One operation a service opened, as a test reads it. `cancel` is the callback it gave: call it to play "Annuler". */
828
+ export interface RecordedTask extends Omit<SdkTaskOpening, 'cancel'> {
829
+ id: string;
830
+ cancel?: () => void | Promise<void>;
831
+ updates: CommandProgress[];
832
+ /** `null` while it runs. */
833
+ outcome:
834
+ | { state: 'done'; note?: string }
835
+ | { state: 'failed'; message: string; code: ErrorCode }
836
+ | { state: 'cancelled' }
837
+ | null;
795
838
  }
796
839
 
797
840
  export interface TestServiceDeps<Repo> extends FeatureServiceDeps<Repo> {
@@ -802,6 +845,8 @@ export interface TestServiceDeps<Repo> extends FeatureServiceDeps<Repo> {
802
845
 
803
846
  export interface TestServiceOverrides<Repo> {
804
847
  repo?: Repo;
848
+ /** Your manifest: `deveyeFor(...).notify` then refuses, as the host does, a module that did not declare `'notify'`. */
849
+ manifest?: Pick<FeatureManifest, 'nativeCapabilities'>;
805
850
  /** What `listWorkspaceIds` answers. Default `[1]`. */
806
851
  workspaceIds?: readonly number[];
807
852
  /** Devices every workspace reveals. Default none. */
@@ -812,6 +857,8 @@ export interface TestServiceOverrides<Repo> {
812
857
  dockerRun?: DevEyeFacade['agents']['dockerRun'];
813
858
  /** What `deps.agents.dockerInventory` resolves. Default null (no answer). */
814
859
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
860
+ /** What `deps.agents.packageInventory` resolves. Default null (no answer). */
861
+ packageInventory?: DevEyeFacade['agents']['packageInventory'];
815
862
  /** What `deps.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
816
863
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
817
864
  /** What `deps.agents.openTcp` resolves. Default a rejection, as for an offline device. */
@@ -874,7 +921,8 @@ export function createTestServiceDeps<Repo = undefined>(
874
921
  liveChanges: [],
875
922
  liveTopicChanges: [],
876
923
  mails: [],
877
- instanceAlerts: []
924
+ instanceAlerts: [],
925
+ tasks: []
878
926
  };
879
927
  const stores = new Map<number, TestFeatureStore>();
880
928
  const sealedBytes = new Map<string, Uint8Array>();
@@ -882,7 +930,8 @@ export function createTestServiceDeps<Repo = undefined>(
882
930
  recorded,
883
931
  overrides.hasRoute ?? true,
884
932
  overrides.notifyAccepted ?? true,
885
- overrides.liveChannels ?? []
933
+ overrides.liveChannels ?? [],
934
+ overrides.manifest?.nativeCapabilities
886
935
  );
887
936
  const devices = recordingDevices(overrides.devices ?? []);
888
937
  const pauses = memoryPauses(overrides.pausedItems);
@@ -946,6 +995,44 @@ export function createTestServiceDeps<Repo = undefined>(
946
995
  country: (ip) => overrides.countries?.[ip] ?? null,
947
996
  attribution: { text: 'IP Geolocation by DB-IP', url: 'https://db-ip.com' }
948
997
  },
998
+ tasks: {
999
+ open(opening) {
1000
+ // The host's rule: the same keyed work, found again while it runs, is the same operation.
1001
+ const running =
1002
+ opening.key === undefined
1003
+ ? undefined
1004
+ : recorded.tasks.find(
1005
+ (t) =>
1006
+ t.outcome === null &&
1007
+ t.userId === opening.userId &&
1008
+ t.workspaceId === opening.workspaceId &&
1009
+ t.key === opening.key &&
1010
+ String(t.itemId ?? '') === String(opening.itemId ?? '')
1011
+ );
1012
+ const task: RecordedTask = running ?? {
1013
+ ...opening,
1014
+ id: `task-${recorded.tasks.length + 1}`,
1015
+ updates: [],
1016
+ outcome: null
1017
+ };
1018
+ if (running) running.cancel = opening.cancel;
1019
+ else recorded.tasks.push(task);
1020
+ const settle = (outcome: NonNullable<RecordedTask['outcome']>): void => {
1021
+ task.outcome ??= outcome;
1022
+ };
1023
+ return {
1024
+ id: task.id,
1025
+ progress: (update) => {
1026
+ if (task.outcome === null) task.updates.push(update);
1027
+ },
1028
+ done: (note) =>
1029
+ settle(note === undefined ? { state: 'done' } : { state: 'done', note }),
1030
+ fail: (message, code = 'internal') =>
1031
+ settle({ state: 'failed', message, code }),
1032
+ cancelled: () => settle({ state: 'cancelled' })
1033
+ };
1034
+ }
1035
+ },
949
1036
  live: {
950
1037
  changed(workspaceId, topics) {
951
1038
  recorded.liveChanges.push(workspaceId);