@deveye/types 0.20.0 → 0.20.2

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. */
@@ -411,6 +476,35 @@ export interface AgentsFacade {
411
476
  awaitFilesOp(opId: string, timeoutMs: number): Promise<{ ok: boolean; error?: string }>;
412
477
  /** Forgets a pending `awaitFilesOp` (the frame was never sent, or the caller gave up). */
413
478
  cancelFilesOp(opId: string): void;
479
+ /**
480
+ * A Docker action on a device, for a caller without a socket (a
481
+ * deployment). Takes the device's long-action lock, which the Devices
482
+ * screens share: refused at once while another long action runs there.
483
+ * Streams the action's output lines to `onLine` and resolves with its
484
+ * verdict, a refusal by the machine's local policy included. Never throws.
485
+ */
486
+ dockerRun(
487
+ deviceId: string,
488
+ order: { engine: ContainerEngine; action: DockerAction; target: string | null },
489
+ options?: { onLine?: (line: string) => void; timeoutMs?: number }
490
+ ): Promise<{ ok: boolean; error?: string }>;
491
+ /** The device's containers, images and volumes; `null` when its agent does not answer in time. */
492
+ dockerInventory(deviceId: string, timeoutMs?: number): Promise<DockerInventory | null>;
493
+ /**
494
+ * The `.tar.gz` of one of the device's folders, built by its agent and
495
+ * pulled at the consumer's pace: the agent sends no more than the
496
+ * consumer has taken, so a slow destination slows the machine down
497
+ * instead of filling the server's memory. Leaving the loop, throwing in
498
+ * it or aborting `signal` cancels the archive on the machine. The stream
499
+ * throws when the device is or goes offline, and when its agent does not
500
+ * answer (one that predates the order): check `report.agent.probes` for
501
+ * `AGENT_FOLDER_ARCHIVE_PROBE` first to say so plainly.
502
+ */
503
+ archiveFolder(
504
+ deviceId: string,
505
+ request: AgentFolderArchiveRequest,
506
+ options?: { signal?: AbortSignal }
507
+ ): AgentFolderArchive;
414
508
  /**
415
509
  * Bytes queued on the agent's socket, not yet on the wire. A sender that
416
510
  * streams towards an agent must watch it: the socket accepts everything,
@@ -420,6 +514,39 @@ export interface AgentsFacade {
420
514
  buffered(deviceId: string): number;
421
515
  }
422
516
 
517
+ /** What a folder archive covers. */
518
+ export interface AgentFolderArchiveRequest {
519
+ /** Absolute path on the machine. */
520
+ path: string;
521
+ exclusions: readonly PathExclusion[];
522
+ /** Do not descend into another filesystem (a network mount, a removable disk). */
523
+ oneFileSystem: boolean;
524
+ }
525
+
526
+ /** How a folder archive went, once its stream has ended. */
527
+ export interface AgentFolderArchiveSummary {
528
+ files: number;
529
+ dirs: number;
530
+ bytesRead: number;
531
+ /** Entries left out because they could not be read. */
532
+ skipped: number;
533
+ /** Files whose size changed while they were read: archived padded or cut. */
534
+ changed: number;
535
+ /** The first skipped or changed entries, and why. */
536
+ samples: ReadonlyArray<{ path: string; reason: string }>;
537
+ }
538
+
539
+ /** The pieces of a folder archive, in order; `summary` is filled once they have all come. */
540
+ export interface AgentFolderArchive extends AsyncIterable<Buffer> {
541
+ readonly summary: AgentFolderArchiveSummary | null;
542
+ }
543
+
544
+ /** Why a member does not hold a permission (see `FeatureServiceDeps.access`). */
545
+ export type SdkAccessDenial =
546
+ 'not_member' | 'suspended' | 'level' | 'not_granted' | 'hidden' | 'read_only' | 'no_device';
547
+
548
+ export type SdkAccessVerdict = { ok: true } | { ok: false; reason: SdkAccessDenial };
549
+
423
550
  /**
424
551
  * The caller's own browser socket (capability `'agents'`): live subscriptions
425
552
  * and chunked downloads with backpressure. Mirrors the app's MonitorTransport
@@ -649,7 +776,8 @@ export interface SdkContextLive {
649
776
  /**
650
777
  * Something of this ACCOUNT changed (its plan, its subscription): its open
651
778
  * clients, in whatever workspace they sit, re-fetch the account plan and
652
- * your declared resources. No payload, so no capability.
779
+ * your declared resources, and the host re-applies its `stock` limits
780
+ * (pauses and resumes). No payload, so no capability.
653
781
  */
654
782
  accountChanged(userId: number): void;
655
783
  }
