@deveye/types 0.24.6 → 0.25.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/net.ts CHANGED
@@ -13,41 +13,46 @@
13
13
  * fetch built on them, for a small text body (a domain's proof, a calendar).
14
14
  */
15
15
  import { resolve4, resolve6 } from 'node:dns/promises';
16
- import { isIP } from 'node:net';
16
+ import { BlockList, isIP } from 'node:net';
17
17
 
18
18
  /**
19
- * Is this a public, routable IP address? Loopback, private ranges, link-local,
20
- * CGNAT and multicast all read as false, in both families.
19
+ * Every address that is not public, in both families: loopback, private
20
+ * ranges, link-local, CGNAT, multicast and reserved, and the IPv4-compatible
21
+ * `::/96` (which holds `::` and `::1`).
21
22
  */
22
- export function isPublicIp(raw: string): boolean {
23
- const ip = raw.replace(/^\[|\]$/g, '').toLowerCase();
24
- const v = isIP(ip);
25
- if (v === 0) return false;
26
-
27
- if (v === 4) return isPublicIpv4(ip);
28
-
29
- // IPv4-mapped or compatible: judge the real v4 part.
30
- const mapped = ip.match(/^::(?:ffff:)?(\d+\.\d+\.\d+\.\d+)$/);
31
- if (mapped) return isPublicIpv4(mapped[1]);
32
-
33
- if (ip === '::' || ip === '::1') return false;
34
- // fc00::/7 (unique-local), fe80::/10 (link-local), ff00::/8 (multicast).
35
- if (/^f[cd]/.test(ip)) return false;
36
- if (/^fe[89ab]/.test(ip)) return false;
37
- if (/^ff/.test(ip)) return false;
38
- return true;
23
+ const NON_PUBLIC = new BlockList();
24
+ for (const [net, prefix] of [
25
+ ['0.0.0.0', 8],
26
+ ['10.0.0.0', 8],
27
+ ['100.64.0.0', 10],
28
+ ['127.0.0.0', 8],
29
+ ['169.254.0.0', 16],
30
+ ['172.16.0.0', 12],
31
+ ['192.168.0.0', 16],
32
+ ['224.0.0.0', 3]
33
+ ] as const) {
34
+ NON_PUBLIC.addSubnet(net, prefix, 'ipv4');
35
+ }
36
+ for (const [net, prefix] of [
37
+ ['::', 96],
38
+ ['fc00::', 7],
39
+ ['fe80::', 10],
40
+ ['ff00::', 8]
41
+ ] as const) {
42
+ NON_PUBLIC.addSubnet(net, prefix, 'ipv6');
39
43
  }
40
44
 
41
- function isPublicIpv4(ip: string): boolean {
42
- const o = ip.split('.').map(Number);
43
- if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
44
- if (o[0] === 0 || o[0] === 10 || o[0] === 127) return false;
45
- if (o[0] === 169 && o[1] === 254) return false; // link-local
46
- if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return false;
47
- if (o[0] === 192 && o[1] === 168) return false;
48
- if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return false; // CGNAT
49
- if (o[0] >= 224) return false; // multicast and reserved
50
- return true;
45
+ /**
46
+ * Is this a public, routable IP address? Loopback, private ranges, link-local,
47
+ * CGNAT and multicast all read as false, in both families. An IPv4 address
48
+ * written in IPv6 (`::ffff:7f00:1`, the form a URL parser gives back) is judged
49
+ * on its IPv4 part: `BlockList.check` matches it against the IPv4 rules.
50
+ */
51
+ export function isPublicIp(raw: string): boolean {
52
+ const ip = raw.replace(/^\[|\]$/g, '');
53
+ const family = isIP(ip);
54
+ if (family === 0) return false;
55
+ return !NON_PUBLIC.check(ip, family === 4 ? 'ipv4' : 'ipv6');
51
56
  }
52
57
 
53
58
  /**
@@ -205,6 +205,13 @@ export interface DatabaseMeasureProvider {
205
205
  workspaceId: number,
206
206
  queries: readonly string[]
207
207
  ): Promise<readonly DatabaseNumberOutcome[] | null>;
208
+ /**
209
+ * May this member run their own queries against the database? The same
210
+ * right as exploring it from the feature's screens, the item's override
211
+ * included: a measurement reads any table. Ask it before linking a
212
+ * database and before saving, testing or running a measurement.
213
+ */
214
+ authorize(databaseId: number, workspaceId: number, userId: number): Promise<SdkAccessVerdict>;
208
215
  }
209
216
 
210
217
  export const DATABASE_ITEMS_PROVIDER = 'database.items' as const;
package/src/sdk/server.ts CHANGED
@@ -17,6 +17,7 @@ import type { SdkDnsRecord } from './domains';
17
17
  import type { MailTransportMessage } from './providers';
18
18
  import type { ModuleEnvSpec } from './env';
19
19
  import type { ExternalService } from '../domain/externalService';
20
+ import type { AdminFeatureFact } from '../features/admin';
20
21
  import type {
21
22
  AgentSyncAckPayload,
22
23
  AgentSyncApplyChunkPayload,
@@ -374,13 +375,36 @@ export interface DevEyeFacade {
374
375
  /**
375
376
  * Throws `not_found` unless the device exists AND is visible in this
376
377
  * workspace (its own, or shared into it), a global administrator
377
- * included: membership is the boundary. With `extras`, a handler also requires the CALLER to hold these
378
- * permissions of the Devices feature on this device (`docker` to drive
379
- * its containers), and throws `forbidden` otherwise: a module cannot
380
- * name another feature's permissions in its own `access`.
378
+ * included: membership is the boundary. In a command, the CALLER must
379
+ * also see it: Devices open to their role, and the device not hidden
380
+ * from it. `level: 'write'` requires the device writable for them
381
+ * (`forbidden` on a read-only one), for a handler that changes what
382
+ * the machine does. With `extras`, a handler also requires the CALLER
383
+ * to hold these permissions of the Devices feature on this device
384
+ * (`docker` to drive its containers), and throws `forbidden`
385
+ * otherwise: a module cannot name another feature's permissions in its
386
+ * own `access`.
387
+ *
388
+ * `control: true` where the handler is about to make the machine act
389
+ * (save a source it reads, a target it deploys to, a folder it syncs):
390
+ * the caller must also have confirmed with an authenticator code
391
+ * lately, `stepup_required` otherwise, which the client turns into the
392
+ * prompt and a retry. Leave it out of a mere check of rights (a list of
393
+ * what the caller could pick).
394
+ */
395
+ authorize(
396
+ deviceId: string,
397
+ options?: { level?: FeatureAccess; extras?: readonly string[]; control?: boolean }
398
+ ): Promise<SdkDevice>;
399
+ /**
400
+ * The `control` confirmation alone, where no device exists yet (a code
401
+ * that pairs new machines).
402
+ */
403
+ assertControl(): Promise<void>;
404
+ /**
405
+ * The devices this workspace sees: its own, and those shared into it.
406
+ * In a command, without those hidden from the caller.
381
407
  */
382
- authorize(deviceId: string, options?: { extras?: readonly string[] }): Promise<SdkDevice>;
383
- /** The devices this workspace sees: its own, and those shared into it. */
384
408
  list(): Promise<readonly SdkDevice[]>;
385
409
  isOnline(deviceId: string): boolean;
386
410
  };
@@ -417,6 +441,8 @@ export interface SdkAccount {
417
441
  username: string;
418
442
  /** A global administrator of this DevEye. */
419
443
  isAdmin: boolean;
444
+ /** A moderator or a global administrator: the accounts that handle reports. */
445
+ canModerate: boolean;
420
446
  /**
421
447
  * A throwaway account the app's end-to-end runner created and will delete:
422
448
  * never a person, and its address receives nothing. Check this, never the
@@ -508,12 +534,14 @@ export interface SdkAccountMail {
508
534
  */
509
535
  send(userId: number, message: SdkAccountMailMessage): Promise<string>;
510
536
  /**
511
- * One copy to each active administrator of this DevEye, for what only the
512
- * operator can act on (a report of illicit content). Resolves the addresses
513
- * reached, empty when there is no active administrator. Every address is
514
- * tried; the first refusal then rejects. Throws `conflict` without a transport.
537
+ * One copy to each active moderator and administrator of this DevEye, for
538
+ * what awaits their decision (a report of illicit content). A moderator
539
+ * never sees where a report came from: leave the reporter's address and IP
540
+ * out of the message. Resolves the addresses reached, empty when there is
541
+ * no one. Every address is tried; the first refusal then rejects. Throws
542
+ * `conflict` without a transport.
515
543
  */
516
- sendToAdmins(message: SdkAccountMailMessage): Promise<readonly string[]>;
544
+ sendToModerators(message: SdkAccountMailMessage): Promise<readonly string[]>;
517
545
  }
518
546
 
519
547
  /**
@@ -703,7 +731,11 @@ export interface AgentsFacade {
703
731
  */
704
732
  requestFilesMutate(deviceId: string, payload: AgentFilesMutatePayload): boolean;
705
733
  requestFilesUpload(deviceId: string, payload: AgentFilesUploadPayload): boolean;
706
- awaitFilesOp(opId: string, timeoutMs: number): Promise<{ ok: boolean; error?: string }>;
734
+ awaitFilesOp(
735
+ deviceId: string,
736
+ opId: string,
737
+ timeoutMs: number
738
+ ): Promise<{ ok: boolean; error?: string }>;
707
739
  /** Forgets a pending `awaitFilesOp` (the frame was never sent, or the caller gave up). */
708
740
  cancelFilesOp(opId: string): void;
709
741
  /**
@@ -961,6 +993,15 @@ export interface SdkSecrecy {
961
993
  * sees a session id nor a key. Default life: two minutes.
962
994
  */
963
995
  ticket(payload: unknown, opts?: { ttlSeconds?: number }): Promise<string>;
996
+ /**
997
+ * The payload of a ticket THIS session minted (same caller, session,
998
+ * workspace and module), `null` for any other: expired, forged, or minted
999
+ * elsewhere. For a gesture that must end where it began: an OAuth popup
1000
+ * hands `code` and `state` back to the page that opened it, which sends
1001
+ * them through a command, so a consent link mailed to someone else never
1002
+ * lands anywhere.
1003
+ */
1004
+ redeem(ticket: string): Promise<{ payload: unknown } | null>;
964
1005
  }
965
1006
 
966
1007
  /**
@@ -978,8 +1019,9 @@ export interface SdkItems {
978
1019
  restrictions(): Promise<ReadonlyMap<string, ItemAccess>>;
979
1020
  /**
980
1021
  * Throws `forbidden` unless THIS item is open to the caller at `level`
981
- * (default `'read'`), role restriction included. Commands that target one
982
- * item call it first.
1022
+ * (default `'read'`), its override included. A command that names its
1023
+ * item in `access.item` is already checked; call it for an item reached
1024
+ * another way (the item a row belongs to).
983
1025
  */
984
1026
  assert(itemId: string, level?: FeatureAccess): Promise<void>;
985
1027
  /**
@@ -1066,6 +1108,8 @@ export interface SdkLive {
1066
1108
  publish(workspaceId: number, event: string, payload: unknown): void;
1067
1109
  /** {@link SdkContextLive.accountChanged}, from a service (a webhook, a ticker). */
1068
1110
  accountChanged(userId: number): void;
1111
+ /** {@link SdkContextLive.pendingChanged}, from a service or a public route (a report just filed). */
1112
+ pendingChanged(): void;
1069
1113
  }
1070
1114
 
1071
1115
  /**
@@ -1083,6 +1127,12 @@ export interface SdkContextLive {
1083
1127
  * (pauses and resumes). No payload, so no capability.
1084
1128
  */
1085
1129
  accountChanged(userId: number): void;
1130
+ /**
1131
+ * What `server.adminPending` counts may have moved (a report decided): the
1132
+ * host counts again and relights the badges of every moderator and
1133
+ * administrator connected. Coalesced by the host, cheap to call.
1134
+ */
1135
+ pendingChanged(): void;
1086
1136
  }
