@deveye/types 0.20.1 → 0.20.3

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
@@ -5,10 +5,13 @@ import type { FeatureAccess } from '../domain/workspaceRole';
5
5
  import type { LogLevelName } from '../domain/logs';
6
6
  import type { ItemAccess } from '../domain/sharing';
7
7
  import type { AuthWindow, DeviceReport, IntegrityReport, ReportProcess } from '../domain/report';
8
+ import type { ContainerEngine, DockerAction, DockerInventory } from '../domain/deviceDocker';
9
+ import type { PathExclusion } from '../domain/pathExclusions';
8
10
  import type { AgentManifest } from '../http/device';
9
11
  import type { MetricSnapshot } from '../domain/metrics';
10
12
  import type { UserColor } from '../domain/user';
11
13
  import type { SdkDnsRecord } from './domains';
14
+ import type { ModuleEnvSpec } from './env';
12
15
  import type {
13
16
  AgentSyncAckPayload,
14
17
  AgentSyncApplyChunkPayload,
@@ -32,6 +35,16 @@ import type {
32
35
  } from '../protocol/agent';
33
36
 
34
37
  export { isPublicIp, isSafePublicUrl } from './net';
38
+ export {
39
+ defineModuleEnv,
40
+ MODULE_ENV_NAME_PATTERN,
41
+ moduleEnvProblem,
42
+ readModuleEnv,
43
+ type ModuleEnvDefault,
44
+ type ModuleEnvSpec,
45
+ type ModuleEnvValues,
46
+ type ModuleEnvVar
47
+ } from './env';
35
48
  export {
36
49
  DOMAIN_HOST_PATTERN,
37
50
  domainOwnershipRecord,
@@ -268,15 +281,15 @@ export interface DevEyeFacade {
268
281
  /** Requires capability `'devices.read'`. */
269
282
  devices: {
270
283
  /**
271
- * Throws `not_found` unless the device exists AND belongs to this
272
- * workspace (a global administrator passes the membership check).
273
- */
274
- authorize(deviceId: string): Promise<SdkDevice>;
275
- /**
276
- * The devices this workspace sees: its own, or the whole fleet for a
277
- * global administrator in their PERSONAL workspace (the app's own rule
278
- * for its device list: that is where an admin watches their machines).
284
+ * Throws `not_found` unless the device exists AND is visible in this
285
+ * workspace (its own, or shared into it), a global administrator
286
+ * included: membership is the boundary. With `extras`, a handler also requires the CALLER to hold these
287
+ * permissions of the Devices feature on this device (`docker` to drive
288
+ * its containers), and throws `forbidden` otherwise: a module cannot
289
+ * name another feature's permissions in its own `access`.
279
290
  */
291
+ authorize(deviceId: string, options?: { extras?: readonly string[] }): Promise<SdkDevice>;
292
+ /** The devices this workspace sees: its own, and those shared into it. */
280
293
  list(): Promise<readonly SdkDevice[]>;
281
294
  isOnline(deviceId: string): boolean;
282
295
  };
@@ -316,26 +329,78 @@ export interface SdkAccounts {
316
329
  search(query: string, limit?: number): Promise<readonly SdkAccount[]>;
317
330
  }
318
331
 
332
+ /**
333
+ * The items of YOUR `stock` quotas that their owner's plan holds paused: the
334
+ * most recently created beyond the limit. Nothing of theirs is deleted; they
335
+ * resume on their own once the limit rises or a slot frees. A paused item
336
+ * stays readable, editable and deletable, and NOTHING of it runs: not on
337
+ * schedule, not on demand. Both reads are synchronous (an in-memory mirror),
338
+ * fit for a hot path. A key that is not a declared stock throws `validation`.
339
+ */
340
+ export interface SdkPlanPauses {
341
+ isPaused(key: string, itemId: string): boolean;
342
+ /**
343
+ * Every paused id of the key, whatever the account: exclude them IN THE
344
+ * SQL of a due list (`id NOT IN (...)`, guard the empty list). Filtering
345
+ * after its `LIMIT` would let the paused, whose timestamps never advance,
346
+ * fill the window and starve the rest.
347
+ */
348
+ paused(key: string): readonly string[];
349
+ }
350
+
319
351
  /**
320
352
  * What the account's plan allows of YOUR `manifest.quotas`. The account is the
321
353
  * OWNER of the workspace of the call: in a shared workspace, what a member
322
354
  * creates counts against its owner. Without a plan provider installed,
323
355
  * everything is unlimited.
324
356
  */
325
- export interface SdkQuota {
357
+ export interface SdkQuota extends SdkPlanPauses {
326
358
  /** `null` = unlimited. An undeclared key throws `validation`. */
327
359
  limit(key: string): Promise<number | null>;
328
360
  /**
329
361
  * Call it BEFORE creating. `countAfter` receives the ids of every workspace
330
362
  * the owner account owns and returns how many there would be once created;
331
363
  * it is never called when unlimited. Throws `quota_exceeded` beyond the
332
- * limit. Only creation is bounded: what exists stays usable after a
333
- * downgrade.
364
+ * limit.
334
365
  */
335
366
  assert(
336
367
  key: string,
337
368
  countAfter: (ownerWorkspaceIds: readonly number[]) => Promise<number>
338
369
  ): Promise<void>;
370
+ /**
371
+ * Call it before running a `stock` item on demand (check now, deploy now,
372
+ * open a session): throws `quota_exceeded` when its owner's plan holds it
373
+ * paused, which opens the plan prompt on the client.
374
+ */
375
+ assertActive(key: string, itemId: string): Promise<void>;
376
+ }
377
+
378
+ /** One item a `stock` quota counts. */
379
+ export interface SdkStockItem {
380
+ /**
381
+ * Your item's id when the quota counts your items: a move then checks the
382
+ * target owner's plan for it. Anything else the quota counts (a page an
383
+ * item publishes, which stays behind on a move) takes an id of its own.
384
+ */
385
+ id: string;
386
+ workspaceId: number;
387
+ }
388
+
389
+ /** What one reconciliation changed for one of your `stock` quotas. */
390
+ export interface SdkPlanPauseChange {
391
+ key: string;
392
+ paused: readonly SdkStockItem[];
393
+ resumed: readonly SdkStockItem[];
394
+ }
395
+
396
+ /** Your half of one `stock` quota: the host ranks, you list. */
397
+ export interface FeatureStockEntry<Repo = unknown> {
398
+ /**
399
+ * The items the quota counts in these workspaces, OLDEST FIRST (creation,
400
+ * then id), under the very WHERE of the counter you pass to `assert`. The
401
+ * host keeps the first `limit` running and pauses the rest.
402
+ */
403
+ list(repo: Repo, ownerWorkspaceIds: readonly number[]): Promise<readonly SdkStockItem[]>;
339
404
  }
340
405
 
341
406
  /** A workspace as the fleet sees it: enough to attach a device to it. */
@@ -354,16 +419,13 @@ export interface SdkWorkspaceSummary {
354
419
  export interface AgentsFacade {
355
420
  isOnline(deviceId: string): boolean;
356
421
  /**
357
- * The three orders a device's lifecycle gives the hub. `requestDestroy`
422
+ * The two orders a device's lifecycle gives the hub. `requestDestroy`
358
423
  * asks the agent to uninstall itself (deletion path); `disconnectAgent`
359
- * closes its socket now (a revoked or force-deleted device);
360
- * `resetAgentSession` drops what the hub remembered of it (a device
361
- * confirmed or reactivated starts clean). All three answer `false` when
362
- * the agent is not connected, which is not an error.
424
+ * closes its socket now (a revoked or force-deleted device). Both answer
425
+ * `false` when the agent is not connected, which is not an error.
363
426
  */
364
427
  requestDestroy(deviceId: string): boolean;
365
428
  disconnectAgent(deviceId: string): boolean;
366
- resetAgentSession(deviceId: string): boolean;
367
429
  /**
368
430
  * The manifest of the agent binaries the app serves (the build version and,
369
431
  * per target, whether the binary is signed), or null while nothing is
@@ -411,6 +473,35 @@ export interface AgentsFacade {
411
473
  awaitFilesOp(opId: string, timeoutMs: number): Promise<{ ok: boolean; error?: string }>;
412
474
  /** Forgets a pending `awaitFilesOp` (the frame was never sent, or the caller gave up). */
413
475
  cancelFilesOp(opId: string): void;
476
+ /**
477
+ * A Docker action on a device, for a caller without a socket (a
478
+ * deployment). Takes the device's long-action lock, which the Devices
479
+ * screens share: refused at once while another long action runs there.
480
+ * Streams the action's output lines to `onLine` and resolves with its
481
+ * verdict, a refusal by the machine's local policy included. Never throws.
482
+ */
483
+ dockerRun(
484
+ deviceId: string,
485
+ order: { engine: ContainerEngine; action: DockerAction; target: string | null },
486
+ options?: { onLine?: (line: string) => void; timeoutMs?: number }
487
+ ): Promise<{ ok: boolean; error?: string }>;
488
+ /** The device's containers, images and volumes; `null` when its agent does not answer in time. */
489
+ dockerInventory(deviceId: string, timeoutMs?: number): Promise<DockerInventory | null>;
490
+ /**
491
+ * The `.tar.gz` of one of the device's folders, built by its agent and
492
+ * pulled at the consumer's pace: the agent sends no more than the
493
+ * consumer has taken, so a slow destination slows the machine down
494
+ * instead of filling the server's memory. Leaving the loop, throwing in
495
+ * it or aborting `signal` cancels the archive on the machine. The stream
496
+ * throws when the device is or goes offline, and when its agent does not
497
+ * answer (one that predates the order): check `report.agent.probes` for
498
+ * `AGENT_FOLDER_ARCHIVE_PROBE` first to say so plainly.
499
+ */
500
+ archiveFolder(
501
+ deviceId: string,
502
+ request: AgentFolderArchiveRequest,
503
+ options?: { signal?: AbortSignal }
504
+ ): AgentFolderArchive;
414
505
  /**
415
506
  * Bytes queued on the agent's socket, not yet on the wire. A sender that
416
507
  * streams towards an agent must watch it: the socket accepts everything,
@@ -420,6 +511,39 @@ export interface AgentsFacade {
420
511
  buffered(deviceId: string): number;
421
512
  }
422
513
 
514
+ /** What a folder archive covers. */
515
+ export interface AgentFolderArchiveRequest {
516
+ /** Absolute path on the machine. */
517
+ path: string;
518
+ exclusions: readonly PathExclusion[];
519
+ /** Do not descend into another filesystem (a network mount, a removable disk). */
520
+ oneFileSystem: boolean;
521
+ }
522
+
523
+ /** How a folder archive went, once its stream has ended. */
524
+ export interface AgentFolderArchiveSummary {
525
+ files: number;
526
+ dirs: number;
527
+ bytesRead: number;
528
+ /** Entries left out because they could not be read. */
529
+ skipped: number;
530
+ /** Files whose size changed while they were read: archived padded or cut. */
531
+ changed: number;
532
+ /** The first skipped or changed entries, and why. */
533
+ samples: ReadonlyArray<{ path: string; reason: string }>;
534
+ }
535
+
536
+ /** The pieces of a folder archive, in order; `summary` is filled once they have all come. */
537
+ export interface AgentFolderArchive extends AsyncIterable<Buffer> {
538
+ readonly summary: AgentFolderArchiveSummary | null;
539
+ }
540
+
541
+ /** Why a member does not hold a permission (see `FeatureServiceDeps.access`). */
542
+ export type SdkAccessDenial =
543
+ 'not_member' | 'suspended' | 'level' | 'not_granted' | 'hidden' | 'read_only' | 'no_device';
544
+
545
+ export type SdkAccessVerdict = { ok: true } | { ok: false; reason: SdkAccessDenial };
546
+
423
547
  /**
424
548
  * The caller's own browser socket (capability `'agents'`): live subscriptions
425
549
  * and chunked downloads with backpressure. Mirrors the app's MonitorTransport
@@ -500,7 +624,7 @@ export interface SdkDevice {
500
624
  id: string;
501
625
  name: string;
502
626
  online: boolean;
503
- /** `active` is the only status whose telemetry the app records. */
627
+ /** `active` is the only status whose agent the socket admits. */
504
628
  status: string;
505
629
  /** The account that enrolled the device (the actor of its audit lines). */
506
630
  ownerUserId: number;
@@ -649,7 +773,8 @@ export interface SdkContextLive {
649
773
  /**
650
774
  * Something of this ACCOUNT changed (its plan, its subscription): its open
651
775
  * clients, in whatever workspace they sit, re-fetch the account plan and
652
- * your declared resources. No payload, so no capability.
776
+ * your declared resources, and the host re-applies its `stock` limits
777
+ * (pauses and resumes). No payload, so no capability.
653
778
  */
654
779
  accountChanged(userId: number): void;
655
780
  }
@@ -671,9 +796,15 @@ export interface SdkDomain {
671
796
  host: string;
672
797
  /** Published in the DNS by nature, so not a secret. */
673
798
  token: string;
674
- /** Both stages have passed, and neither has failed three times in a row since. */
799
+ /**
800
+ * Both stages have passed, neither has failed three times in a row since,
801
+ * and the owner's plan does not hold the name paused. What decides
802
+ * whether you serve it.
803
+ */
675
804
  verified: boolean;
676
805
  verifiedAt: number | null;
806
+ /** The owner's plan holds this name paused: it is not served until the limit rises. */
807
+ planPaused: boolean;
677
808
  }
678
809
 
679
810
  /** Your feature's domains in the caller's workspace. Throws `forbidden` unless the manifest declares `domains`. */
@@ -699,10 +830,17 @@ export interface SdkDns {
699
830
  cname(name: string): Promise<string[]>;
700
831
  }
701
832
 
833
+ /** Where DevEye lives, see `SdkFeatureContext.origins`. */
834
+ export interface SdkOrigins {
835
+ app: string;
836
+ public: string;
837
+ site: string | null;
838
+ }
839
+
702
840
  /** What the domain hooks receive. Sessionless: they also run from the background pass. */
703
841
  export interface FeatureDomainsContext<Repo = unknown> {
704
842
  repo: Repo;
705
- origins: { app: string; public: string };
843
+ origins: SdkOrigins;
706
844
  /** Open tier only. */
707
845
  cipherFor(workspaceId: number): SdkCipher;
708
846
  storeFor(workspaceId: number): SessionlessFeatureStore;
@@ -789,11 +927,13 @@ export interface SdkFeatureContext<Repo = unknown> {
789
927
  * origin members use (`PUBLIC_ORIGIN`), `public` the one anyone reaches
790
928
  * the public routes by, which differs when the host serves them on a
791
929
  * domain of their own, the app itself possibly staying private (else the
792
- * same).
930
+ * same). `site` is the marketing site (`SITE_URL`), where the legal pages
931
+ * live (`/cgu`, `/cgv`, `/confidentialite`, `/mentions-legales`); `null`
932
+ * when the host has none.
793
933
  * For what a module hands to the outside world (an install snippet, a
794
934
  * callback URL): never derive it from the browser's location.
795
935
  */
796
- origins: { app: string; public: string };
936
+ origins: SdkOrigins;
797
937
  }
798
938
 
799
939
  /**
@@ -952,6 +1092,8 @@ export type SdkPublicStreamHandler = (
952
1092
  * Where a module declares its public routes (capability `'routes.public'`).
953
1093
  * Paths are absolute (`/t.js`, `/api/t/b`); a path the host already serves
954
1094
  * is refused at boot. Every route is registered on every public listener.
1095
+ * `/` belongs to the host: a page served at the root of a customer domain goes
1096
+ * through `FeatureService.domainRoot`.
955
1097
  */
956
1098
  export interface SdkPublicApp {
957
1099
  get(path: string, opts: SdkPublicRouteOptions, handler: SdkPublicHandler): void;
@@ -993,6 +1135,32 @@ export interface FeatureService {
993
1135
  * the outside; register the same routes each time.
994
1136
  */
995
1137
  publicRoutes?(app: SdkPublicApp): void;
1138
+ /**
1139
+ * The page served at the root (`GET /`) of one of YOUR verified web
1140
+ * domains, for a name that is the page itself (`status.example.com`)
1141
+ * rather than a prefix of your routes. Called only once the request's
1142
+ * host matched a verified domain of your feature, on every listener that
1143
+ * receives it, behind the maintenance gate. Route by `domain`, never by the
1144
+ * header. When several features verified the same name, the first
1145
+ * installed that declares `domainRoot` answers. Requires capability
1146
+ * `'routes.public'` and manifest `domains.web`.
1147
+ */
1148
+ domainRoot?(req: SdkPublicRequest, reply: SdkPublicReply, domain: SdkDomain): Promise<unknown>;
1149
+ /**
1150
+ * Your `stock` items that a plan just paused or resumed, once written: for
1151
+ * what you hold OPEN (a connection, a session, a timer). What you run on
1152
+ * schedule needs nothing here, it reads `SdkPlanPauses` each time. Never
1153
+ * called while your service is halted by maintenance.
1154
+ */
1155
+ onPlanPause?(change: SdkPlanPauseChange): void | Promise<void>;
1156
+ /**
1157
+ * An account is about to be deleted, with everything it owns: end what
1158
+ * you hold for it elsewhere (a subscription with a payment provider). Your
1159
+ * rows go with the account (`ON DELETE CASCADE`), nothing to do for them.
1160
+ * Runs before the row is deleted: a throw aborts the deletion. Never called
1161
+ * while your service is halted by maintenance: the deletion is refused then.
1162
+ */
1163
+ onAccountDeleted?(userId: number): void | Promise<void>;
996
1164
  }
997
1165
 
998
1166
  /**
@@ -1010,6 +1178,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
1010
1178
  deveyeFor(workspaceId: number): Pick<DevEyeFacade, 'notify'>;
1011
1179
  /** Devices of one workspace, sessionless (capability `'devices.read'`). */
1012
1180
  devicesFor(workspaceId: number): Pick<DevEyeFacade['devices'], 'list' | 'isOnline'>;
1181
+ /** Members of one workspace, owner included, sessionless (capability `'members.read'`): a name a public page shows. */
1182
+ membersFor(workspaceId: number): DevEyeFacade['members'];
1013
1183
  /** The whole fleet by id, sessionless (capability `'devices.read'`). */
1014
1184
  devices: SdkFleetDevices;
1015
1185
  /** Capability `'accounts.read'`. */
@@ -1020,6 +1190,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
1020
1190
  * owner of that workspace.
1021
1191
  */
1022
1192
  quotaFor(workspaceId: number): SdkQuota;
1193
+ /** Your paused `stock` items, whatever the workspace. */
1194
+ pauses: SdkPlanPauses;
1023
1195
  /** The devices' telemetry, sessionless (capability `'telemetry.read'`). */
1024
1196
  telemetry: SdkTelemetry;
1025
1197
  /** Live invalidation of your feature's resources, from a service. */
@@ -1037,12 +1209,35 @@ export interface FeatureServiceDeps<Repo = unknown> {
1037
1209
  }): void;
1038
1210
  /** The agent-fleet transport (capability `'agents'`). */
1039
1211
  agents: AgentsFacade;
1212
+ /**
1213
+ * What a member may do NOW, without a session: for work that runs on a
1214
+ * member's behalf long after they set it up (a nightly backup of their
1215
+ * machine), and must stop when they lose the right. The rules of a
1216
+ * command: account not suspended, membership, role, the item's
1217
+ * override. `feature` answers for YOUR feature only. `device` answers
1218
+ * for the Devices permissions on one device (capability
1219
+ * `'devices.read'`), with the rule of `devices.authorize`: an override
1220
+ * that lowers the device to read-only closes it.
1221
+ */
1222
+ access: {
1223
+ feature(
1224
+ workspaceId: number,
1225
+ userId: number,
1226
+ need: { level?: FeatureAccess; extras?: readonly string[]; itemId?: string }
1227
+ ): Promise<SdkAccessVerdict>;
1228
+ device(
1229
+ workspaceId: number,
1230
+ userId: number,
1231
+ deviceId: string,
1232
+ extras: readonly string[]
1233
+ ): Promise<SdkAccessVerdict>;
1234
+ };
1040
1235
  /** Raw key wrapping under the server key, and derived keys. */
1041
1236
  keys: SdkServerKeys;
1042
1237
  /** Redeems a ticket minted by `ctx.secrecy.ticket` of THIS module; `null` when invalid, expired or another module's. */
1043
1238
  secrecy: { redeem(ticket: string): Promise<SdkRedeemedTicket | null> };
1044
1239
  /** Where DevEye lives (the same `origins` a request context gets): for a page or a link a route hands to the browser. */
1045
- origins: { app: string; public: string };
1240
+ origins: SdkOrigins;
1046
1241
  /** Your feature's domains, whatever the workspace (manifest `domains`). */
1047
1242
  domains: SdkFleetDomains;
1048
1243
  /** The named contracts the host holds, see `SdkProviders`. */
@@ -1080,6 +1275,14 @@ export interface FeatureServer<Repo = unknown> {
1080
1275
  items?: FeatureItemsEntry<Repo>;
1081
1276
  /** Required when the manifest declares `domains`, refused otherwise. */
1082
1277
  domains?: FeatureDomainsEntry<Repo>;
1278
+ /** One entry per `stock` quota of the manifest, by its key, and none other. */
1279
+ quotas?: Readonly<Record<string, FeatureStockEntry<Repo>>>;
1280
+ /**
1281
+ * The environment variables you read, as the spec you read them with
1282
+ * (`defineModuleEnv`). Plain data: the host reads it again at boot and
1283
+ * warns about every variable left to its default.
1284
+ */
1285
+ env?: ModuleEnvSpec;
1083
1286
  }
1084
1287
 
1085
1288
  /**
@@ -42,7 +42,8 @@ test('createTestContext follows the manifest for extras, and records what handle
42
42
  test('createTestServiceDeps: one store per workspace, hand-driven tickers, a wrapper that round-trips', async () => {
43
43
  const deps = createTestServiceDeps({
44
44
  workspaceIds: [1, 2],
45
- devices: [testDevice({ id: 'd1', name: 'One', online: false })]
45
+ devices: [testDevice({ id: 'd1', name: 'One', online: false })],
46
+ members: { 2: [{ userId: 5, name: 'Alice', isOwner: true, color: null }] }
46
47
  });
47
48
  assert.deepEqual(await deps.listWorkspaceIds(), [1, 2]);
48
49
  await deps.storeFor(1).put('a', '1');
@@ -65,6 +66,12 @@ test('createTestServiceDeps: one store per workspace, hand-driven tickers, a wra
65
66
 
66
67
  assert.equal(deps.devicesFor(1).isOnline('d1'), false);
67
68
  assert.equal((await deps.devicesFor(1).list()).length, 1);
69
+
70
+ assert.deepEqual(
71
+ (await deps.membersFor(2).list()).map((m) => m.name),
72
+ ['Alice']
73
+ );
74
+ assert.deepEqual(await deps.membersFor(1).list(), []);
68
75
  });
69
76
 
70
77
  test('the harness searches accounts like the app: substring, exact id first, capped', async () => {
@@ -136,3 +143,17 @@ test('the harness bounds a quota like the app: never counted when unlimited, ref
136
143
  bounded.live.accountChanged(7);
137
144
  assert.deepEqual(bounded.recorded.accountChanges, [7]);
138
145
  });
146
+
147
+ test('the harnesses hold the plan pauses and refuse a paused item on demand', async () => {
148
+ const ctx = createTestContext({ pausedItems: { monitors: ['7'] } });
149
+ assert.equal(ctx.quota.isPaused('monitors', '7'), true);
150
+ assert.equal(ctx.quota.isPaused('monitors', '8'), false);
151
+ assert.deepEqual(ctx.quota.paused('monitors'), ['7']);
152
+ await assert.rejects(ctx.quota.assertActive('monitors', '7'), { code: 'quota_exceeded' });
153
+ await ctx.quota.assertActive('monitors', '8');
154
+
155
+ const deps = createTestServiceDeps({ pausedItems: { monitors: ['7'] } });
156
+ assert.equal(deps.pauses.isPaused('monitors', '7'), true);
157
+ assert.deepEqual(deps.quotaFor(1).paused('monitors'), ['7']);
158
+ assert.deepEqual(createTestServiceDeps().pauses.paused('monitors'), []);
159
+ });