@@ -671,9 +799,15 @@ export interface SdkDomain {
671
799
  host: string;
672
800
  /** Published in the DNS by nature, so not a secret. */
673
801
  token: string;
674
- /** Both stages have passed, and neither has failed three times in a row since. */
802
+ /**
803
+ * Both stages have passed, neither has failed three times in a row since,
804
+ * and the owner's plan does not hold the name paused. What decides
805
+ * whether you serve it.
806
+ */
675
807
  verified: boolean;
676
808
  verifiedAt: number | null;
809
+ /** The owner's plan holds this name paused: it is not served until the limit rises. */
810
+ planPaused: boolean;
677
811
  }
678
812
 
679
813
  /** Your feature's domains in the caller's workspace. Throws `forbidden` unless the manifest declares `domains`. */
@@ -699,10 +833,17 @@ export interface SdkDns {
699
833
  cname(name: string): Promise<string[]>;
700
834
  }
701
835
 
836
+ /** Where DevEye lives, see `SdkFeatureContext.origins`. */
837
+ export interface SdkOrigins {
838
+ app: string;
839
+ public: string;
840
+ site: string | null;
841
+ }
842
+
702
843
  /** What the domain hooks receive. Sessionless: they also run from the background pass. */
703
844
  export interface FeatureDomainsContext<Repo = unknown> {
704
845
  repo: Repo;
705
- origins: { app: string; public: string };
846
+ origins: SdkOrigins;
706
847
  /** Open tier only. */
707
848
  cipherFor(workspaceId: number): SdkCipher;
708
849
  storeFor(workspaceId: number): SessionlessFeatureStore;
@@ -786,12 +927,16 @@ export interface SdkFeatureContext<Repo = unknown> {
786
927
  live: SdkContextLive;
787
928
  /**
788
929
  * Where DevEye lives, as URLs without a trailing slash: `app` is the
789
- * origin members use (`PUBLIC_ORIGIN`), `public` the one reachable
790
- * without the VPN when the host has a public surface (else the same).
930
+ * origin members use (`PUBLIC_ORIGIN`), `public` the one anyone reaches
931
+ * the public routes by, which differs when the host serves them on a
932
+ * domain of their own, the app itself possibly staying private (else the
933
+ * same). `site` is the marketing site (`SITE_URL`), where the legal pages
934
+ * live (`/cgu`, `/cgv`, `/confidentialite`, `/mentions-legales`); `null`
935
+ * when the host has none.
791
936
  * For what a module hands to the outside world (an install snippet, a
792
937
  * callback URL): never derive it from the browser's location.
793
938
  */
794
- origins: { app: string; public: string };
939
+ origins: SdkOrigins;
795
940
  }
796
941
 
797
942
  /**
@@ -950,6 +1095,8 @@ export type SdkPublicStreamHandler = (
950
1095
  * Where a module declares its public routes (capability `'routes.public'`).
951
1096
  * Paths are absolute (`/t.js`, `/api/t/b`); a path the host already serves
952
1097
  * is refused at boot. Every route is registered on every public listener.
1098
+ * `/` belongs to the host: a page served at the root of a customer domain goes
1099
+ * through `FeatureService.domainRoot`.
953
1100
  */
954
1101
  export interface SdkPublicApp {
955
1102
  get(path: string, opts: SdkPublicRouteOptions, handler: SdkPublicHandler): void;
@@ -991,6 +1138,32 @@ export interface FeatureService {
991
1138
  * the outside; register the same routes each time.
992
1139
  */
993
1140
  publicRoutes?(app: SdkPublicApp): void;
1141
+ /**
1142
+ * The page served at the root (`GET /`) of one of YOUR verified web
1143
+ * domains, for a name that is the page itself (`status.example.com`)
1144
+ * rather than a prefix of your routes. Called only once the request's
1145
+ * host matched a verified domain of your feature, on every listener that
1146
+ * receives it, behind the maintenance gate. Route by `domain`, never by the
1147
+ * header. When several features verified the same name, the first
1148
+ * installed that declares `domainRoot` answers. Requires capability
1149
+ * `'routes.public'` and manifest `domains.web`.
1150
+ */
1151
+ domainRoot?(req: SdkPublicRequest, reply: SdkPublicReply, domain: SdkDomain): Promise<unknown>;
1152
+ /**
1153
+ * Your `stock` items that a plan just paused or resumed, once written: for
1154
+ * what you hold OPEN (a connection, a session, a timer). What you run on
1155
+ * schedule needs nothing here, it reads `SdkPlanPauses` each time. Never
1156
+ * called while your service is halted by maintenance.
1157
+ */
1158
+ onPlanPause?(change: SdkPlanPauseChange): void | Promise<void>;
1159
+ /**
1160
+ * An account is about to be deleted, with everything it owns: end what
1161
+ * you hold for it elsewhere (a subscription with a payment provider). Your
1162
+ * rows go with the account (`ON DELETE CASCADE`), nothing to do for them.
1163
+ * Runs before the row is deleted: a throw aborts the deletion. Never called
1164
+ * while your service is halted by maintenance: the deletion is refused then.
1165
+ */
1166
+ onAccountDeleted?(userId: number): void | Promise<void>;
994
1167
  }
995
1168
 
996
1169
  /**
@@ -1008,6 +1181,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
1008
1181
  deveyeFor(workspaceId: number): Pick<DevEyeFacade, 'notify'>;
1009
1182
  /** Devices of one workspace, sessionless (capability `'devices.read'`). */
1010
1183
  devicesFor(workspaceId: number): Pick<DevEyeFacade['devices'], 'list' | 'isOnline'>;
1184
+ /** Members of one workspace, owner included, sessionless (capability `'members.read'`): a name a public page shows. */
1185
+ membersFor(workspaceId: number): DevEyeFacade['members'];
1011
1186
  /** The whole fleet by id, sessionless (capability `'devices.read'`). */
1012
1187
  devices: SdkFleetDevices;
1013
1188
  /** Capability `'accounts.read'`. */
@@ -1018,6 +1193,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
1018
1193
  * owner of that workspace.
1019
1194
  */
1020
1195
  quotaFor(workspaceId: number): SdkQuota;
1196
+ /** Your paused `stock` items, whatever the workspace. */
1197
+ pauses: SdkPlanPauses;
1021
1198
  /** The devices' telemetry, sessionless (capability `'telemetry.read'`). */
1022
1199
  telemetry: SdkTelemetry;
1023
1200
  /** Live invalidation of your feature's resources, from a service. */
@@ -1035,12 +1212,35 @@ export interface FeatureServiceDeps<Repo = unknown> {
1035
1212
  }): void;
1036
1213
  /** The agent-fleet transport (capability `'agents'`). */
1037
1214
  agents: AgentsFacade;
1215
+ /**
1216
+ * What a member may do NOW, without a session: for work that runs on a
1217
+ * member's behalf long after they set it up (a nightly backup of their
1218
+ * machine), and must stop when they lose the right. The rules of a
1219
+ * command: account not suspended, membership, role, the item's
1220
+ * override. `feature` answers for YOUR feature only. `device` answers
1221
+ * for the Devices permissions on one device (capability
1222
+ * `'devices.read'`), with the rule of `devices.authorize`: an override
1223
+ * that lowers the device to read-only closes it.
1224
+ */
1225
+ access: {
1226
+ feature(
1227
+ workspaceId: number,
1228
+ userId: number,
1229
+ need: { level?: FeatureAccess; extras?: readonly string[]; itemId?: string }
1230
+ ): Promise<SdkAccessVerdict>;
1231
+ device(
1232
+ workspaceId: number,
1233
+ userId: number,
1234
+ deviceId: string,
1235
+ extras: readonly string[]
1236
+ ): Promise<SdkAccessVerdict>;
1237
+ };
1038
1238
  /** Raw key wrapping under the server key, and derived keys. */
1039
1239
  keys: SdkServerKeys;
1040
1240
  /** Redeems a ticket minted by `ctx.secrecy.ticket` of THIS module; `null` when invalid, expired or another module's. */
1041
1241
  secrecy: { redeem(ticket: string): Promise<SdkRedeemedTicket | null> };
1042
1242
  /** Where DevEye lives (the same `origins` a request context gets): for a page or a link a route hands to the browser. */
1043
- origins: { app: string; public: string };
1243
+ origins: SdkOrigins;
1044
1244
  /** Your feature's domains, whatever the workspace (manifest `domains`). */
1045
1245
  domains: SdkFleetDomains;
1046
1246
  /** The named contracts the host holds, see `SdkProviders`. */
@@ -1078,6 +1278,14 @@ export interface FeatureServer<Repo = unknown> {
1078
1278
  items?: FeatureItemsEntry<Repo>;
1079
1279
  /** Required when the manifest declares `domains`, refused otherwise. */
1080
1280
  domains?: FeatureDomainsEntry<Repo>;
1281
+ /** One entry per `stock` quota of the manifest, by its key, and none other. */
1282
+ quotas?: Readonly<Record<string, FeatureStockEntry<Repo>>>;
1283
+ /**
1284
+ * The environment variables you read, as the spec you read them with
1285
+ * (`defineModuleEnv`). Plain data: the host reads it again at boot and
1286
+ * warns about every variable left to its default.
1287
+ */
1288
+ env?: ModuleEnvSpec;
1081
1289
  }
1082
1290
 
1083
1291
  /**
@@ -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
+ });