1087
1137
 
1088
1138
  /** The whole fleet, sessionless (capability `'devices.read'`), for services. */
@@ -1249,6 +1299,18 @@ export interface SdkFeatureContext<Repo = unknown> {
1249
1299
  origins: SdkOrigins;
1250
1300
  }
1251
1301
 
1302
+ /**
1303
+ * Finds the item a command reaches through another row; `undefined` or `null`
1304
+ * when that row does not exist. Method-shaped so a definition typed with your
1305
+ * repo stays assignable to the host's list of commands.
1306
+ */
1307
+ export type SdkItemFinder<Repo, I extends ZodType> = {
1308
+ find(
1309
+ ctx: SdkFeatureContext<Repo>,
1310
+ input: z.output<I>
1311
+ ): Promise<string | number | null | undefined>;
1312
+ }['find'];
1313
+
1252
1314
  /**
1253
1315
  * One command your module handles. The dispatcher validates `input` before the
1254
1316
  * handler and `output` after it, enforces `access` first, and broadcasts your
@@ -1268,16 +1330,28 @@ export interface SdkFeatureDefinition<
1268
1330
  * `level`: the caller's level on your feature (`read` by default).
1269
1331
  * `extras`: the extra permissions the caller must hold, ALL required.
1270
1332
  * `admin`: the caller must be a global administrator; the feature check
1271
- * still applies. Your feature id is implied: you cannot gate on another
1272
- * feature's rights.
1333
+ * still applies. `moderation`: a moderator or a global administrator, for
1334
+ * the commands of a `moderation` admin tab. Your feature id is implied:
1335
+ * you cannot gate on another feature's rights.
1273
1336
  * `scope: 'account'`: the command acts on the caller's ACCOUNT, not on a
1274
1337
  * workspace. The host runs it in the caller's personal workspace whatever
1275
1338
  * the client sent, so the role held in a shared workspace never decides.
1339
+ * `item`: the item the command targets, as the input field holding its
1340
+ * id, or as a function that finds it when the command reaches it through
1341
+ * another row (the site a form belongs to). The host checks `level` and
1342
+ * `extras` on THAT item, whose override replaces the role in both
1343
+ * directions, before your handler runs. The function runs first, with the
1344
+ * same context; it returns `undefined` when the row does not exist. Without
1345
+ * an item (or when the optional field is absent from a request), the role
1346
+ * on your feature decides alone: an override never opens a command that
1347
+ * does not name its item.
1276
1348
  */
