@deveye/types 0.24.6 → 0.25.1

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/copy.ts CHANGED
@@ -47,6 +47,15 @@ export interface ItemTreeTable {
47
47
  * indistinguishable from another. Revisit it whenever you add one.
48
48
  */
49
49
  sealed?: readonly string[];
50
+ /**
51
+ * Sealed columns that hold a secret among other data: the copy carries
52
+ * what this returns instead of the clear text (a mail account's servers,
53
+ * without its password), and the copy arrives to be reconnected. A secret
54
+ * held in a column of its own belongs in `omit`. A copy goes through the
55
+ * browser of whoever makes it, who may only read the item: no password or
56
+ * token ever travels.
57
+ */
58
+ redact?: Readonly<Record<string, (plain: string) => string>>;
50
59
  /**
51
60
  * Columns pointing at a row of a table of this tree (this one included),
52
61
  * by that table's name: rewritten to the ids the destination handed out. A
@@ -155,6 +164,12 @@ export function itemTreeProblem(tree: ItemTree): string | null {
155
164
  const bad = names.find((n) => !IDENTIFIER.test(n));
156
165
  if (bad !== undefined) return `${t.table}: "${bad}" is not a plain SQL identifier`;
157
166
  if (seen.has(t.table)) return `${t.table}: listed twice`;
167
+ const unsealed = Object.keys(t.redact ?? {}).find(
168
+ (column) => !(t.sealed ?? []).includes(column)
169
+ );
170
+ if (unsealed !== undefined) {
171
+ return `${t.table}.${unsealed}: only a sealed column is redacted`;
172
+ }
158
173
  if (t.tier && t !== root) return `${t.table}: only the root chooses the tier`;
159
174
  if ((t.orderColumn || t.unique) && (t !== root || !t.workspaceColumn)) {
160
175
  return `${t.table}: orderColumn and unique are for a root that names its workspaceColumn`;
@@ -274,7 +289,7 @@ export async function exportItemTree(
274
289
  `Une ligne de ${t.table} est illisible : copie annulée, rien n’a été écrit.`
275
290
  );
276
291
  }
277
- copy[column] = plain;
292
+ copy[column] = t.redact?.[column]?.(plain) ?? plain;
278
293
  } else copy[column] = toWire(value);
279
294
  }
280
295
  out[t.table].push(copy);
@@ -375,7 +390,14 @@ export async function importItemTree(
375
390
  );
376
391
  }
377
392
  values[column] = mapped;
378
- } else if (sealed.has(column) && typeof raw === 'string' && raw !== '') {
393
+ } else if (sealed.has(column) && raw !== null && raw !== '') {
394
+ // Anything but text would land in an encrypted column unsealed.
395
+ if (typeof raw !== 'string') {
396
+ throw new FeatureError(
397
+ 'validation',
398
+ `Valeur inattendue dans la copie : ${t.table}.${column}.`
399
+ );
400
+ }
379
401
  values[column] = await cipher.encrypt(raw);
380
402
  } else values[column] = fromWire(raw);
381
403
  }
@@ -0,0 +1,28 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { csvCell, toCsv } from './csv';
5
+
6
+ test('csvCell: a formula trigger gets an apostrophe, a number does not, a separator gets quotes', () => {
7
+ assert.equal(csvCell('=SUM(A1:A9)'), "'=SUM(A1:A9)");
8
+ assert.equal(csvCell('@cmd'), "'@cmd");
9
+ assert.equal(csvCell('+33 6 12 34 56 78'), "'+33 6 12 34 56 78");
10
+ assert.equal(csvCell('-12.50'), '-12.50');
11
+ assert.equal(csvCell('-12,50'), '-12,50');
12
+ assert.equal(csvCell('a;b'), '"a;b"');
13
+ assert.equal(csvCell('a,b', ','), '"a,b"');
14
+ assert.equal(csvCell('a,b'), 'a,b');
15
+ assert.equal(csvCell('dit "oui"'), '"dit ""oui"""');
16
+ assert.equal(csvCell('ligne\nsuite'), '"ligne\nsuite"');
17
+ });
18
+
19
+ test('toCsv: a byte order mark, CRLF rows, the separator of choice', () => {
20
+ assert.equal(
21
+ toCsv([
22
+ ['a', 'b'],
23
+ ['1', '=2']
24
+ ]),
25
+ "\ufeffa;b\r\n1;'=2"
26
+ );
27
+ assert.equal(toCsv([['a', 'b']], ','), '\ufeffa,b');
28
+ });
package/src/sdk/csv.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A CSV a spreadsheet opens as a table and never evaluates. The byte order
3
+ * mark makes Excel read UTF-8 as UTF-8; the separator defaults to the one a
4
+ * French Excel expects.
5
+ */
6
+ export function toCsv(rows: readonly (readonly string[])[], separator = ';'): string {
7
+ return `\ufeff${rows.map((row) => row.map((cell) => csvCell(cell, separator)).join(separator)).join('\r\n')}`;
8
+ }
9
+
10
+ /**
11
+ * One cell. Quoted when it carries the separator, a quote or a line break;
12
+ * prefixed with an apostrophe when it starts with a formula trigger (`=`, `+`,
13
+ * `-`, `@`, a tab, a carriage return) without being a plain number: quoting
14
+ * alone changes nothing, the spreadsheet strips the quotes before it evaluates.
15
+ * Content that came from a form, a bank statement or a database is someone
16
+ * else's text.
17
+ */
18
+ export function csvCell(value: string, separator = ';'): string {
19
+ const formula = /^[=+\-@\t\r]/.test(value) && !/^-?\d+(?:[.,]\d+)?$/.test(value);
20
+ const safe = formula ? `'${value}` : value;
21
+ return safe.includes(separator) || /["\r\n]/.test(safe)
22
+ ? `"${safe.replace(/"/g, '""')}"`
23
+ : safe;
24
+ }
@@ -59,7 +59,10 @@ export interface SavedDeviceChoice {
59
59
  authorUserId?: number | null;
60
60
  }
61
61
 
62
- /** The chosen device, if the caller may open its network; a `validation` error when none is chosen. */
62
+ /**
63
+ * The chosen device, if the caller may open its network and confirmed with an
64
+ * authenticator code lately (`control`); a `validation` error when none is chosen.
65
+ */
63
66
  export async function authorizeRelayDevice(
64
67
  ctx: SdkFeatureContext<unknown>,
65
68
  deviceId: string | null,
@@ -68,7 +71,10 @@ export async function authorizeRelayDevice(
68
71
  if (!deviceId) {
69
72
  throw new FeatureError('validation', `Choisissez l’appareil par lequel joindre ${what}.`);
70
73
  }
71
- return ctx.deveye.devices.authorize(deviceId, { extras: [DEVICE_NETWORK_RIGHT] });
74
+ return ctx.deveye.devices.authorize(deviceId, {
75
+ extras: [DEVICE_NETWORK_RIGHT],
76
+ control: true
77
+ });
72
78
  }
73
79
 
74
80
  /**
package/src/sdk/index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * `@deveye/types/sdk/client` (component contracts), `@deveye/types/sdk/testing`
7
7
  * (handler test harness).
8
8
  */
9
+ export * from './csv';
9
10
  export * from './deviceRelayOption';
10
11
  export * from './ids';
11
12
  export * from './manifest';
@@ -93,6 +93,16 @@ export interface FeatureQuotaSpec {
93
93
  perOperation?: true;
94
94
  }
95
95
 
96
+ /** One tab of `adminTabs`. */
97
+ export interface AdminTabSpec {
98
+ /** Same shape as an extra permission key: the key of `FeatureClient.AdminTabs` and of `adminPending`. */
99
+ id: string;
100
+ /** A noun, as a tab reads: "Reports". */
101
+ label: string;
102
+ /** Moderators open it too; without it, global administrators only. */
103
+ moderation?: true;
104
+ }
105
+
96
106
  /** Hard cap on `extraPermissions`: keeps role editors legible. */
97
107
  export const MAX_EXTRA_PERMISSIONS = 10;
98
108
 
@@ -364,13 +374,15 @@ export interface FeatureManifest<Id extends FeatureId = FeatureId> {
364
374
  adminTools?: boolean;
365
375
  };
366
376
  /**
367
- * A page of yours among the system pages of the account menu, which only a
368
- * global administrator sees and opens: what the operator of the instance
369
- * handles for everyone (reports to moderate). Needs
370
- * `FeatureClient.AdminView`, and every command it sends declares
371
- * `access.admin`. `icon` defaults to the manifest's.
377
+ * Your tabs in the feature administration popup, after the overview the
378
+ * host draws: what the operator of the instance handles for everyone,
379
+ * across accounts. A `moderation` tab (reports to handle) also opens to
380
+ * moderators, and every command it sends declares `access.moderation`;
381
+ * any other is for global administrators only, its commands declaring
382
+ * `access.admin`. Each id needs its component in `FeatureClient.AdminTabs`;
383
+ * `server.adminPending` lights the badges, by tab id.
372
384
  */
373
- adminEntry?: { label: string; icon?: string };
385
+ adminTabs?: readonly AdminTabSpec[];
374
386
  /**
375
387
  * The module lives in the user menu only: no card, no row in the roles
376
388
  * screen, `Widget` and `Full` not required. Requires `accountEntry`, no
@@ -531,7 +543,13 @@ export function validateManifest(m: FeatureManifest): void {
531
543
  }
532
544
 
533
545
  if (m.accountEntry && !m.accountEntry.label.trim()) fail(m.id, 'accountEntry requires a label');
534
- if (m.adminEntry && !m.adminEntry.label.trim()) fail(m.id, 'adminEntry requires a label');
546
+ const adminTabIds = new Set<string>();
547
+ for (const tab of m.adminTabs ?? []) {
548
+ if (!EXTRA_KEY_PATTERN.test(tab.id)) fail(m.id, `invalid admin tab id « ${tab.id} »`);
549
+ if (adminTabIds.has(tab.id)) fail(m.id, `duplicate admin tab id « ${tab.id} »`);
550
+ adminTabIds.add(tab.id);
551
+ if (!tab.label.trim()) fail(m.id, `admin tab « ${tab.id} »: empty label`);
552
+ }
535
553
  if (m.accountOnly) {
536
554
  if (!m.accountEntry) fail(m.id, 'accountOnly requires accountEntry');
537
555
  if (m.hasItems) fail(m.id, 'accountOnly modules own no items');
@@ -5,7 +5,7 @@ import test from 'node:test';
5
5
  import { isPublicIp, isRemoteFailure, isSafePublicUrl, NetRefused, safeFetchText } from './net';
6
6
 
7
7
  test('isPublicIp: the private ranges of both families read as false', () => {
8
- for (const ip of ['8.8.8.8', '1.1.1.1', '2001:4860:4860::8888']) {
8
+ for (const ip of ['8.8.8.8', '1.1.1.1', '2001:4860:4860::8888', '::ffff:808:808']) {
9
9
  assert.equal(isPublicIp(ip), true, ip);
10
10
  }
11
11
  for (const ip of [
@@ -21,8 +21,13 @@ test('isPublicIp: the private ranges of both families read as false', () => {
21
21
  '::1',
22
22
  'fd00::1',
23
23
  'fe80::1',
24
- // IPv4-mapped: judged on the v4 part, not on the v6 prefix.
24
+ // IPv4 written in IPv6, dotted or in the hex form a URL parser gives
25
+ // back: judged on the v4 part, not on the v6 prefix.
25
26
  '::ffff:127.0.0.1',
27
+ '::ffff:7f00:1',
28
+ '::ffff:a9fe:a9fe',
29
+ '::ffff:a00:1',
30
+ '::7f00:1',
26
31
  'not-an-ip'
27
32
  ]) {
28
33
  assert.equal(isPublicIp(ip), false, ip);
@@ -40,6 +45,9 @@ test('isSafePublicUrl: only public http(s) hosts, string or URL', () => {
40
45
  'https://app.localhost',
41
46
  'http://192.168.1.10/admin',
42
47
  'http://[::1]:8080',
48
+ // The parser turns these into `[::ffff:7f00:1]` and `[::ffff:a9fe:a9fe]`.
49
+ 'http://[::ffff:127.0.0.1]:3000/',
50
+ 'http://[::ffff:169.254.169.254]/latest/meta-data/',
43
51
  // Anything but http(s): a git `ext::` or a `file://` would run a
44
52
  // command or read the server's disk.
45
53
  'file:///etc/passwd',
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,
@@ -250,6 +251,17 @@ export interface SdkAlert {
250
251
  embeds?: readonly Record<string, unknown>[];
251
252
  }
252
253
 
254
+ /** An alert for the instance's administrators, see `FeatureServiceDeps.alertInstance`. */
255
+ export interface SdkInstanceAlert {
256
+ /** Groups repeats: one alert per key every ten minutes at most. */
257
+ key: string;
258
+ /** `resolved` announces a return to normal. */
259
+ level: 'info' | 'resolved' | 'error' | 'critical';
260
+ title: string;
261
+ /** Rendered as a code block: a message, a path, a date. */
262
+ detail?: string;
263
+ }
264
+
253
265
  /** A routed channel that can carry a live message (see `notify.liveChannels`). */
254
266
  export interface SdkLiveChannel {
255
267
  id: number;
@@ -374,13 +386,36 @@ export interface DevEyeFacade {
374
386
  /**
375
387
  * Throws `not_found` unless the device exists AND is visible in this
376
388
  * 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`.
389
+ * included: membership is the boundary. In a command, the CALLER must
390
+ * also see it: Devices open to their role, and the device not hidden
391
+ * from it. `level: 'write'` requires the device writable for them
392
+ * (`forbidden` on a read-only one), for a handler that changes what
393
+ * the machine does. With `extras`, a handler also requires the CALLER
394
+ * to hold these permissions of the Devices feature on this device
395
+ * (`docker` to drive its containers), and throws `forbidden`
396
+ * otherwise: a module cannot name another feature's permissions in its
397
+ * own `access`.
398
+ *
399
+ * `control: true` where the handler is about to make the machine act
400
+ * (save a source it reads, a target it deploys to, a folder it syncs):
401
+ * the caller must also have confirmed with an authenticator code
402
+ * lately, `stepup_required` otherwise, which the client turns into the
403
+ * prompt and a retry. Leave it out of a mere check of rights (a list of
404
+ * what the caller could pick).
405
+ */
406
+ authorize(
407
+ deviceId: string,
408
+ options?: { level?: FeatureAccess; extras?: readonly string[]; control?: boolean }
409
+ ): Promise<SdkDevice>;
410
+ /**
411
+ * The `control` confirmation alone, where no device exists yet (a code
412
+ * that pairs new machines).
413
+ */
414
+ assertControl(): Promise<void>;
415
+ /**
416
+ * The devices this workspace sees: its own, and those shared into it.
417
+ * In a command, without those hidden from the caller.
381
418
  */
382
- authorize(deviceId: string, options?: { extras?: readonly string[] }): Promise<SdkDevice>;
383
- /** The devices this workspace sees: its own, and those shared into it. */
384
419
  list(): Promise<readonly SdkDevice[]>;
385
420
  isOnline(deviceId: string): boolean;
386
421
  };
@@ -417,6 +452,8 @@ export interface SdkAccount {
417
452
  username: string;
418
453
  /** A global administrator of this DevEye. */
419
454
  isAdmin: boolean;
455
+ /** A moderator or a global administrator: the accounts that handle reports. */
456
+ canModerate: boolean;
420
457
  /**
421
458
  * A throwaway account the app's end-to-end runner created and will delete:
422
459
  * never a person, and its address receives nothing. Check this, never the
@@ -508,12 +545,14 @@ export interface SdkAccountMail {
508
545
  */
509
546
  send(userId: number, message: SdkAccountMailMessage): Promise<string>;
510
547
  /**
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.
548
+ * One copy to each active moderator and administrator of this DevEye, for
549
+ * what awaits their decision (a report of illicit content). A moderator
550
+ * never sees where a report came from: leave the reporter's address and IP
551
+ * out of the message. Resolves the addresses reached, empty when there is
552
+ * no one. Every address is tried; the first refusal then rejects. Throws
553
+ * `conflict` without a transport.
515
554
  */
516
- sendToAdmins(message: SdkAccountMailMessage): Promise<readonly string[]>;
555
+ sendToModerators(message: SdkAccountMailMessage): Promise<readonly string[]>;
517
556
  }
518
557
 
519
558
  /**
@@ -703,7 +742,11 @@ export interface AgentsFacade {
703
742
  */
704
743
  requestFilesMutate(deviceId: string, payload: AgentFilesMutatePayload): boolean;
705
744
  requestFilesUpload(deviceId: string, payload: AgentFilesUploadPayload): boolean;
706
- awaitFilesOp(opId: string, timeoutMs: number): Promise<{ ok: boolean; error?: string }>;
745
+ awaitFilesOp(
746
+ deviceId: string,
747
+ opId: string,
748
+ timeoutMs: number
749
+ ): Promise<{ ok: boolean; error?: string }>;
707
750
  /** Forgets a pending `awaitFilesOp` (the frame was never sent, or the caller gave up). */
708
751
  cancelFilesOp(opId: string): void;
709
752
  /**
@@ -961,6 +1004,15 @@ export interface SdkSecrecy {
961
1004
  * sees a session id nor a key. Default life: two minutes.
962
1005
  */
963
1006
  ticket(payload: unknown, opts?: { ttlSeconds?: number }): Promise<string>;
1007
+ /**
1008
+ * The payload of a ticket THIS session minted (same caller, session,
1009
+ * workspace and module), `null` for any other: expired, forged, or minted
1010
+ * elsewhere. For a gesture that must end where it began: an OAuth popup
1011
+ * hands `code` and `state` back to the page that opened it, which sends
1012
+ * them through a command, so a consent link mailed to someone else never
1013
+ * lands anywhere.
1014
+ */
1015
+ redeem(ticket: string): Promise<{ payload: unknown } | null>;
964
1016
  }
965
1017
 
966
1018
  /**
@@ -978,8 +1030,9 @@ export interface SdkItems {
978
1030
  restrictions(): Promise<ReadonlyMap<string, ItemAccess>>;
979
1031
  /**
980
1032
  * 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.
1033
+ * (default `'read'`), its override included. A command that names its
1034
+ * item in `access.item` is already checked; call it for an item reached
1035
+ * another way (the item a row belongs to).
983
1036
  */
984
1037
  assert(itemId: string, level?: FeatureAccess): Promise<void>;
985
1038
  /**
@@ -1066,6 +1119,8 @@ export interface SdkLive {
1066
1119
  publish(workspaceId: number, event: string, payload: unknown): void;
1067
1120
  /** {@link SdkContextLive.accountChanged}, from a service (a webhook, a ticker). */
1068
1121
  accountChanged(userId: number): void;
1122
+ /** {@link SdkContextLive.pendingChanged}, from a service or a public route (a report just filed). */
1123
+ pendingChanged(): void;
1069
1124
  }
1070
1125
 
1071
1126
  /**
@@ -1083,6 +1138,12 @@ export interface SdkContextLive {
1083
1138
  * (pauses and resumes). No payload, so no capability.
1084
1139
  */
1085
1140
  accountChanged(userId: number): void;
1141
+ /**
1142
+ * What `server.adminPending` counts may have moved (a report decided): the
1143
+ * host counts again and relights the badges of every moderator and
1144
+ * administrator connected. Coalesced by the host, cheap to call.
1145
+ */
1146
+ pendingChanged(): void;
1086
1147
  }
1087
1148
 
1088
1149
  /** The whole fleet, sessionless (capability `'devices.read'`), for services. */
@@ -1249,6 +1310,18 @@ export interface SdkFeatureContext<Repo = unknown> {
1249
1310
  origins: SdkOrigins;
1250
1311
  }
1251
1312
 
1313
+ /**
1314
+ * Finds the item a command reaches through another row; `undefined` or `null`
1315
+ * when that row does not exist. Method-shaped so a definition typed with your
1316
+ * repo stays assignable to the host's list of commands.
1317
+ */
1318
+ export type SdkItemFinder<Repo, I extends ZodType> = {
1319
+ find(
1320
+ ctx: SdkFeatureContext<Repo>,
1321
+ input: z.output<I>
1322
+ ): Promise<string | number | null | undefined>;
1323
+ }['find'];
1324
+
1252
1325
  /**
1253
1326
  * One command your module handles. The dispatcher validates `input` before the
1254
1327
  * handler and `output` after it, enforces `access` first, and broadcasts your
@@ -1268,16 +1341,28 @@ export interface SdkFeatureDefinition<
1268
1341
  * `level`: the caller's level on your feature (`read` by default).
1269
1342
  * `extras`: the extra permissions the caller must hold, ALL required.
1270
1343
  * `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.
1344
+ * still applies. `moderation`: a moderator or a global administrator, for
1345
+ * the commands of a `moderation` admin tab. Your feature id is implied:
1346
+ * you cannot gate on another feature's rights.
1273
1347
  * `scope: 'account'`: the command acts on the caller's ACCOUNT, not on a
1274
1348
  * workspace. The host runs it in the caller's personal workspace whatever
1275
1349
  * the client sent, so the role held in a shared workspace never decides.
1350
+ * `item`: the item the command targets, as the input field holding its
1351
+ * id, or as a function that finds it when the command reaches it through
1352
+ * another row (the site a form belongs to). The host checks `level` and
1353
+ * `extras` on THAT item, whose override replaces the role in both
1354
+ * directions, before your handler runs. The function runs first, with the
1355
+ * same context; it returns `undefined` when the row does not exist. Without
1356
+ * an item (or when the optional field is absent from a request), the role
1357
+ * on your feature decides alone: an override never opens a command that
1358
+ * does not name its item.
1276
1359
  */
1277
1360
  access?: {
1278
1361
  level?: FeatureAccess;
1279
1362
  extras?: readonly string[];
1363
+ item?: Extract<keyof z.input<I>, string> | SdkItemFinder<Repo, I>;
1280
1364
  admin?: boolean;
1365
+ moderation?: boolean;
1281
1366
  scope?: 'account';
1282
1367
  };
1283
1368
  /**
@@ -1642,6 +1727,14 @@ export interface FeatureServiceDeps<Repo = unknown> {
1642
1727
  domains: SdkFleetDomains;
1643
1728
  /** The named contracts the host holds, see `SdkProviders`. */
1644
1729
  providers: SdkProviders;
1730
+ /**
1731
+ * Alerts the instance's administrators on their `system` channels, for
1732
+ * what the INSTANCE must fix (its configuration, a certificate it serves),
1733
+ * never for one user's trouble: that goes to `deveyeFor(ws).notify`. The
1734
+ * host prefixes `key` with your feature id; nothing leaves outside
1735
+ * production. Log the cause as well: the alert is not a log.
1736
+ */
1737
+ alertInstance(alert: SdkInstanceAlert): void;
1645
1738
  /**
1646
1739
  * The app's standard loop: setInterval + reentrancy guard + unref, the
1647
1740
  * exact pattern of every native service. Use it instead of rolling your own.
@@ -1714,8 +1807,31 @@ export interface FeatureServer<Repo = unknown> {
1714
1807
  mailSamples?: readonly SdkMailSample[];
1715
1808
  /** Your end-to-end scenarios, run by an administrator against this very server. */
1716
1809
  e2e?: FeatureE2eEntry<Repo>;
1810
+ /**
1811
+ * What awaits a human decision, by id of `manifest.adminTabs` (open
1812
+ * reports, a queue running late): the badges of the account menu and of
1813
+ * the administration popup. A tab absent or at 0 lights nothing. Cheap
1814
+ * counts only: the host asks again on every `live.pendingChanged()`.
1815
+ */
1816
+ adminPending?(ctx: SdkAdminContext<Repo>): Promise<Readonly<Record<string, number>>>;
1817
+ /**
1818
+ * Your own figures for the overview of the administration popup, across
1819
+ * every account (links created, files stored): what the host cannot count
1820
+ * from your tables and quotas alone.
1821
+ */
1822
+ adminFacts?(ctx: SdkAdminContext<Repo>): Promise<readonly SdkAdminFact[]>;
1717
1823
  }
1718
1824
 
1825
+ /** What `FeatureServer.adminPending` and `adminFacts` are called with: no session, every account at once. */
1826
+ export interface SdkAdminContext<Repo = unknown> {
1827
+ repo: Repo;
1828
+ /** Your paused `stock` items, whatever the workspace. */
1829
+ pauses: SdkPlanPauses;
1830
+ }
1831
+
1832
+ /** One figure of `FeatureServer.adminFacts`. */
1833
+ export type SdkAdminFact = AdminFeatureFact;
1834
+
1719
1835
  /** What `FeatureServer.externalServices` is called with. */
1720
1836
  export interface SdkExternalServicesContext<Repo = unknown> {
1721
1837
  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