@deveye/types 0.18.2 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveye/types",
3
- "version": "0.18.2",
3
+ "version": "0.18.3",
4
4
  "description": "Shared contracts (types + zod schemas) for DevEye apps",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -0,0 +1,46 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * A domain name a feature serves under, declared in the feature's settings
5
+ * and verified in two stages: ownership (a TXT record DevEye checks itself),
6
+ * then service (the owning feature's own probe).
7
+ *
8
+ * Host and token travel in the clear: both are published in the DNS.
9
+ */
10
+
11
+ export const DNS_RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'SRV'] as const;
12
+
13
+ export const dnsRecordSchema = z.object({
14
+ type: z.enum(DNS_RECORD_TYPES),
15
+ /** Fully qualified, without the trailing dot. */
16
+ name: z.string().min(1).max(255),
17
+ value: z.string().min(1).max(4096),
18
+ /** MX and SRV only. */
19
+ priority: z.number().int().nonnegative().optional()
20
+ });
21
+ export type DnsRecord = z.infer<typeof dnsRecordSchema>;
22
+
23
+ /** `pending` until the first check has run. */
24
+ export const domainStateSchema = z.enum(['pending', 'ok', 'failed']);
25
+ export type DomainState = z.infer<typeof domainStateSchema>;
26
+
27
+ export const FEATURE_DOMAIN_HOST_MAX = 253;
28
+
29
+ export const featureDomainSchema = z.object({
30
+ id: z.number().int().positive(),
31
+ host: z.string().min(1).max(FEATURE_DOMAIN_HOST_MAX),
32
+ /** The TXT record that proves ownership. */
33
+ ownership: dnsRecordSchema,
34
+ /** What the owning feature asks to publish on top of it. */
35
+ records: z.array(dnsRecordSchema),
36
+ dnsState: domainStateSchema,
37
+ dnsError: z.string(),
38
+ probeState: domainStateSchema,
39
+ probeError: z.string(),
40
+ /** Unix seconds. Null until both stages have passed once. */
41
+ verifiedAt: z.number().int().nullable(),
42
+ checkedAt: z.number().int().nullable(),
43
+ /** How many of the feature's items designate this domain. */
44
+ useCount: z.number().int().nonnegative()
45
+ });
46
+ export type FeatureDomain = z.infer<typeof featureDomainSchema>;
@@ -270,6 +270,18 @@ export const FEATURE_REGISTRY: readonly (FeatureDescriptor & { id: WorkspaceFeat
270
270
  sources: {
271
271
  hint: 'La clé d’API du NVD, facultative : sans elle le catalogue se remplit quand même, elle ne fait que relever le quota de requêtes.'
272
272
  }
273
+ },
274
+ {
275
+ id: 'mailserver',
276
+ label: 'Serveur mail',
277
+ description:
278
+ 'Lecture : les adresses hébergées et leur activité. Écriture : créer une adresse, régler son quota, déclarer un domaine.',
279
+ icon: 'at',
280
+ notifies: false,
281
+ hasItems: true,
282
+ itemNoun: 'adresse',
283
+ itemNounGender: 'f',
284
+ shareTier: 'open'
273
285
  }
274
286
  ];
275
287
 
@@ -37,7 +37,8 @@ export const nativeHomeFeatureIdSchema = z.enum([
37
37
  'finance',
38
38
  'audience',
39
39
  'osint',
40
- 'cve'
40
+ 'cve',
41
+ 'mailserver'
41
42
  ]);
42
43
  export type NativeHomeFeatureId = z.infer<typeof nativeHomeFeatureIdSchema>;
43
44
 
@@ -142,7 +142,13 @@ export const nativeLiveTopicSchema = z.enum([
142
142
  * quelle fonctionnalité, et un canal change pour toutes à la fois alors que
143
143
  * `mutates` est déclaré par commande.
144
144
  */
145
- 'notify'
145
+ 'notify',
146
+ /**
147
+ * Les domaines déclarés par une fonctionnalité de l'espace, et leur état de
148
+ * vérification. À part pour la même raison que `notify` : ils se relisent
149
+ * depuis les réglages de n'importe quelle fonctionnalité qui en gère.
150
+ */
151
+ 'domain'
146
152
  ]);
147
153
  export type NativeLiveTopic = z.infer<typeof nativeLiveTopicSchema>;
148
154
 
@@ -193,6 +199,7 @@ export const TOPIC_FEATURE: Record<NativeLiveTopic, WorkspaceFeatureId | null> =
193
199
  audience: 'audience',
194
200
  osint: 'osint',
195
201
  cve: 'cve',
202
+ mailserver: 'mailserver',
196
203
  workspace: null,
197
204
  home: null,
198
205
  account: null,
@@ -201,7 +208,10 @@ export const TOPIC_FEATURE: Record<NativeLiveTopic, WorkspaceFeatureId | null> =
201
208
  admin: null,
202
209
  // Aucun droit de feature à vérifier : la relecture déclenchée est gardée
203
210
  // côté commande. Même nature que `workspace`.