1277
1349
  access?: {
1278
1350
  level?: FeatureAccess;
1279
1351
  extras?: readonly string[];
1352
+ item?: Extract<keyof z.input<I>, string> | SdkItemFinder<Repo, I>;
1280
1353
  admin?: boolean;
1354
+ moderation?: boolean;
1281
1355
  scope?: 'account';
1282
1356
  };
1283
1357
  /**
@@ -1714,8 +1788,31 @@ export interface FeatureServer<Repo = unknown> {
1714
1788
  mailSamples?: readonly SdkMailSample[];
1715
1789
  /** Your end-to-end scenarios, run by an administrator against this very server. */
1716
1790
  e2e?: FeatureE2eEntry<Repo>;
1791
+ /**
1792
+ * What awaits a human decision, by id of `manifest.adminTabs` (open
1793
+ * reports, a queue running late): the badges of the account menu and of
1794
+ * the administration popup. A tab absent or at 0 lights nothing. Cheap
1795
+ * counts only: the host asks again on every `live.pendingChanged()`.
1796
+ */
1797
+ adminPending?(ctx: SdkAdminContext<Repo>): Promise<Readonly<Record<string, number>>>;
1798
+ /**
1799
+ * Your own figures for the overview of the administration popup, across
1800
+ * every account (links created, files stored): what the host cannot count
1801
+ * from your tables and quotas alone.
1802
+ */
1803
+ adminFacts?(ctx: SdkAdminContext<Repo>): Promise<readonly SdkAdminFact[]>;
1717
1804
  }
