@deveye/types 0.20.2 → 0.21.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
@@ -1,3 +1,4 @@
1
+ import type { FeatureAccountExport } from './accountExport';
1
2
  import type { ItemTree, ItemTreeRows } from './copy';
2
3
  import type { z, ZodType } from 'zod';
3
4
  import type { ErrorCode } from '../protocol/error';
@@ -11,6 +12,7 @@ import type { AgentManifest } from '../http/device';
11
12
  import type { MetricSnapshot } from '../domain/metrics';
12
13
  import type { UserColor } from '../domain/user';
13
14
  import type { SdkDnsRecord } from './domains';
15
+ import type { MailTransportMessage } from './providers';
14
16
  import type { ModuleEnvSpec } from './env';
15
17
  import type {
16
18
  AgentSyncAckPayload,
@@ -26,6 +28,7 @@ import type {
26
28
  AgentSyncMovePayload,
27
29
  AgentSyncOpResultPayload,
28
30
  AgentSyncPushPayload,
31
+ AgentSyncPushAckPayload,
29
32
  AgentSyncScanPayload,
30
33
  AgentFilesMutatePayload,
31
34
  AgentFilesUploadPayload,
@@ -34,7 +37,15 @@ import type {
34
37
  CloudSyncStatePush
35
38
  } from '../protocol/agent';
36
39
 
37
- export { isPublicIp, isSafePublicUrl } from './net';
40
+ export {
41
+ isPublicIp,
42
+ isSafePublicUrl,
43
+ NetRefused,
44
+ resolvesPublicly,
45
+ safeFetchText,
46
+ type SafeFetchOptions
47
+ } from './net';
48
+ export { mapLimit } from './pool';
38
49
  export {
39
50
  defineModuleEnv,
40
51
  MODULE_ENV_NAME_PATTERN,
@@ -302,6 +313,21 @@ export interface DevEyeFacade {
302
313
  /** The CALLER's own account, never someone else's. */
303
314
  me(): Promise<SdkAccount>;
304
315
  };
316
+ /** Requires capability `'accounts.usage'`. */
317
+ usage: {
318
+ /**
319
+ * What this account uses of every limit this DevEye knows. The caller
320
+ * must be this account or a global administrator (`forbidden`
321
+ * otherwise); an unknown account throws `not_found`.
322
+ */
323
+ of(userId: number): Promise<SdkAccountUsage>;
324
+ /**
325
+ * `of` for many accounts, in the order given, unknown ids left out. A
326
+ * global administrator's surface only. The host paces the counting so a
327
+ * sweep never starves the database: one call, never one per account.
328
+ */
329
+ ofMany(userIds: readonly number[]): Promise<readonly SdkAccountUsage[]>;
330
+ };
305
331
  }
306
332
 
307
333
  /** An account of this DevEye, as `'accounts.read'` shows it. */
@@ -311,6 +337,14 @@ export interface SdkAccount {
311
337
  username: string;
312
338
  /** A global administrator of this DevEye. */
313
339
  isAdmin: boolean;
340
+ /**
341
+ * A throwaway account the app's end-to-end runner created and will delete:
342
+ * never a person, and its address receives nothing. Check this, never the
343
+ * address: it is set once, at creation, and nothing can grant it later.
344
+ */
345
+ e2e: boolean;
346
+ /** Suspended by an administrator: it keeps everything and cannot sign in. */
347
+ suspended: boolean;
314
348
  /** Milliseconds since the epoch. */
315
349
  created: number;
316
350
  }
@@ -327,6 +361,79 @@ export interface SdkAccounts {
327
361
  * and is capped at 50.
328
362
  */
329
363
  search(query: string, limit?: number): Promise<readonly SdkAccount[]>;
364
+ /** Every account, oldest first: an administrator's sweep. What you show of it is yours to gate. */
365
+ all(): Promise<readonly SdkAccount[]>;
366
+ }
367
+
368
+ /** What one account uses of one limit, whatever its plan allows. */
369
+ export interface SdkAccountQuotaUse {
370
+ /**
371
+ * `stock`: things that exist, the excess paused; `flow`: checked at each
372
+ * use, nothing paused; `perOperation`: one operation bounded, nothing counted.
373
+ */
374
+ kind: 'stock' | 'flow' | 'perOperation';
375
+ /**
376
+ * What the limit is compared to now, over every workspace the account
377
+ * OWNS: the things that exist, paused ones included, for a `stock`; this
378
+ * month's flow or the bytes held otherwise; for `workspace.members`, its
379
+ * fullest shared workspace. `null` for a `perOperation` limit.
380
+ */
381
+ used: number | null;
382
+ /** How many of them its plan holds paused, in the unit of `used`. 0 for anything but a stock. */
383
+ paused: number;
384
+ }
385
+
386
+ /** What one account uses, as `'accounts.usage'` reads it. */
387
+ export interface SdkAccountUsage {
388
+ userId: number;
389
+ /**
390
+ * By `<featureId>.<quotaKey>`: every quota of the installed modules and the
391
+ * host's own (`workspace.shared`, `workspace.members`, `domains.hosts`),
392
+ * bounded or not. The limits are the plan provider's (`planFor`).
393
+ */
394
+ quotas: Readonly<Record<string, SdkAccountQuotaUse>>;
395
+ }
396
+
397
+ /**
398
+ * Any account's usage, sessionless (capability `'accounts.usage'`), for
399
+ * services: the same reading as `ctx.deveye.usage`, without its caller check.
400
+ */
401
+ export interface SdkUsage {
402
+ of(userId: number): Promise<SdkAccountUsage>;
403
+ ofMany(userIds: readonly number[]): Promise<readonly SdkAccountUsage[]>;
404
+ }
405
+
406
+ /** One email to an account. Plain text everywhere: the host lays it out and escapes it. */
407
+ export interface SdkAccountMailMessage {
408
+ subject: string;
409
+ /** One paragraph each, in order. */
410
+ paragraphs: readonly string[];
411
+ /** Framed and set apart after the paragraphs: what the reader must not miss (a deadline). */
412
+ notice?: string;
413
+ /** A link drawn as a button, after the notice. */
414
+ button?: { label: string; url: string };
415
+ /** Small print, last. */
416
+ footnote?: string;
417
+ }
418
+
419
+ /** Emails to the accounts of this DevEye, from the server's own sender (capability `'accounts.mail'`). */
420
+ export interface SdkAccountMail {
421
+ /** `false` when this server has no mail transport: `send` would throw `conflict`. */
422
+ readonly configured: boolean;
423
+ /**
424
+ * Sends to the account's own address, never another, and resolves that
425
+ * address for your records. Throws `not_found` for an unknown account and
426
+ * `conflict` without a transport; a refusal of the mail server rejects as
427
+ * is. Nothing is retried for you.
428
+ */
429
+ send(userId: number, message: SdkAccountMailMessage): Promise<string>;
430
+ /**
431
+ * One copy to each active administrator of this DevEye, for what only the
432
+ * operator can act on (a report of illicit content). Resolves the addresses
433
+ * reached, empty when there is no active administrator. Every address is
434
+ * tried; the first refusal then rejects. Throws `conflict` without a transport.
435
+ */
436
+ sendToAdmins(message: SdkAccountMailMessage): Promise<readonly string[]>;
330
437
  }
331
438
 
332
439
  /**
@@ -348,6 +455,13 @@ export interface SdkPlanPauses {
348
455
  paused(key: string): readonly string[];
349
456
  }
350
457
 
458
+ /** Where the owner stands against one limit of YOUR `manifest.quotas`. */
459
+ export interface SdkQuotaUse {
460
+ /** By YOUR `server.quotas[key]`, over every workspace the owner owns. */
461
+ used: number;
462
+ limit: number;
463
+ }
464
+
351
465
  /**
352
466
  * What the account's plan allows of YOUR `manifest.quotas`. The account is the
353
467
  * OWNER of the workspace of the call: in a shared workspace, what a member
@@ -355,24 +469,41 @@ export interface SdkPlanPauses {
355
469
  * everything is unlimited.
356
470
  */
357
471
  export interface SdkQuota extends SdkPlanPauses {
358
- /** `null` = unlimited. An undeclared key throws `validation`. */
472
+ /**
473
+ * `null` = unlimited. An undeclared key throws `validation`. Reads 0 while
474
+ * the host serves priority accounts first and the owner is not one.
475
+ */
359
476
  limit(key: string): Promise<number | null>;
360
477
  /**
361
478
  * Call it BEFORE creating. `countAfter` receives the ids of every workspace
362
479
  * the owner account owns and returns how many there would be once created;
363
480
  * it is never called when unlimited. Throws `quota_exceeded` beyond the
364
- * limit.
481
+ * limit. Count with the same repo function as `server.quotas[key]`: the
482
+ * usage shown and the refusal must agree.
365
483
  */
366
484
  assert(
367
485
  key: string,
368
486
  countAfter: (ownerWorkspaceIds: readonly number[]) => Promise<number>
369
487
  ): Promise<void>;
488
+ /**
489
+ * Where the owner stands, counted by YOUR `server.quotas[key]`: what a
490
+ * screen says BEFORE the refusal. `null` = unlimited, and nothing is
491
+ * counted. A `perOperation` key throws `validation`: nothing accumulates.
492
+ */
493
+ usage(key: string): Promise<SdkQuotaUse | null>;
370
494
  /**
371
495
  * Call it before running a `stock` item on demand (check now, deploy now,
372
496
  * open a session): throws `quota_exceeded` when its owner's plan holds it
373
497
  * paused, which opens the plan prompt on the client.
374
498
  */
375
499
  assertActive(key: string, itemId: string): Promise<void>;
500
+ /**
501
+ * Whether the owner pays: a paid or trial plan, a plan granted on the paid
502
+ * tier, an administrator, or no plan provider at all (a self-hosted
503
+ * instance). What a default that costs the host keys on (a probe cadence),
504
+ * never a refusal: refusals go through `limit` and `assert`.
505
+ */
506
+ paid(): Promise<boolean>;
376
507
  }
377
508
 
378
509
  /** One item a `stock` quota counts. */
@@ -393,14 +524,24 @@ export interface SdkPlanPauseChange {
393
524
  resumed: readonly SdkStockItem[];
394
525
  }
395
526
 
396
- /** Your half of one `stock` quota: the host ranks, you list. */
397
- export interface FeatureStockEntry<Repo = unknown> {
527
+ /**
528
+ * How the host counts one of your quotas, for `ctx.quota.usage` and an
529
+ * account's usage (`'accounts.usage'`): a `stock` by its list, any other by
530
+ * its count, under the very WHERE of the counter you pass to `assert`.
531
+ */
532
+ export interface FeatureQuotaEntry<Repo = unknown> {
398
533
  /**
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
534
+ * `stock` quotas only, required there: the items the quota counts in these
535
+ * workspaces, OLDEST FIRST (creation, then id). How many is the usage; the
401
536
  * host keeps the first `limit` running and pauses the rest.
402
537
  */
403
- list(repo: Repo, ownerWorkspaceIds: readonly number[]): Promise<readonly SdkStockItem[]>;
538
+ list?(repo: Repo, ownerWorkspaceIds: readonly number[]): Promise<readonly SdkStockItem[]>;
539
+ /**
540
+ * Any other quota but `perOperation`, required there: what the limit is
541
+ * compared to now (this month's events, the bytes held). A month is the
542
+ * current UTC month unless your feature keeps a calendar of its own.
543
+ */
544
+ count?(repo: Repo, ownerWorkspaceIds: readonly number[]): Promise<number>;
404
545
  }
405
546
 
406
547
  /** A workspace as the fleet sees it: enough to attach a device to it. */
@@ -419,16 +560,13 @@ export interface SdkWorkspaceSummary {
419
560
  export interface AgentsFacade {
420
561
  isOnline(deviceId: string): boolean;
421
562
  /**
422
- * The three orders a device's lifecycle gives the hub. `requestDestroy`
563
+ * The two orders a device's lifecycle gives the hub. `requestDestroy`
423
564
  * asks the agent to uninstall itself (deletion path); `disconnectAgent`
424
- * closes its socket now (a revoked or force-deleted device);
425
- * `resetAgentSession` drops what the hub remembered of it (a device
426
- * confirmed or reactivated starts clean). All three answer `false` when
427
- * the agent is not connected, which is not an error.
565
+ * closes its socket now (a revoked or force-deleted device). Both answer
566
+ * `false` when the agent is not connected, which is not an error.
428
567
  */
429
568
  requestDestroy(deviceId: string): boolean;
430
569
  disconnectAgent(deviceId: string): boolean;
431
- resetAgentSession(deviceId: string): boolean;
432
570
  /**
433
571
  * The manifest of the agent binaries the app serves (the build version and,
434
572
  * per target, whether the binary is signed), or null while nothing is
@@ -450,9 +588,21 @@ export interface AgentsFacade {
450
588
  * offline (it receives the config at its next connection anyway).
451
589
  */
452
590
  pushConfig(deviceId: string): Promise<boolean>;
591
+ /**
592
+ * The cadence each device's agent runs at, by device id: its own setting,
593
+ * or the default of the plan of its HOME workspace's owner.
594
+ */
595
+ metricIntervals(
596
+ devices: readonly {
597
+ id: string;
598
+ workspace_id: number | null;
599
+ metric_interval_seconds: number | null;
600
+ }[]
601
+ ): Promise<ReadonlyMap<string, number>>;
453
602
  requestSyncConfig(deviceId: string, payload: AgentSyncConfigPayload): boolean;
454
603
  requestSyncScan(deviceId: string, payload: AgentSyncScanPayload): boolean;
455
604
  requestSyncPush(deviceId: string, payload: AgentSyncPushPayload): boolean;
605
+ requestSyncPushAck(deviceId: string, payload: AgentSyncPushAckPayload): boolean;
456
606
  requestSyncApplyChunk(deviceId: string, payload: AgentSyncApplyChunkPayload): boolean;
457
607
  requestSyncApplyStart(deviceId: string, payload: AgentSyncApplyStartPayload): boolean;
458
608
  requestSyncApplyDir(deviceId: string, payload: AgentSyncApplyDirPayload): boolean;
@@ -597,6 +747,58 @@ export interface SdkProviders {
597
747
  get<T>(key: string): T | undefined;
598
748
  }
599
749
 
750
+ /** One object of an {@link SdkObjectStore}, as `list` yields it. */
751
+ export interface SdkStoredObject {
752
+ key: string;
753
+ size: number;
754
+ }
755
+
756
+ /**
757
+ * Where a module keeps files (capability `'objects'`): the server's disk, or
758
+ * the S3 bucket the host configured. A key is a relative path (`a/b/c`, no
759
+ * `..`, no leading `/`); store only the KEY in your tables, never where it
760
+ * resolves, so the host can move the whole tree (another disk, another
761
+ * bucket) without a row to rewrite. Writes are atomic: a reader sees the
762
+ * whole object or none.
763
+ */
764
+ export interface SdkObjectStore {
765
+ /** `'local'`: the server's disk. `'s3'`: every byte read costs egress. */
766
+ readonly kind: 'local' | 's3';
767
+ /** Where it lives, for a screen: « disque du serveur », « S3 : bucket ». */
768
+ describe(): string;
769
+ put(key: string, body: AsyncIterable<Uint8Array> | Uint8Array): Promise<{ size: number }>;
770
+ /**
771
+ * Stores a finished local file under `key`, then removes the local file:
772
+ * a rename on the server's disk, an upload on S3. For a file assembled
773
+ * in {@link spoolDir}.
774
+ */
775
+ putFile(key: string, localPath: string): Promise<{ size: number }>;
776
+ /** The object's bytes, streamed. `range` is inclusive, like HTTP's. Throws when absent. */
777
+ get(key: string, range?: { start: number; end?: number }): AsyncIterable<Buffer>;
778
+ /** `null` when absent. */
779
+ head(key: string): Promise<{ size: number } | null>;
780
+ /** Every object whose key starts with `prefix`, in no guaranteed order. */
781
+ list(prefix: string): AsyncIterable<SdkStoredObject>;
782
+ /** Idempotent: an absent key is not an error. */
783
+ delete(key: string): Promise<void>;
784
+ /** Every object under `prefix`, which must end with `/`. */
785
+ deletePrefix(prefix: string): Promise<void>;
786
+ /**
787
+ * A directory on the server's disk, whatever `kind`, for what cannot be
788
+ * written as a whole object at once (a partial upload resumed later).
789
+ * Yours alone; the store never cleans it.
790
+ */
791
+ spoolDir(): string;
792
+ /**
793
+ * The store's root when files written there would not last: on the
794
+ * server's disk, inside a container, a directory on no mounted volume,
795
+ * so its writable layer, wiped at the next redeploy. `null` otherwise,
796
+ * and always on S3. Refuse to write there, naming the variable that sets
797
+ * `localDir`: the files would vanish without a word.
798
+ */
799
+ ephemeralRoot(): Promise<string | null>;
800
+ }
801
+
600
802
  /**
601
803
  * Raw bytes under the SERVER key, for wrapping module-owned key material; never
602
804
  * for user data, which goes through ciphers and the store. The host seals under
@@ -627,7 +829,7 @@ export interface SdkDevice {
627
829
  id: string;
628
830
  name: string;
629
831
  online: boolean;
630
- /** `active` is the only status whose telemetry the app records. */
832
+ /** `active` is the only status whose agent the socket admits. */
631
833
  status: string;
632
834
  /** The account that enrolled the device (the actor of its audit lines). */
633
835
  ownerUserId: number;
@@ -635,6 +837,8 @@ export interface SdkDevice {
635
837
  workspaceId: number | null;
636
838
  /** The agent's metric cadence in seconds, null when it follows the default. */
637
839
  metricIntervalSeconds: number | null;
840
+ /** The cadence the agent actually runs at: its own, or the default of its owner's plan. */
841
+ effectiveMetricIntervalSeconds: number;
638
842
  /** The last OS/security report, null before the first one (or unreadable). */
639
843
  report: DeviceReport | null;
640
844
  }
@@ -1162,8 +1366,33 @@ export interface FeatureService {
1162
1366
  * rows go with the account (`ON DELETE CASCADE`), nothing to do for them.
1163
1367
  * Runs before the row is deleted: a throw aborts the deletion. Never called
1164
1368
  * while your service is halted by maintenance: the deletion is refused then.
1369
+ * Return a note when the holder must learn something of yours (their
1370
+ * subscription stopped): it joins the confirmation email they receive.
1165
1371
  */
1166
- onAccountDeleted?(userId: number): void | Promise<void>;
1372
+ onAccountDeleted?(
1373
+ userId: number
1374
+ ): void | SdkAccountDeletedNote | Promise<void | SdkAccountDeletedNote>;
1375
+ /**
1376
+ * What your service knows of its own health that the host cannot see: a
1377
+ * port it failed to open, an engine it depends on. Read by the public
1378
+ * status page about once a minute. Answer from memory: no network call, no
1379
+ * write, no heavy query; after 2 s the host counts you as degraded. Omit it
1380
+ * when the process and the database are all you rely on: the host already
1381
+ * watches those, along with your failing tickers and commands.
1382
+ */
1383
+ health?(): SdkServiceHealth | Promise<SdkServiceHealth>;
1384
+ }
1385
+
1386
+ /** A service's own verdict on itself, as `FeatureService.health` gives it. */
1387
+ export interface SdkServiceHealth {
1388
+ state: 'up' | 'degraded' | 'down';
1389
+ /** Shown on the public status page: a short sentence for users, never an internal detail. */
1390
+ reason?: string;
1391
+ }
1392
+
1393
+ /** One paragraph of yours in the email confirming an account's deletion to its holder. */
1394
+ export interface SdkAccountDeletedNote {
1395
+ paragraph: string;
1167
1396
  }
1168
1397
 
1169
1398
  /**
@@ -1187,6 +1416,10 @@ export interface FeatureServiceDeps<Repo = unknown> {
1187
1416
  devices: SdkFleetDevices;
1188
1417
  /** Capability `'accounts.read'`. */
1189
1418
  accounts: SdkAccounts;
1419
+ /** Capability `'accounts.usage'`. */
1420
+ usage: SdkUsage;
1421
+ /** Capability `'accounts.mail'`. */
1422
+ accountMail: SdkAccountMail;
1190
1423
  /**
1191
1424
  * {@link SdkQuota} for a workspace, sessionless: for what gets created
1192
1425
  * outside any command (bytes an agent uploads). Same account rule, the
@@ -1237,6 +1470,12 @@ export interface FeatureServiceDeps<Repo = unknown> {
1237
1470
  };
1238
1471
  /** Raw key wrapping under the server key, and derived keys. */
1239
1472
  keys: SdkServerKeys;
1473
+ /**
1474
+ * The object store (capability `'objects'`). `localDir` is where your
1475
+ * objects live while the host keeps them on its disk, typically a path of
1476
+ * your `env`; with an S3 configured, it only holds your `spoolDir()`.
1477
+ */
1478
+ objects(localDir: string): SdkObjectStore;
1240
1479
  /** Redeems a ticket minted by `ctx.secrecy.ticket` of THIS module; `null` when invalid, expired or another module's. */
1241
1480
  secrecy: { redeem(ticket: string): Promise<SdkRedeemedTicket | null> };
1242
1481
  /** Where DevEye lives (the same `origins` a request context gets): for a page or a link a route hands to the browser. */
@@ -1278,14 +1517,131 @@ export interface FeatureServer<Repo = unknown> {
1278
1517
  items?: FeatureItemsEntry<Repo>;
1279
1518
  /** Required when the manifest declares `domains`, refused otherwise. */
1280
1519
  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>>>;
1520
+ /**
1521
+ * What the holder's data export writes of your feature (GDPR
1522
+ * portability): see {@link FeatureAccountExport}. Required once your
1523
+ * feature owns a table; without tables, the host exports your store alone.
1524
+ */
1525
+ accountExport?: FeatureAccountExport<Repo>;
1526
+ /** One entry per quota of the manifest, by its key, `perOperation` ones excepted, and none other. */
1527
+ quotas?: Readonly<Record<string, FeatureQuotaEntry<Repo>>>;
1283
1528
  /**
1284
1529
  * The environment variables you read, as the spec you read them with
1285
1530
  * (`defineModuleEnv`). Plain data: the host reads it again at boot and
1286
1531
  * warns about every variable left to its default.
1287
1532
  */
1288
1533
  env?: ModuleEnvSpec;
1534
+ /**
1535
+ * Every email you send, on made-up data, for the administrator's mail
1536
+ * tester: built by the SAME function as the real one, or the tester proves
1537
+ * nothing. `sender: 'server'` requires capability `'accounts.mail'`. Keys
1538
+ * are unique within your feature.
1539
+ */
1540
+ mailSamples?: readonly SdkMailSample[];
1541
+ /** Your end-to-end scenarios, run by an administrator against this very server. */
1542
+ e2e?: FeatureE2eEntry<Repo>;
1543
+ }
1544
+
1545
+ /** What a mail sample is built with. */
1546
+ export interface SdkMailSampleContext {
1547
+ origins: SdkOrigins;
1548
+ /** Milliseconds since the epoch. */
1549
+ now: number;
1550
+ }
1551
+
1552
+ /** A message a workspace mailbox sends: what `MailTransportProvider.send` takes, the recipient aside. */
1553
+ export type SdkWorkspaceMail = Omit<MailTransportMessage, 'to'>;
1554
+
1555
+ export type SdkMailSample = {
1556
+ /** `[a-z][a-zA-Z0-9]*`, unique within your feature. */
1557
+ key: string;
1558
+ /** What the tester lists, in the interface's language. */
1559
+ label: string;
1560
+ } & (
1561
+ | {
1562
+ /** From the server's own sender, as `accountMail.send` would. */
1563
+ sender: 'server';
1564
+ build(ctx: SdkMailSampleContext): SdkAccountMailMessage | Promise<SdkAccountMailMessage>;
1565
+ }
1566
+ | {
1567
+ /** From a workspace mailbox the administrator picks, as `MAIL_TRANSPORT_PROVIDER` would. */
1568
+ sender: 'workspace';
1569
+ build(ctx: SdkMailSampleContext): SdkWorkspaceMail | Promise<SdkWorkspaceMail>;
1570
+ }
1571
+ );
1572
+
1573
+ /** The throwaway account a scenario runs as. It owns `workspaceId` and is deleted with all it owns afterwards. */
1574
+ export interface SdkE2eAccount {
1575
+ userId: number;
1576
+ username: string;
1577
+ email: string;
1578
+ password: string;
1579
+ /** Its personal workspace. */
1580
+ workspaceId: number;
1581
+ }
1582
+
1583
+ export interface SdkE2eContext<Repo = unknown> {
1584
+ account: SdkE2eAccount;
1585
+ /**
1586
+ * A command through a real socket of that account and the whole
1587
+ * dispatcher. Rejects with a `FeatureError` carrying the server's code.
1588
+ */
1589
+ send<T = unknown>(command: string, input: unknown, opts?: { workspaceId?: number }): Promise<T>;
1590
+ /** A sessionless request to this server's own listener: what a visitor's browser sends to a public route. */
1591
+ fetch(
1592
+ path: string,
1593
+ init?: { method?: 'GET' | 'POST'; headers?: Record<string, string>; body?: string }
1594
+ ): Promise<{ status: number; body: string }>;
1595
+ /**
1596
+ * Polls until `probe` answers something other than `null`, `undefined` or
1597
+ * `false`, then resolves with it. Rejects after `timeoutMs` (default 10 s),
1598
+ * saying `what` was awaited.
1599
+ */
1600
+ waitFor<T>(
1601
+ probe: () => Promise<T | null | undefined | false>,
1602
+ opts?: { timeoutMs?: number; intervalMs?: number; what?: string }
1603
+ ): Promise<T>;
1604
+ /**
1605
+ * Undoes something once the steps are over, whatever happened, last
1606
+ * registered first, while the account still exists. Register the undo
1607
+ * right after the thing is created, before anything can fail.
1608
+ */
1609
+ defer(label: string, undo: () => Promise<void>): void;
1610
+ /** Shared between the steps of one run. */
1611
+ state: Map<string, unknown>;
1612
+ repo: Repo;
1613
+ origins: SdkOrigins;
1614
+ /** Aborted when the administrator stops the run or a timeout fires. */
1615
+ signal: AbortSignal;
1616
+ }
1617
+
1618
+ export interface SdkE2eStep<Repo = unknown> {
1619
+ /** What the report shows, in the interface's language. */
1620
+ label: string;
1621
+ /** Longer than the default 20 s: a step that waits on a third party (a payment provider's webhook). */
1622
+ timeoutMs?: number;
1623
+ /** Throws to fail. A returned string is shown as the step's detail. */
1624
+ run(ctx: SdkE2eContext<Repo>): Promise<string | void>;
1625
+ }
1626
+
1627
+ export interface SdkE2eScenario<Repo = unknown> {
1628
+ /** `[a-z][a-zA-Z0-9]*`, unique within your feature. */
1629
+ id: string;
1630
+ label: string;
1631
+ /** Why it cannot run here right now, or `null`. Asked before every run. */
1632
+ skip?(ctx: { origins: SdkOrigins }): string | null | Promise<string | null>;
1633
+ steps: readonly SdkE2eStep<Repo>[];
1634
+ }
1635
+
1636
+ export interface FeatureE2eEntry<Repo = unknown> {
1637
+ scenarios: readonly SdkE2eScenario<Repo>[];
1638
+ /**
1639
+ * Removes what a crashed run left OUTSIDE the test accounts (an object at
1640
+ * a payment provider): what lives in your tables goes with the account.
1641
+ * Called at boot, before and after every run. Idempotent; a throw keeps
1642
+ * the run marked as leaving residue.
1643
+ */
1644
+ sweep?(): Promise<void>;
1289
1645
  }
1290
1646
 
1291
1647
  /**
@@ -1613,7 +1969,18 @@ export type {
1613
1969
  ItemTreeTable
1614
1970
  } from './copy';
1615
1971
 
1616
- // Le conteneur chiffré que CloudSync et Backup partagent (voir `devb.ts`).
1972
+ export { accountExportProblem, EXPORT_SECRET_COLUMN, exportTableRows } from './accountExport';
1973
+ export type {
1974
+ FeatureAccountExport,
1975
+ SdkAccountExportContext,
1976
+ SdkExportFiles,
1977
+ SdkExportSkip,
1978
+ SdkExportTable,
1979
+ SdkExportWriter,
1980
+ SdkWorkspaceExportContext
1981
+ } from './accountExport';
1982
+
1983
+ // Le conteneur chiffré des modules qui stockent des fichiers (voir `devb.ts`).
1617
1984
  export {
1618
1985
  BLOB_CHUNK_BYTES,
1619
1986
  BLOB_CHUNK_SEALED,
@@ -1623,7 +1990,12 @@ export {
1623
1990
  BLOB_VERSION_STREAM,
1624
1991
  createBlobHeader,
1625
1992
  openChunk,
1993
+ openSealedRange,
1994
+ openSealedStream,
1626
1995
  openStreamDecipher,
1627
1996
  parseBlobHeader,
1628
- sealChunk
1997
+ sealChunk,
1998
+ sealedSize,
1999
+ sealStream
1629
2000
  } from './devb';
2001
+ export { contentDisposition, parseByteRange } from './download';
@@ -80,6 +80,8 @@ test('the harness searches accounts like the app: substring, exact id first, cap
80
80
  username,
81
81
  email: `${username}@example.com`,
82
82
  isAdmin: false,
83
+ e2e: false,
84
+ suspended: false,
83
85
  created: 0
84
86
  });
85
87
  const { accounts } = createTestServiceDeps({
@@ -94,6 +96,10 @@ test('the harness searches accounts like the app: substring, exact id first, cap
94
96
  assert.deepEqual(await ids('12abc'), []);
95
97
  assert.deepEqual(await ids('', 1), [12]);
96
98
  assert.equal((await ids('', 0)).length, 1, 'a limit below one is raised to one');
99
+ assert.deepEqual(
100
+ (await accounts.all()).map((a) => a.id),
101
+ [7, 12, 3]
102
+ );
97
103
  });
98
104
 
99
105
  test('the harness scopes domains to the workspace, and finds a host whatever its spelling', async () => {
@@ -144,6 +150,66 @@ test('the harness bounds a quota like the app: never counted when unlimited, ref
144
150
  assert.deepEqual(bounded.recorded.accountChanges, [7]);
145
151
  });
146
152
 
153
+ test('the harness reads usage like the app: nothing counted when unlimited, a stock by its list', async () => {
154
+ let counted = 0;
155
+ const quotas = {
156
+ monitors: {
157
+ list: (_repo: undefined, owned: readonly number[]) => {
158
+ counted++;
159
+ return Promise.resolve(owned.map((id) => ({ id: String(id), workspaceId: id })));
160
+ }
161
+ },
162
+ events: {
163
+ count: (_repo: undefined, owned: readonly number[]) => {
164
+ counted++;
165
+ return Promise.resolve(owned.length * 10);
166
+ }
167
+ }
168
+ };
169
+ assert.equal(await createTestContext({ quotas }).quota.usage('monitors'), null);
170
+ assert.equal(counted, 0);
171
+
172
+ const ctx = createTestContext({
173
+ quotas,
174
+ quotaLimits: { monitors: 0, events: 50 },
175
+ ownerWorkspaceIds: [1, 2]
176
+ });
177
+ assert.deepEqual(await ctx.quota.usage('monitors'), { used: 2, limit: 0 });
178
+ assert.deepEqual(await ctx.quota.usage('events'), { used: 20, limit: 50 });
179
+ assert.deepEqual(
180
+ await createTestServiceDeps({ quotas, quotaLimits: { events: 5 } })
181
+ .quotaFor(1)
182
+ .usage('events'),
183
+ { used: 10, limit: 5 }
184
+ );
185
+ await assert.rejects(
186
+ createTestContext({ quotaLimits: { monitors: 1 } }).quota.usage('monitors'),
187
+ /pass your server's quotas/
188
+ );
189
+ });
190
+
191
+ test('the harness reads an account usage like the app: its own, or anyone for an administrator', async () => {
192
+ const accountUsage = [
193
+ { userId: 1, quotas: { 'x.monitors': { kind: 'stock' as const, used: 2, paused: 0 } } },
194
+ { userId: 2, quotas: { 'x.monitors': { kind: 'stock' as const, used: 9, paused: 4 } } }
195
+ ];
196
+ const me = createTestContext({ userId: 1, accountUsage });
197
+ assert.equal((await me.deveye.usage.of(1)).quotas['x.monitors'].used, 2);
198
+ await assert.rejects(me.deveye.usage.of(2), { code: 'forbidden' });
199
+ await assert.rejects(me.deveye.usage.ofMany([1]), { code: 'forbidden' });
200
+
201
+ const admin = createTestContext({ userId: 1, isAdmin: true, accountUsage });
202
+ assert.deepEqual(
203
+ (await admin.deveye.usage.ofMany([2, 5, 1])).map((u) => u.userId),
204
+ [2, 1]
205
+ );
206
+ await assert.rejects(admin.deveye.usage.of(5), { code: 'not_found' });
207
+ assert.equal(
208
+ (await createTestServiceDeps({ accountUsage }).usage.of(2)).quotas['x.monitors'].paused,
209
+ 4
210
+ );
211
+ });
212
+
147
213
  test('the harnesses hold the plan pauses and refuse a paused item on demand', async () => {
148
214
  const ctx = createTestContext({ pausedItems: { monitors: ['7'] } });
149
215
  assert.equal(ctx.quota.isPaused('monitors', '7'), true);