204
- notify: null
211
+ notify: null,
212
+ // Même régime : la trame ne porte aucune donnée, et `domain.list` vérifie
213
+ // le droit sur la fonctionnalité visée.
214
+ domain: null
205
215
  };
206
216
 
207
217
  /**
@@ -88,7 +88,14 @@ export const workspaceFeatureIdSchema = z.enum([
88
88
  * Veille CVE. `read` = lire le fil et chercher dans le catalogue, `write` =
89
89
  * épingler une CVE pour tout l'espace et poser la clé d'API du NVD.
90
90
  */
91
- 'cve'
91
+ 'cve',
92
+ /**
93
+ * Serveur mail. `read` = voir les adresses hébergées et leur activité,
94
+ * `write` = créer une adresse, régler son quota, déclarer un domaine.
95
+ * Réinitialiser un mot de passe et purger la file d'envoi sont des
96
+ * permissions propres du module.
97
+ */
98
+ 'mailserver'
92
99
  ]);
93
100
 
94
101
  export type WorkspaceFeatureId = z.infer<typeof workspaceFeatureIdSchema>;
@@ -0,0 +1,40 @@
1
+ import { z } from 'zod';
2
+ import { FEATURE_DOMAIN_HOST_MAX, featureDomainSchema } from '../domain/featureDomain';
3
+ import { featureIdSchema } from '../domain/workspaceRole';
4
+
5
+ /**
6
+ * The domains of one feature in the active workspace. Cross-cutting: the
7
+ * feature is an input, and each command authorizes against it (read to list,
8
+ * write for the rest). A feature whose manifest declares no `domains` is
9
+ * refused.
10
+ */
11
+
12
+ export const domainList = {
13
+ command: 'domain.list' as const,
14
+ input: z.object({ feature: featureIdSchema }),
15
+ output: z.object({ domains: z.array(featureDomainSchema) })
16
+ };
17
+
18
+ export const domainAdd = {
19
+ command: 'domain.add' as const,
20
+ input: z.object({
21
+ feature: featureIdSchema,
22
+ host: z.string().min(1).max(FEATURE_DOMAIN_HOST_MAX)
23
+ }),
24
+ output: z.object({ domain: featureDomainSchema })
25
+ };
26
+
27
+ /** Runs both stages now instead of waiting for the background pass. */
28
+ export const domainVerify = {
29
+ command: 'domain.verify' as const,
30
+ input: z.object({ feature: featureIdSchema, id: z.number().int().positive() }),
31
+ output: z.object({ domain: featureDomainSchema })
32
+ };
33
+
34
+ export const domainRemove = {
35
+ command: 'domain.remove' as const,
36
+ input: z.object({ feature: featureIdSchema, id: z.number().int().positive() }),
37
+ output: z.object({ ok: z.literal(true) })
38
+ };
39
+
40
+ export const domainCommands = [domainList, domainAdd, domainVerify, domainRemove] as const;
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { agentCommands } from './agent';
3
+ import { domainCommands } from './domain';
3
4
  import { feedbackCommands } from './feedback';
4
5
  import { homeCommands } from './home';
5
6
  import { liveCommands } from './live';
@@ -30,6 +31,7 @@ export const featureCommands = [
30
31
  ...homeCommands,
31
32
  ...notifyCommands,
32
33
  ...sharingCommands,
34
+ ...domainCommands,
33
35
  ...liveCommands
34
36
  ] as const;
35
37
 
package/src/index.ts CHANGED
@@ -682,6 +682,21 @@ export {
682
682
  sharingCommands
683
683
  } from './features/sharing';
684
684
  export { SHAREABLE_FEATURES, SHARE_WIRED_FEATURES } from './domain/featureRegistry';