1718
1805
 
1806
+ /** What `FeatureServer.adminPending` and `adminFacts` are called with: no session, every account at once. */
1807
+ export interface SdkAdminContext<Repo = unknown> {
1808
+ repo: Repo;
1809
+ /** Your paused `stock` items, whatever the workspace. */
1810
+ pauses: SdkPlanPauses;
1811
+ }
1812
+
1813
+ /** One figure of `FeatureServer.adminFacts`. */
1814
+ export type SdkAdminFact = AdminFeatureFact;
1815
+
1719
1816
  /** What `FeatureServer.externalServices` is called with. */
1720
1817
  export interface SdkExternalServicesContext<Repo = unknown> {
1721
1818
  repo: Repo;
@@ -80,6 +80,7 @@ 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
+ canModerate: false,
83
84
  e2e: false,
84
85
  suspended: false,
85
86
  created: 0
@@ -142,6 +142,8 @@ export interface RecordedCalls {
142
142
  livePublishes: { workspaceId: number; event: string; payload: unknown }[];
143
143
  /** Accounts beaten through `live.accountChanged`, in order. */
144
144
  accountChanges: number[];
145
+ /** How many times `live.pendingChanged` was called. */
146
+ pendingChanges: number;
145
147
  }
146
148
 
147
149
  /** What a command's test context records on top of {@link RecordedCalls}. */
@@ -220,6 +222,7 @@ function recordingDevices(
220
222
  )
221
223
  )
222
224
  : Promise.resolve(devices.find((d) => d.id === id) ?? testDevice({ id })),
225
+ assertControl: () => Promise.resolve(),
223
226
  list: () => Promise.resolve([...devices]),
224
227
  isOnline: (id) => devices.find((d) => d.id === id)?.online ?? true
225
228
  };
@@ -541,6 +544,7 @@ export function createTestContext<Repo = undefined>(
541
544
  pinnedInstants: [],
542
545
  livePublishes: [],
543
546
  accountChanges: [],
547
+ pendingChanges: 0,
544
548
  progress: []
545
549
  };
546
550
  const isOwner = overrides.isOwner ?? true;
@@ -573,6 +577,7 @@ export function createTestContext<Repo = undefined>(
573
577
  email: `user${overrides.userId ?? 1}@deveye.test`,
574
578
  username: `user${overrides.userId ?? 1}`,
575
579
  isAdmin: overrides.isAdmin ?? false,
580
+ canModerate: overrides.isAdmin ?? false,
576
581
  e2e: false,
577
582
  suspended: false,
578
583
  created: 0
@@ -616,7 +621,19 @@ export function createTestContext<Repo = undefined>(
616
621
  ticket: (payload) =>
617
622
  Promise.resolve(
618
623
  `ticket:${JSON.stringify({ userId: overrides.userId ?? 1, workspaceId, payload, unlocked: overrides.unlocked ?? true })}`
619
- )
624
+ ),
625
+ // Only a ticket this caller minted, in this workspace, reads back.
626
+ redeem: (ticket) => {
627
+ if (!ticket.startsWith('ticket:')) return Promise.resolve(null);
628
+ const parsed = JSON.parse(ticket.slice('ticket:'.length)) as {
629
+ userId: number;
630
+ workspaceId: number;
631
+ payload: unknown;
632
+ };
633
+ const mine =
634
+ parsed.userId === (overrides.userId ?? 1) && parsed.workspaceId === workspaceId;
635
+ return Promise.resolve(mine ? { payload: parsed.payload } : null);
636
+ }
620
637
  },
621
638
  keys: {
622
639
  sealBytes: (plain) => `sealed:${Buffer.from(plain).toString('base64')}`,
@@ -629,6 +646,9 @@ export function createTestContext<Repo = undefined>(
629
646
  },
630
647
  accountChanged(userId) {
631
648
  recorded.accountChanges.push(userId);
649
+ },
650
+ pendingChanged() {
651
+ recorded.pendingChanges++;
632
652
  }
633
653
  },