685
+ export {
686
+ DNS_RECORD_TYPES,
687
+ FEATURE_DOMAIN_HOST_MAX,
688
+ dnsRecordSchema,
689
+ domainStateSchema,
690
+ featureDomainSchema
691
+ } from './domain/featureDomain';
692
+ export type { DnsRecord, DomainState, FeatureDomain } from './domain/featureDomain';
693
+ export {
694
+ domainAdd,
695
+ domainCommands,
696
+ domainList,
697
+ domainRemove,
698
+ domainVerify
699
+ } from './features/domain';
685
700
  export {
686
701
  metricSeriesPointSchema,
687
702
  metricSnapshotSchema,
@@ -25,6 +25,7 @@ declare module 'deveye-sdk-client' {
25
25
  } from 'react';
26
26
  import type {
27
27
  FeatureAccess,
28
+ FeatureDomain,
28
29
  FeatureId,
29
30
  MinimalUser,
30
31
  User,
@@ -464,6 +465,17 @@ declare module 'deveye-sdk-client' {
464
465
  export function useFeatureLifecycle(hooks: { onUnmount?: () => void }): void;
465
466
  /** The members of the active workspace, as the session lists them (empty before it answers). */
466
467
  export function useWorkspaceMembers(): readonly MinimalUser[];
468
+ /**
469
+ * The domains of a feature whose manifest declares `domains`, in the
470
+ * active workspace, kept live. For a form that designates one (filter on
471
+ * `verifiedAt !== null`); declaring and verifying happen in the Domains
472
+ * tab, opened with `<FeatureSettingsButton initialSection='domains' />`.
473
+ */
474
+ export function useDomains(feature: FeatureId): {
475
+ domains: readonly FeatureDomain[];
476
+ loading: boolean;
477
+ error: string | null;
478
+ };
467
479
  /**
468
480
  * A member's identity dot: their avatar, or the default picture until they
469
481
  * upload one. `user` may be undefined: a deleted account must not break a
package/src/sdk/client.ts CHANGED
@@ -343,13 +343,33 @@ export interface AudienceClientProvider {
343
343
  * the ready senders (open tier, enabled) an email notification channel picks
344
344
  * from, and the feature's own account dialog.
345
345
  */
346
+ /** What a caller already knows of the mailbox it sends to Mail's account form. */
347
+ export interface MailAccountPrefill {
348
+ displayName: string;
349
+ emailAddress: string;
350
+ imap: { host: string; port: number; username: string; password: string };
351
+ smtp: { host: string; port: number; username: string; password: string };
352
+ }
353
+
346
354
  export interface MailClientProvider {
347
355
  /** The workspace's ready senders, as the module lists them. */
348
356
  listSenders(): Promise<readonly { id: number; label: string; address: string }[]>;
357
+ /**
358
+ * The account holding this address among those the caller can read, or
359
+ * null. A guarded account of a locked session does not show its address:
360
+ * it reads as absent.
361
+ */
362
+ findByAddress(address: string): Promise<{ id: number } | null>;
349
363
  /**
350
364
  * The feature's account form (manual connection or OAuth consent), to
351
365
  * declare a mailbox from the channel form. `onSaved` fires when a mailbox
352
- * came out of it; the host re-lists to find which.
366
+ * came out of it; the host re-lists to find which. With `prefill`, the
367
+ * form opens on the manual connection, filled in and ready to save.
353
368
  */
354
- AccountDialog: ComponentType<{ open: boolean; onClose: () => void; onSaved: () => void }>;
369
+ AccountDialog: ComponentType<{
370
+ open: boolean;
371
+ onClose: () => void;
372
+ onSaved: () => void;
373
+ prefill?: MailAccountPrefill;
374
+ }>;
355
375
  }
@@ -0,0 +1,30 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+
4
+ import { DOMAIN_HOST_PATTERN, domainOwnershipRecord, normaliseDomainHost } from './domains';
5
+
6
+ test('normaliseDomainHost drops case, port and trailing dots', () => {
7
+ assert.equal(normaliseDomainHost(' Rdv.Example.COM:8443 '), 'rdv.example.com');
8
+ assert.equal(normaliseDomainHost('example.com..'), 'example.com');
9
+ });
10
+
11
+ test('DOMAIN_HOST_PATTERN wants at least two plain labels', () => {
12
+ assert.ok(DOMAIN_HOST_PATTERN.test('mail.example.com'));
13
+ assert.ok(DOMAIN_HOST_PATTERN.test('xn--bcher-kva.example'));
14
+ assert.ok(!DOMAIN_HOST_PATTERN.test('localhost'));
15
+ assert.ok(!DOMAIN_HOST_PATTERN.test('exa mple.com'));
16
+ assert.ok(!DOMAIN_HOST_PATTERN.test('https://example.com'));
17
+ assert.ok(!DOMAIN_HOST_PATTERN.test(`${'a'.repeat(64)}.com`));
18
+ });
19
+
20
+ test('the ownership record names the feature by its slug', () => {
21
+ assert.deepEqual(domainOwnershipRecord('x-rdv', 'example.com', 'abc'), {
22
+ type: 'TXT',
23
+ name: '_deveye.example.com',
24
+ value: 'deveye-rdv=abc'
25
+ });
26
+ assert.equal(
27
+ domainOwnershipRecord('mailserver', 'example.com', 'abc').value,
28
+ 'deveye-mailserver=abc'
29
+ );
30
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Domain names a feature serves under: the pure half, shared by the server
3
+ * contract, the app and the test harness. No I/O here.
4
+ */
5
+ import type { DnsRecord } from '../domain/featureDomain';
6
+
7
+ export type SdkDnsRecord = DnsRecord;
8
+
9
+ /** A bare host name: labels of letters, digits and hyphens, at least two. Punycode passes as is. */
10
+ export const DOMAIN_HOST_PATTERN = /^(?=.{1,253}$)[a-z0-9-]{1,63}(\.[a-z0-9-]{1,63})+$/;
11
+
12
+ /** Lowercase, port and trailing dots dropped. Accepts a raw `Host` header. */
13
+ export function normaliseDomainHost(raw: string): string {
14
+ return raw.trim().toLowerCase().split(':')[0].replace(/\.+$/, '');
15
+ }
16
+
17
+ /**
18
+ * The ownership proof DevEye checks itself: `_deveye.<host>` holding
19
+ * `deveye-<slug>=<token>`, the slug being the feature id without its `x-`.
20
+ * Several features can prove the same host: each adds its own value.
21
+ */
22
+ export function domainOwnershipRecord(
23
+ featureId: string,
24
+ host: string,
25
+ token: string
26
+ ): SdkDnsRecord {
27
+ const slug = featureId.replace(/^x-/, '');
28
+ return { type: 'TXT', name: `_deveye.${host}`, value: `deveye-${slug}=${token}` };
29
+ }
@@ -100,3 +100,36 @@ test('resolveExtras: the owner holds everything, a member what the grant says, u
100
100
  assert.equal(owner.extraValue('reset'), '');
101
101
  assert.equal(resolveExtras(undefined, true, { reset: true }).canExtra('reset'), false);
102
102
  });
103
+
104
+ test('validateManifest ties the domains tab to the domains field', () => {
105
+ const domains = { hint: 'Your own names.', service: 'Point the name here.' };
106
+ assert.doesNotThrow(() =>
107
+ validateManifest({ ...base, domains, settings: { feature: ['domains'] } })
108
+ );
109
+ assert.throws(
110
+ () => validateManifest({ ...base, settings: { feature: ['domains'] } }),
111
+ /domains tab requires domains/
112
+ );
113
+ assert.throws(
114
+ () =>
115
+ validateManifest({
116
+ ...base,
117
+ hasItems: true,
118
+ itemNoun: 'thing',
119
+ domains,
120
+ settings: { item: ['domains'] }
121
+ }),
122
+ /feature-scope/
123
+ );
124
+ assert.throws(
125
+ () => validateManifest({ ...base, domains: { ...domains, service: ' ' } }),
126
+ /empty service/
127
+ );
128
+ });
129
+
130
+ test('validateManifest refuses a tab id it does not know', () => {
131
+ assert.throws(
132
+ () => validateManifest({ ...base, settings: { feature: ['nope' as 'general'] } }),
133
+ /unknown settings tab/
134
+ );
135
+ });
@@ -111,8 +111,10 @@ export type NativeCapability =
111
111
 
112
112
  /**
113
113
  * Settings tabs the shell can render for you.
114
- * - `'notifications'` and `'permissions'` are fully generic: DevEye renders
115
- * them from the manifest alone, you write no component.
114
+ * - `'notifications'`, `'permissions'` and `'domains'` are fully generic:
115
+ * DevEye renders them from the manifest alone, you write no component.
116
+ * `'domains'` (feature scope only) needs the manifest's `domains` and a
117
+ * `domains` entry on the server side.
116
118
  * - `'general'`, `'sources'`, `'sync'` and `'encryption'` need a panel
117
119
  * component, provided by your client entry (`settingsPanels`), keyed by
118
120
  * the tab id. `'sync'` (item scope only) is the cadence and maintenance of
@@ -122,7 +124,7 @@ export type NativeCapability =
122
124
  * places the tab, the module owns the choice.
123
125
  */
124
126
  export type SettingsTab =
125
- 'general' | 'sources' | 'notifications' | 'permissions' | 'sync' | 'encryption';
127
+ 'general' | 'sources' | 'domains' | 'notifications' | 'permissions' | 'sync' | 'encryption';
126
128
 
127
129
  /** A custom settings tab. Needs a matching panel in `settingsPanels`. */
128
130
  export interface CustomTabRef {
@@ -144,6 +146,7 @@ const CUSTOM_TAB_PATTERN = /^[a-z][a-z0-9]{1,23}$/;
144
146
  const BUILTIN_TABS: readonly string[] = [
145
147
  'general',
146
148
  'sources',
149
+ 'domains',
147
150
  'notifications',
148
151
  'permissions',
149
152
  'sync',
@@ -151,6 +154,9 @@ const BUILTIN_TABS: readonly string[] = [
151
154
  'sharing'
152
155
  ];
153
156
 
157
+ /** The built-in ids a manifest may list: `sharing` is the shell's alone. */
158
+ const DECLARABLE_TABS: readonly string[] = BUILTIN_TABS.filter((id) => id !== 'sharing');
159
+
154
160
  /** See {@link FeatureManifest.alsoInvalidatedBy}. */
155
161
  export interface CrossTopicInvalidation {
156
162
  /** A NATIVE live topic that is not this feature's own. */
@@ -207,6 +213,22 @@ export interface FeatureManifest<Id extends FeatureId = FeatureId> {
207
213
  itemNounGender?: 'm' | 'f';
208
214
  /** Feature-scope reusable settings (API keys, destinations). Opens the Sources tab. */
209
215
  sources?: { hint: string };
216
+ /**
217
+ * The feature serves something under domain names the workspace owns (a
218
+ * public page, a mailbox). Opens the Domains tab, which DevEye renders:
219
+ * declaring, the DNS records to publish, verification. Commits the server
220
+ * entry to `domains` (`FeatureDomainsEntry`).
221
+ */
222
+ domains?: {
223
+ /** Lead sentence of the tab. */
224
+ hint: string;
225
+ /** The one sentence of the second step: how the domain gets wired to what you serve. */
226
+ service: string;
227
+ /** Placeholder of the host field. */
228
+ placeholder?: string;
229
+ /** Warning of the removal confirm when items designate the domain. */
230
+ removal?: string;
231
+ };
210
232
  /**
211
233
  * Whether an item can be projected into another workspace. Decided by
212
234
  * encryption: only the open tier is readable by the server alone. Anything
@@ -392,6 +414,11 @@ export function validateManifest(m: FeatureManifest): void {
392
414
  }
393
415
  }
394
416
 
417
+ if (m.domains) {
418
+ if (!m.domains.hint.trim()) fail(m.id, 'domains: empty hint');
419
+ if (!m.domains.service.trim()) fail(m.id, 'domains: empty service');
420
+ }
421
+
395
422
  for (const scope of ['feature', 'item'] as const) {
396
423
  for (const tab of m.settings?.[scope] ?? []) {
397
424
  if (typeof tab === 'string') {
@@ -402,9 +429,16 @@ export function validateManifest(m: FeatureManifest): void {
402
429
  if (tab === 'sources' && scope === 'item') {
403
430
  fail(m.id, 'sources is a feature-scope tab');
404
431
  }
432
+ if (tab === 'domains' && !m.domains) fail(m.id, 'domains tab requires domains');
433
+ if (tab === 'domains' && scope === 'item') {
434
+ fail(m.id, 'domains is a feature-scope tab');
435
+ }
405
436
  if (tab === 'encryption' && scope === 'feature') {
406
437
  fail(m.id, 'encryption is an item-scope tab');
407
438
  }
439
+ if (!DECLARABLE_TABS.includes(tab)) {
440
+ fail(m.id, `unknown settings tab « ${String(tab)} »`);
441
+ }
408
442
  } else {
409
443
  if (!CUSTOM_TAB_PATTERN.test(tab.id) || BUILTIN_TABS.includes(tab.id)) {
410
444
  fail(m.id, `invalid custom tab id « ${tab.id} »`);
@@ -125,20 +125,40 @@ export interface MailSender {
125
125
  address: string;
126
126
  }
127
127
 
128
+ /**
129
+ * A file carried along a message: the `.ics` invitation of a booking, a small
130
+ * report. `Uint8Array` rather than `Buffer`: the published package does not
131
+ * depend on Node's types beyond `node:net`, and the adapter bridges it.
132
+ */
133
+ export interface MailAttachment {
134
+ filename: string;
135
+ contentType: string;
136
+ content: Uint8Array;
137
+ }
138
+
128
139
  export interface MailTransportProvider {
129
140
  /** The workspace's ready senders (open tier, enabled). */
130
141
  listSenders(workspaceId: number): Promise<readonly MailSender[]>;
131
142
  /** Is this account a ready sender of this workspace right now? */
132
143
  isReady(accountId: number, workspaceId: number): Promise<boolean>;
133
144
  /**
134
- * Sends one plain-text message from this account. Resolves `true` when the
135
- * provider accepted it; `false` (never a throw) when the account is not a
136
- * ready sender or the send failed, the failure logged by the module.
145
+ * Sends one message from this account. Resolves `true` when the provider
146
+ * accepted it; `false` (never a throw) when the account is not a ready
147
+ * sender or the send failed, the failure logged by the module.
148
+ *
149
+ * `text` stays mandatory whatever else is given: a recipient whose client
150
+ * shows no HTML must lose nothing.
137
151
  */
138
152
  send(
139
153
  accountId: number,
140
154
  workspaceId: number,
141
- message: { to: string; subject: string; text: string }
155
+ message: {
156
+ to: string;
157
+ subject: string;
158
+ text: string;
159
+ html?: string;
160
+ attachments?: readonly MailAttachment[];
161
+ }
142
162
  ): Promise<boolean>;
143
163
  }
144
164
 
package/src/sdk/server.ts CHANGED
@@ -7,6 +7,7 @@ import type { AuthWindow, DeviceReport, IntegrityReport, ReportProcess } from '.
7
7
  import type { AgentManifest } from '../http/device';
8
8
  import type { MetricSnapshot } from '../domain/metrics';
9
9
  import type { UserColor } from '../domain/user';
10
+ import type { SdkDnsRecord } from './domains';
10
11
  import type {
11
12
  AgentSyncAckPayload,
12
13
  AgentSyncApplyChunkPayload,
@@ -30,6 +31,12 @@ import type {
30
31
  } from '../protocol/agent';
31
32
 
32
33
  export { isPublicIp, isSafePublicUrl } from './net';
34
+ export {
35
+ DOMAIN_HOST_PATTERN,
36
+ domainOwnershipRecord,
37
+ normaliseDomainHost,
38
+ type SdkDnsRecord
39
+ } from './domains';
33
40
 
34
41
  /**
35
42
  * Server-side SDK surface: what a feature module's handlers and background
@@ -579,6 +586,77 @@ export interface SdkFleetDevices {
579
586
  isOnline(deviceId: string): boolean;
580
587
  }
581
588
 
589
+ /**
590
+ * One of your feature's domains (manifest `domains`). Declared and verified
591
+ * in the Domains tab the shell renders; your module only reads them.
592
+ */
593
+ export interface SdkDomain {
594
+ id: number;
595
+ workspaceId: number;
596
+ host: string;
597
+ /** Published in the DNS by nature, so not a secret. */
598
+ token: string;
599
+ /** Both stages have passed, and neither has failed three times in a row since. */
600
+ verified: boolean;
601
+ verifiedAt: number | null;
602
+ }
603
+
604
+ /** Your feature's domains in the caller's workspace. Throws `forbidden` unless the manifest declares `domains`. */
605
+ export interface SdkDomains {
606
+ list(): Promise<readonly SdkDomain[]>;
607
+ get(id: number): Promise<SdkDomain | null>;
608
+ verified(): Promise<readonly SdkDomain[]>;
609
+ }
610
+
611
+ /** Your feature's domains, sessionless: for a service or a public route. */
612
+ export interface SdkFleetDomains {
613
+ /** Whatever the workspace. `host` is normalised for you: pass the raw `Host` header. */
614
+ findByHost(host: string): Promise<SdkDomain | null>;
615
+ get(workspaceId: number, id: number): Promise<SdkDomain | null>;
616
+ listVerified(workspaceId: number): Promise<readonly SdkDomain[]>;
617
+ }
618
+
619
+ /** DNS lookups, injected so a probe is testable. A name that does not exist yields `[]`, not a throw. */
620
+ export interface SdkDns {
621
+ /** One string per record, the 255-byte chunks rejoined. */
622
+ txt(name: string): Promise<string[]>;
623
+ mx(name: string): Promise<{ exchange: string; priority: number }[]>;
624
+ cname(name: string): Promise<string[]>;
625
+ }
626
+
627
+ /** What the domain hooks receive. Sessionless: they also run from the background pass. */
628
+ export interface FeatureDomainsContext<Repo = unknown> {
629
+ repo: Repo;
630
+ origins: { app: string; public: string };
631
+ /** Open tier only. */
632
+ cipherFor(workspaceId: number): SdkCipher;
633
+ storeFor(workspaceId: number): SessionlessFeatureStore;
634
+ keys: SdkServerKeys;
635
+ dns: SdkDns;
636
+ logger: SdkLogger;
637
+ }
638
+
639
+ export type SdkDomainProbe = { ok: true } | { ok: false; error: string };
640
+
641
+ /**
642
+ * Your half of domain verification, required when the manifest declares
643
+ * `domains`. Ownership (the TXT record) is always DevEye's check; yours is
644
+ * the second stage: is the domain really wired to what you serve?
645
+ */
646
+ export interface FeatureDomainsEntry<Repo = unknown> {
647
+ /** What to publish on top of the ownership record (a CNAME, an MX...). Shown in the records dialog. */
648
+ records(ctx: FeatureDomainsContext<Repo>, domain: SdkDomain): Promise<readonly SdkDnsRecord[]>;
649
+ /** Called only once ownership holds. A failed check is a returned sentence, never a throw. */
650
+ probe(ctx: FeatureDomainsContext<Repo>, domain: SdkDomain): Promise<SdkDomainProbe>;
651
+ /** How many of your items designate each domain, by domain id. Shown on the row and in the removal warning. */
652
+ useCount?(
653
+ ctx: FeatureDomainsContext<Repo>,
654
+ workspaceId: number
655
+ ): Promise<ReadonlyMap<number, number>>;
656
+ /** Runs before the row is deleted: drop your references. A throw aborts the removal. */
657
+ onRemoved?(ctx: FeatureDomainsContext<Repo>, domain: SdkDomain): Promise<void>;
658
+ }
659
+
582
660
  /** What a handler receives. One request, one workspace, rights pre-resolved. */
583
661
  export interface SdkFeatureContext<Repo = unknown> {
584
662
  userId: number;
@@ -613,6 +691,8 @@ export interface SdkFeatureContext<Repo = unknown> {
613
691
  items: SdkItems;
614
692
  /** Projections into the active workspace. Throws `forbidden` when the manifest says `shareTier: 'never'`. */
615
693
  sharing: SdkSharing;
694
+ /** Your feature's domains in this workspace (manifest `domains`). */
695
+ domains: SdkDomains;
616
696
  /** The named contracts the host holds, see `SdkProviders`. */
617
697
  providers: SdkProviders;
618
698
  /** Fire-and-forget audit line; actor, IP and workspace are pre-bound. */
@@ -690,6 +770,18 @@ export interface SdkPublicRequest {
690
770
  * What a ticketed GET (a download URL, an OAuth callback) carries.
691
771
  */
692
772
  query?: unknown;
773
+ /**
774
+ * Path parameters the host decoded (`/rdv/:ref` reads `{ ref: 'abc' }`).
775
+ * `unknown` like `body` and `query`: re-read it through a schema. Absent
776
+ * from a route that declares none.
777
+ */
778
+ params?: unknown;
779
+ /**
780
+ * The request's host, normalised by the host: `Host`, or `X-Forwarded-Host`
781
+ * behind a trusted proxy, port included. UNTRUSTED data: it proves nothing,
782
+ * it only picks among what the database already verified.
783
+ */
784
+ host?: string;
693
785
  ip: string;
694
786
  }
695
787
 
@@ -797,6 +889,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
797
889
  secrecy: { redeem(ticket: string): Promise<SdkRedeemedTicket | null> };
798
890
  /** Where DevEye lives (the same `origins` a request context gets): for a page or a link a route hands to the browser. */
799
891
  origins: { app: string; public: string };
892
+ /** Your feature's domains, whatever the workspace (manifest `domains`). */
893
+ domains: SdkFleetDomains;
800
894
  /** The named contracts the host holds, see `SdkProviders`. */
801
895
  providers: SdkProviders;
802
896
  /**
@@ -829,6 +923,8 @@ export interface FeatureServer<Repo = unknown> {
829
923
  * notifies (the channels screen names the item a route points to).
830
924
  */
831
925
  items?: FeatureItemsEntry<Repo>;
926
+ /** Required when the manifest declares `domains`, refused otherwise. */
927
+ domains?: FeatureDomainsEntry<Repo>;
832
928
  }
833
929
 
834
930
  /**
@@ -2,7 +2,13 @@ import assert from 'node:assert/strict';
2
2
  import { test } from 'node:test';
3
3
  import { z } from 'zod';
4
4
 
5
- import { createTestContext, createTestServiceDeps, testDevice } from './testing';
5
+ import {
6
+ createTestContext,
7
+ createTestDomainsContext,
8
+ createTestServiceDeps,
9
+ testDevice,
10
+ testDomain
11
+ } from './testing';
6
12
 
7
13
  test('createTestContext follows the manifest for extras, and records what handlers do', async () => {
8
14
  const manifest = {
@@ -60,3 +66,29 @@ test('createTestServiceDeps: one store per workspace, hand-driven tickers, a wra
60
66
  assert.equal(deps.devicesFor(1).isOnline('d1'), false);
61
67
  assert.equal((await deps.devicesFor(1).list()).length, 1);
62
68
  });
69
+
70
+ test('the harness scopes domains to the workspace, and finds a host whatever its spelling', async () => {
71
+ const domains = [
72
+ testDomain({ id: 1, host: 'a.example.com' }),
73
+ testDomain({ id: 2, host: 'b.example.com', verified: false, verifiedAt: null }),
74
+ testDomain({ id: 3, host: 'c.example.com', workspaceId: 2 })
75
+ ];
76
+ const ctx = createTestContext({ domains });
77
+ assert.deepEqual(
78
+ (await ctx.domains.list()).map((d) => d.id),
79
+ [1, 2]
80
+ );
81
+ assert.deepEqual(
82
+ (await ctx.domains.verified()).map((d) => d.id),
83
+ [1]
84
+ );
85
+ assert.equal(await ctx.domains.get(3), null, 'another workspace');
86
+
87
+ const deps = createTestServiceDeps({ domains });
88
+ assert.equal((await deps.domains.findByHost('C.Example.com:443.'))?.id, 3);
89
+ assert.equal(await deps.domains.findByHost('nope.example.com'), null);
90
+
91
+ const hooks = createTestDomainsContext({ dns: { txt: () => Promise.resolve(['v=spf1']) } });
92
+ assert.deepEqual(await hooks.dns.txt('x'), ['v=spf1']);
93
+ assert.deepEqual(await hooks.dns.mx('x'), []);
94
+ });
@@ -1,9 +1,13 @@
1
1
  import type { ZodType } from 'zod';
2
2
  import type { ItemAccess } from '../domain/sharing';
3
+ import { normaliseDomainHost } from './domains';
3
4
  import { resolveExtras, type FeatureManifest } from './manifest';
4
5
  import {
5
6
  FeatureError,
6
7
  type DevEyeFacade,
8
+ type FeatureDomainsContext,
9
+ type SdkDns,
10
+ type SdkDomain,
7
11
  type FeatureServiceDeps,
8
12
  type FeatureStore,
9
13
  type SdkCipher,
@@ -236,6 +240,20 @@ function fakeDerive(salt: string, info: string, length: number): Uint8Array {
236
240
  return out;
237
241
  }
238
242
 
243
+ function memoryDomains(domains: readonly SdkDomain[]) {
244
+ return {
245
+ in: (workspaceId: number) => domains.filter((d) => d.workspaceId === workspaceId),
246
+ byHost: (host: string) => domains.find((d) => d.host === normaliseDomainHost(host)) ?? null
247
+ };
248
+ }
249
+
250
+ /** Lookups that find nothing, unless the test says otherwise. */
251
+ const emptyDns: SdkDns = {
252
+ txt: () => Promise.resolve([]),
253
+ mx: () => Promise.resolve([]),
254
+ cname: () => Promise.resolve([])
255
+ };
256
+
239
257
  /** The named contracts a test hands to the module (`providers` override). */
240
258
  function fakeProviders(table: Readonly<Record<string, unknown>>): SdkProviders {
241
259
  return { get: <T>(key: string) => table[key] as T | undefined };
@@ -296,6 +314,8 @@ export interface TestContextOverrides<Repo> {
296
314
  * identity cipher either way.
297
315
  */
298
316
  shares?: Readonly<Record<string, number>>;
317
+ /** The feature's domains, every workspace mixed: `ctx.domains` answers for the active one. Default none. */
318
+ domains?: readonly SdkDomain[];
299
319
  /** The named contracts the host holds (`ctx.providers.get(key)`). */
300
320
  providers?: Readonly<Record<string, unknown>>;
301
321
  }
@@ -418,6 +438,21 @@ export function createTestContext<Repo = undefined>(
418
438
  sendSyncChunk: () => 0,
419
439
  syncChunkBuffered: () => 0
420
440
  },
441
+ domains: {
442
+ list: () => Promise.resolve(memoryDomains(overrides.domains ?? []).in(workspaceId)),
443
+ get: (id) =>
444
+ Promise.resolve(
445
+ memoryDomains(overrides.domains ?? [])
446
+ .in(workspaceId)
447
+ .find((d) => d.id === id) ?? null
448
+ ),
449
+ verified: () =>
450
+ Promise.resolve(
451
+ memoryDomains(overrides.domains ?? [])
452
+ .in(workspaceId)
453
+ .filter((d) => d.verified)
454
+ )
455
+ },
421
456
  providers: fakeProviders(overrides.providers ?? {}),
422
457
  audit: (entry) => {
423
458
  recorded.audits.push({ action: entry.action, description: entry.description });
@@ -462,6 +497,8 @@ export interface TestServiceOverrides<Repo> {
462
497
  origins?: { app: string; public: string };
463
498
  /** Instants `telemetry.snapshot` answers (matched within a second). Default none. */
464
499
  snapshots?: readonly SdkTelemetrySnapshot[];
500
+ /** The feature's domains, every workspace mixed. Default none. */
501
+ domains?: readonly SdkDomain[];
465
502
  /** The named contracts the host holds (`deps.providers.get(key)`). */
466
503
  providers?: Readonly<Record<string, unknown>>;
467
504
  }
@@ -564,6 +601,22 @@ export function createTestServiceDeps<Repo = undefined>(
564
601
  openBytes: (sealed) => sealedBytes.get(sealed) ?? null,
565
602
  derive: fakeDerive
566
603
  },
604
+ domains: {
605
+ findByHost: (host) =>
606
+ Promise.resolve(memoryDomains(overrides.domains ?? []).byHost(host)),
607
+ get: (workspaceId, id) =>
608
+ Promise.resolve(
609
+ memoryDomains(overrides.domains ?? [])
610
+ .in(workspaceId)
611
+ .find((d) => d.id === id) ?? null
612
+ ),
613
+ listVerified: (workspaceId) =>
614
+ Promise.resolve(
615
+ memoryDomains(overrides.domains ?? [])
616
+ .in(workspaceId)
617
+ .filter((d) => d.verified)
618
+ )
619
+ },
567
620
  providers: fakeProviders(overrides.providers ?? {}),
568
621
  createTicker({ intervalMs, tick }) {
569
622
  recorded.tickers.push({ intervalMs, tick });
@@ -572,3 +625,51 @@ export function createTestServiceDeps<Repo = undefined>(
572
625
  logger: silentLogger
573
626
  };
574
627
  }
628
+
629
+ /** A domain row for a test, verified by default. */
630
+ export function testDomain(over: Partial<SdkDomain> & { id: number; host: string }): SdkDomain {
631
+ return { workspaceId: 1, token: 'a'.repeat(32), verified: true, verifiedAt: 1, ...over };
632
+ }
633
+
634
+ /**
635
+ * What the `domains` hooks of a server entry receive, in memory: identity
636
+ * cipher, one store per workspace, and lookups that find nothing unless `dns`
637
+ * says otherwise.
638
+ */
639
+ export function createTestDomainsContext<Repo = undefined>(
640
+ overrides: {
641
+ repo?: Repo;
642
+ dns?: Partial<SdkDns>;
643
+ origins?: { app: string; public: string };
644
+ } = {}
645
+ ): FeatureDomainsContext<Repo> {
646
+ const stores = new Map<number, TestFeatureStore>();
647
+ const sealedBytes = new Map<string, Uint8Array>();
648
+ return {
649
+ repo: overrides.repo as Repo,
650
+ origins: overrides.origins ?? {
651
+ app: 'https://deveye.test',
652
+ public: 'https://public.deveye.test'
653
+ },
654
+ cipherFor: () => identityCipher,
655
+ storeFor(workspaceId) {
656
+ let store = stores.get(workspaceId);
657
+ if (!store) {
658
+ store = memoryStore();
659
+ stores.set(workspaceId, store);
660
+ }
661
+ return store;
662
+ },
663
+ keys: {
664
+ sealBytes: (plain) => {
665
+ const handle = `sealed:${sealedBytes.size}`;
666
+ sealedBytes.set(handle, Uint8Array.from(plain));
667
+ return handle;
668
+ },
669
+ openBytes: (sealed) => sealedBytes.get(sealed) ?? null,
670
+ derive: fakeDerive
671
+ },
672
+ dns: { ...emptyDns, ...overrides.dns },
673
+ logger: silentLogger
674
+ };
675
+ }