634
654
  quota: {
@@ -658,19 +678,19 @@ export function createTestContext<Repo = undefined>(
658
678
  },
659
679
  items: {
660
680
  restrictions: () => Promise.resolve(restrictions),
661
- // The exact rule of the app's dispatcher: the feature first (a
662
- // restriction can only lower), then the row.
681
+ // The app's rule: the item's override replaces the feature level,
682
+ // in both directions; without one, the feature level decides.
663
683
  assert(itemId, level = 'read') {
664
- if (level === 'write' && !canWrite) {
665
- return Promise.reject(new FeatureError('forbidden', 'write required'));
666
- }
667
684
  const restriction = restrictions.get(itemId);
668
685
  if (restriction === 'none') {
669
686
  return Promise.reject(new FeatureError('forbidden', 'item hidden'));
670
687
  }
671
- if (restriction === 'read' && level === 'write') {
688
+ if (level === 'write' && restriction === 'read') {
672
689
  return Promise.reject(new FeatureError('forbidden', 'item read-only'));
673
690
  }
691
+ if (level === 'write' && restriction === undefined && !canWrite) {
692
+ return Promise.reject(new FeatureError('forbidden', 'write required'));
693
+ }
674
694
  return Promise.resolve();
675
695
  },
676
696
  canExtra(itemId, key) {
@@ -756,7 +776,7 @@ export interface RecordedServiceCalls extends RecordedCalls {
756
776
  liveChanges: number[];
757
777
  /** `live.changed` calls that named topics, as `{ workspaceId, topics }` (a bare beat is not listed here). */
758
778
  liveTopicChanges: { workspaceId: number; topics: readonly string[] }[];
759
- /** Emails `accountMail.send` and `sendToAdmins` accepted, with the address they went to. */
779
+ /** Emails `accountMail.send` and `sendToModerators` accepted, with the address they went to. */
760
780
  mails: { userId: number; to: string; message: SdkAccountMailMessage }[];
761
781
  }
762
782
 
@@ -835,6 +855,7 @@ export function createTestServiceDeps<Repo = undefined>(
835
855
  pinnedInstants: [],
836
856
  livePublishes: [],
837
857
  accountChanges: [],
858
+ pendingChanges: 0,
838
859
  tickers: [],
839
860
  liveChanges: [],
840
861
  liveTopicChanges: [],
@@ -915,6 +936,9 @@ export function createTestServiceDeps<Repo = undefined>(
915
936
  },
916
937
  accountChanged(userId) {
917
938
  recorded.accountChanges.push(userId);
939
+ },
940
+ pendingChanged() {
941
+ recorded.pendingChanges++;
918
942
  }
919
943
  },
920
944
  quotaFor: () => ({
@@ -995,13 +1019,17 @@ export function createTestServiceDeps<Repo = undefined>(
995
1019
  recorded.mails.push({ userId, to, message });
996
1020
  return Promise.resolve(to);
997
1021
  },
998
- sendToAdmins(message) {
1022
+ sendToModerators(message) {
999
1023
  if (overrides.mailConfigured === false) {
1000
1024
  return Promise.reject(new FeatureError('conflict', 'no mail transport'));
1001
1025
  }
1002
- const admins = (overrides.accounts ?? []).filter((a) => a.isAdmin && !a.suspended);
1003
- for (const a of admins) recorded.mails.push({ userId: a.id, to: a.email, message });
1004
- return Promise.resolve(admins.map((a) => a.email));
1026
+ const moderators = (overrides.accounts ?? []).filter(
1027
+ (a) => a.canModerate && !a.suspended
1028
+ );
1029
+ for (const a of moderators) {
1030
+ recorded.mails.push({ userId: a.id, to: a.email, message });
1031
+ }
1032
+ return Promise.resolve(moderators.map((a) => a.email));
1005
1033
  }
1006
1034
  },
1007
1035
  audit: (entry) => {