@deveye/types 0.21.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveye/types",
3
- "version": "0.21.0",
3
+ "version": "0.21.2",
4
4
  "description": "Shared contracts (types + zod schemas) for DevEye apps",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -48,11 +48,14 @@ export const MAINTENANCE_CLOSE_CODE = 4503;
48
48
  export const MAINTENANCE_MESSAGE_MAX = 1000;
49
49
 
50
50
  /**
51
- * The `session` frame that opens every socket. `maintenance` is optional: a
52
- * remote instance on an older version does not send it.
51
+ * The `session` frame that opens every socket. `version` is the server's app
52
+ * version, which a client compares with its own bundle to reload after an
53
+ * update. `version` and `maintenance` are optional: a remote instance on an
54
+ * older version does not send them.
53
55
  */
54
56
  export const sessionFrameSchema = z.object({
55
57
  userId: z.number().int().positive(),
58
+ version: z.string().optional(),
56
59
  maintenance: maintenanceStateSchema.optional()
57
60
  });
58
61
  export type SessionFrame = z.infer<typeof sessionFrameSchema>;
@@ -224,7 +224,9 @@ export const agentPolicySchema = z.object({
224
224
  /** Deployments (`composeDeploy`), on top of `docker`. */
225
225
  dockerDeploy: z.boolean().default(true),
226
226
  /** CloudSync shares: the server reading and writing a synced folder. */
227
- sync: z.boolean().default(true)
227
+ sync: z.boolean().default(true),
228
+ /** Tunnels (`tunnel.open`): a module reaching a service of the machine, such as a database. */
229
+ tunnel: z.boolean().default(true)
228
230
  });
229
231
  export type AgentPolicy = z.infer<typeof agentPolicySchema>;
230
232
 
@@ -258,7 +260,8 @@ export const agentInfoSchema = z.object({
258
260
  destroy: true,
259
261
  docker: true,
260
262
  dockerDeploy: true,
261
- sync: true
263
+ sync: true,
264
+ tunnel: true
262
265
  }),
263
266
  /** The agent reaches this server over plain http/ws (opted in locally): everything, shell included, travels in clear. */
264
267
  insecureTransport: z.boolean().default(false)
@@ -95,8 +95,15 @@ export type UserSecurity = z.infer<typeof userSecuritySchema>;
95
95
  * - `feedbackHintDismissed` : la bulle qui présente le bouton de signalement a
96
96
  * été vue. Posée par sa croix comme par l'ouverture du formulaire, elle ne
97
97
  * se retire jamais : la bulle se montre une fois dans la vie d'un compte.
98
+ * - `homeLayoutHintDismissed`, `aboutHintDismissed` : de même pour les bulles
99
+ * du bouton d'organisation de l'accueil et du numéro de version.
98
100
  */
99
- export const userSettingFlagSchema = z.enum(['hideLiveCursors', 'feedbackHintDismissed']);
101
+ export const userSettingFlagSchema = z.enum([
102
+ 'hideLiveCursors',
103
+ 'feedbackHintDismissed',
104
+ 'homeLayoutHintDismissed',
105
+ 'aboutHintDismissed'
106
+ ]);
100
107
  export type UserSettingFlag = z.infer<typeof userSettingFlagSchema>;
101
108
 
102
109
  export const userSchema = z.object({
package/src/http/auth.ts CHANGED
@@ -32,6 +32,8 @@ export const sessionBundleSchema = z.object({
32
32
  feedbackEnabled: z.boolean(),
33
33
  /** The marketing site (`SITE_URL`), for the legal links. `null`: none. */
34
34
  siteUrl: z.string().url().nullable(),
35
+ /** Where this server's source code is offered (`SOURCE_URL`), as the AGPL requires. `null`: none. */
36
+ sourceUrl: z.string().url().nullable(),
35
37
  /**
36
38
  * Admin only: the process booted with `MAINTENANCE=1` and no admin has
37
39
  * closed the reminder. Shown once the site maintenance is lifted. Read at
package/src/index.ts CHANGED
@@ -80,6 +80,15 @@ export {
80
80
  AGENT_TERM_OPEN,
81
81
  AGENT_TERM_OUTPUT,
82
82
  AGENT_TERM_RESIZE,
83
+ AGENT_TUNNEL_CLOSE,
84
+ AGENT_TUNNEL_CLOSED,
85
+ AGENT_TUNNEL_CREDIT,
86
+ AGENT_TUNNEL_DATA,
87
+ AGENT_TUNNEL_OPEN,
88
+ AGENT_TUNNEL_OPENED,
89
+ AGENT_TUNNEL_PIECE_BYTES,
90
+ AGENT_TUNNEL_PROBE,
91
+ AGENT_TUNNEL_WRITE,
83
92
  AGENT_UPDATE,
84
93
  AGENT_UPDATED,
85
94
  agentClientMessageSchema,
@@ -147,6 +156,13 @@ export {
147
156
  agentTermOpenPayloadSchema,
148
157
  agentTermOutputPayloadSchema,
149
158
  agentTermResizePayloadSchema,
159
+ agentTunnelClosedPayloadSchema,
160
+ agentTunnelClosePayloadSchema,
161
+ agentTunnelCreditPayloadSchema,
162
+ agentTunnelDataPayloadSchema,
163
+ agentTunnelOpenedPayloadSchema,
164
+ agentTunnelOpenPayloadSchema,
165
+ agentTunnelWritePayloadSchema,
150
166
  agentUpdatedMessagePayloadSchema,
151
167
  agentUpdatePayloadSchema,
152
168
  CLOUD_SYNC_CHUNK_EVENT,
@@ -251,6 +267,13 @@ export type {
251
267
  AgentTermInputPayload,
252
268
  AgentTermOpenPayload,
253
269
  AgentTermResizePayload,
270
+ AgentTunnelClosedPayload,
271
+ AgentTunnelClosePayload,
272
+ AgentTunnelCreditPayload,
273
+ AgentTunnelDataPayload,
274
+ AgentTunnelOpenedPayload,
275
+ AgentTunnelOpenPayload,
276
+ AgentTunnelWritePayload,
254
277
  AgentUpdatePayload,
255
278
  CloudSyncChunkPush,
256
279
  CloudSyncProgressPush,
@@ -345,6 +345,37 @@ export const agentFilesArchiveEndPayloadSchema = z.object({
345
345
  });
346
346
  export type AgentFilesArchiveEndPayload = z.infer<typeof agentFilesArchiveEndPayloadSchema>;
347
347
 
348
+ const tunnelId = z.string().min(1).max(64);
349
+ /** Raw bytes per `tunnel.data` or `tunnel.write` frame, before base64. */
350
+ export const AGENT_TUNNEL_PIECE_BYTES = 64 * 1024;
351
+ const tunnelData = z.string().max(90_000);
352
+
353
+ /** Agent → server: the TCP connection of a `tunnel.open` is up; bytes may flow. */
354
+ export const AGENT_TUNNEL_OPENED = 'tunnel.opened' as const;
355
+ export const agentTunnelOpenedPayloadSchema = z.object({ deviceId: z.uuid(), tunnelId });
356
+ export type AgentTunnelOpenedPayload = z.infer<typeof agentTunnelOpenedPayloadSchema>;
357
+
358
+ /** Agent → server: bytes read from the target (`data` base64). Spends one credit. */
359
+ export const AGENT_TUNNEL_DATA = 'tunnel.data' as const;
360
+ export const agentTunnelDataPayloadSchema = z.object({
361
+ deviceId: z.uuid(),
362
+ tunnelId,
363
+ data: tunnelData
364
+ });
365
+ export type AgentTunnelDataPayload = z.infer<typeof agentTunnelDataPayloadSchema>;
366
+
367
+ /**
368
+ * Agent → server: the tunnel ended, the last frame for its id. `error` when it
369
+ * did not end with the target closing (refused, unreachable, cut).
370
+ */
371
+ export const AGENT_TUNNEL_CLOSED = 'tunnel.closed' as const;
372
+ export const agentTunnelClosedPayloadSchema = z.object({
373
+ deviceId: z.uuid(),
374
+ tunnelId,
375
+ error: z.string().max(500).optional()
376
+ });
377
+ export type AgentTunnelClosedPayload = z.infer<typeof agentTunnelClosedPayloadSchema>;
378
+
348
379
  const syncOpId = z.string().min(1).max(64);
349
380
  const syncRelPath = z.string().min(1).max(SYNC_REL_PATH_MAX);
350
381
 
@@ -605,6 +636,18 @@ export const agentClientMessageSchema = z.discriminatedUnion('command', [
605
636
  command: z.literal(AGENT_FILES_ARCHIVE_END),
606
637
  payload: agentFilesArchiveEndPayloadSchema
607
638
  }),
639
+ z.object({
640
+ command: z.literal(AGENT_TUNNEL_OPENED),
641
+ payload: agentTunnelOpenedPayloadSchema
642
+ }),
643
+ z.object({
644
+ command: z.literal(AGENT_TUNNEL_DATA),
645
+ payload: agentTunnelDataPayloadSchema
646
+ }),
647
+ z.object({
648
+ command: z.literal(AGENT_TUNNEL_CLOSED),
649
+ payload: agentTunnelClosedPayloadSchema
650
+ }),
608
651
  z.object({
609
652
  command: z.literal(AGENT_SYNC_CHANGED),
610
653
  payload: agentSyncChangedPayloadSchema
@@ -871,6 +914,43 @@ export const AGENT_FILES_ARCHIVE_CANCEL = 'files.archiveCancel' as const;
871
914
  export const agentFilesArchiveCancelPayloadSchema = z.object({ opId: filesOpId });
872
915
  export type AgentFilesArchiveCancelPayload = z.infer<typeof agentFilesArchiveCancelPayloadSchema>;
873
916
 
917
+ /**
918
+ * Open a TCP connection from the machine to `host:port` and relay it: what
919
+ * lets a module reach a service only the machine can see (a database on its
920
+ * loopback). The agent answers `tunnel.opened` then `tunnel.data` frames under
921
+ * credits, or `tunnel.closed` with the reason. It only reaches its own
922
+ * loopback, plus the hosts its operator lists in `tunnel_targets`.
923
+ */
924
+ export const AGENT_TUNNEL_OPEN = 'tunnel.open' as const;
925
+ /** What an agent that knows `tunnel.open` declares in `report.agent.probes`. */
926
+ export const AGENT_TUNNEL_PROBE = 'tunnel';
927
+ export const agentTunnelOpenPayloadSchema = z.object({
928
+ tunnelId,
929
+ host: z.string().min(1).max(255),
930
+ port: z.number().int().min(1).max(65535),
931
+ /** Credits granted up front. */
932
+ window: z.number().int().min(1).max(64)
933
+ });
934
+ export type AgentTunnelOpenPayload = z.infer<typeof agentTunnelOpenPayloadSchema>;
935
+
936
+ /** Bytes for the target (`data` base64). */
937
+ export const AGENT_TUNNEL_WRITE = 'tunnel.write' as const;
938
+ export const agentTunnelWritePayloadSchema = z.object({ tunnelId, data: tunnelData });
939
+ export type AgentTunnelWritePayload = z.infer<typeof agentTunnelWritePayloadSchema>;
940
+
941
+ /** More credits for a tunnel, as the server consumes its `tunnel.data` frames. */
942
+ export const AGENT_TUNNEL_CREDIT = 'tunnel.credit' as const;
943
+ export const agentTunnelCreditPayloadSchema = z.object({
944
+ tunnelId,
945
+ credits: z.number().int().min(1).max(64)
946
+ });
947
+ export type AgentTunnelCreditPayload = z.infer<typeof agentTunnelCreditPayloadSchema>;
948
+
949
+ /** Close a tunnel. The agent sends nothing back: the server has already forgotten it. */
950
+ export const AGENT_TUNNEL_CLOSE = 'tunnel.close' as const;
951
+ export const agentTunnelClosePayloadSchema = z.object({ tunnelId });
952
+ export type AgentTunnelClosePayload = z.infer<typeof agentTunnelClosePayloadSchema>;
953
+
874
954
  /**
875
955
  * CloudSync, serveur → agent. Le serveur orchestre tout : l'agent reçoit ses
876
956
  * assignations (`sync.config`), scanne sur ordre, transfère sur ordre.
@@ -1217,6 +1297,22 @@ export const agentServerMessageSchema = z.discriminatedUnion('command', [
1217
1297
  command: z.literal(AGENT_FILES_ARCHIVE_CANCEL),
1218
1298
  payload: agentFilesArchiveCancelPayloadSchema
1219
1299
  }),
1300
+ z.object({
1301
+ command: z.literal(AGENT_TUNNEL_OPEN),
1302
+ payload: agentTunnelOpenPayloadSchema
1303
+ }),
1304
+ z.object({
1305
+ command: z.literal(AGENT_TUNNEL_WRITE),
1306
+ payload: agentTunnelWritePayloadSchema
1307
+ }),
1308
+ z.object({
1309
+ command: z.literal(AGENT_TUNNEL_CREDIT),
1310
+ payload: agentTunnelCreditPayloadSchema
1311
+ }),
1312
+ z.object({
1313
+ command: z.literal(AGENT_TUNNEL_CLOSE),
1314
+ payload: agentTunnelClosePayloadSchema
1315
+ }),
1220
1316
  z.object({
1221
1317
  command: z.literal(AGENT_SYNC_CONFIG),
1222
1318
  payload: agentSyncConfigPayloadSchema
@@ -1266,8 +1362,8 @@ export type OrderSignature = z.infer<typeof orderSignatureSchema>;
1266
1362
  /**
1267
1363
  * The orders the server signs (`ORDER_SIGNING_KEY`) and the agent refuses
1268
1364
  * unsigned: what runs code, writes or deletes files, changes the agent's
1269
- * privileges or its life, or drives its containers. Mirror of
1270
- * `SIGNED_COMMANDS` in `agent/src/protocol.rs`.
1365
+ * privileges or its life, drives its containers, or reaches into its network.
1366
+ * Mirror of `SIGNED_COMMANDS` in `agent/src/protocol.rs`.
1271
1367
  */
1272
1368
  export const SIGNED_AGENT_COMMANDS: ReadonlySet<string> = new Set([
1273
1369
  AGENT_TERM_OPEN,
@@ -1278,7 +1374,8 @@ export const SIGNED_AGENT_COMMANDS: ReadonlySet<string> = new Set([
1278
1374
  AGENT_DESTROY,
1279
1375
  AGENT_PKG_UPGRADE,
1280
1376
  AGENT_LIFECYCLE,
1281
- AGENT_DOCKER_ACTION
1377
+ AGENT_DOCKER_ACTION,
1378
+ AGENT_TUNNEL_OPEN
1282
1379
  ]);
1283
1380
 
1284
1381
  /**
@@ -35,6 +35,7 @@ declare module 'deveye-sdk-client' {
35
35
  } from '@deveye/types';
36
36
  import type {
37
37
  AccountPlan,
38
+ DeviceRelayOption,
38
39
  FeatureManifest,
39
40
  ManifestCommand,
40
41
  PageTheme,
@@ -698,6 +699,28 @@ declare module 'deveye-sdk-client' {
698
699
  disabled?: boolean;
699
700
  action?: ReactNode;
700
701
  }>;
702
+ /**
703
+ * The device through which a service is reached by its agent
704
+ * (`relayDeviceOptions` on the server side). `load` is the module's
705
+ * command listing them, `null` when read-only; a device one cannot choose
706
+ * stays listed, disabled, with its reason underneath. The label and the
707
+ * hint (what the device will see) stay with the caller.
708
+ */
709
+ export const DeviceRelayField: ComponentType<{
710
+ value: string;
711
+ onChange: (deviceId: string) => void;
712
+ load: (() => Promise<readonly DeviceRelayOption[]>) | null;
713
+ disabled?: boolean;
714
+ id?: string;
715
+ 'aria-label'?: string;
716
+ }>;
717
+ /** The options of a `DeviceRelayField`, for a form that renders its own field. */
718
+ export function useDeviceRelayOptions(
719
+ load: (() => Promise<readonly DeviceRelayOption[]>) | null
720
+ ): {
721
+ devices: readonly DeviceRelayOption[];
722
+ error: string | null;
723
+ };
701
724
  /** One rule of a `PathExclusionsEditor`. */
702
725
  export interface PathExclusionItem {
703
726
  key: string | number;
@@ -0,0 +1,206 @@
1
+ import assert from 'node:assert/strict';
2
+ import { connect, createServer, type AddressInfo, type Server } from 'node:net';
3
+ import { after, before, describe, it } from 'node:test';
4
+
5
+ import {
6
+ localForwarder,
7
+ openDeviceTunnel,
8
+ relayForAuthor,
9
+ relayOf,
10
+ type DeviceRelay
11
+ } from './deviceRelay';
12
+ import { AGENT_TUNNEL_PROBE } from '../protocol/agent';
13
+ import type { AgentsFacade, FeatureServiceDeps, SdkDevice } from './server';
14
+
15
+ /** An echo service standing for what only the device can reach. */
16
+ let echo: Server;
17
+ let echoPort = 0;
18
+
19
+ before(async () => {
20
+ echo = createServer((socket) => socket.pipe(socket));
21
+ await new Promise<void>((resolve) => echo.listen(0, '127.0.0.1', resolve));
22
+ echoPort = (echo.address() as AddressInfo).port;
23
+ });
24
+
25
+ after(async () => {
26
+ await new Promise<void>((resolve) => echo.close(() => resolve()));
27
+ });
28
+
29
+ /** Sends `text` to `host:port` and returns what comes back. */
30
+ function roundTrip(host: string, port: number, text: string): Promise<string> {
31
+ return new Promise((resolve, reject) => {
32
+ const socket = connect({ host, port }, () => socket.write(text));
33
+ socket.once('data', (chunk) => {
34
+ resolve(chunk.toString());
35
+ socket.destroy();
36
+ });
37
+ socket.once('error', reject);
38
+ });
39
+ }
40
+
41
+ describe('localForwarder', () => {
42
+ it('listens on the loopback only and relays each connection to what connect() opens', async () => {
43
+ let opened = 0;
44
+ const tunnel = await localForwarder(async () => {
45
+ opened++;
46
+ return connect({ host: '127.0.0.1', port: echoPort });
47
+ });
48
+ try {
49
+ assert.equal(tunnel.host, '127.0.0.1');
50
+ assert.equal(await roundTrip(tunnel.host, tunnel.port, 'ping'), 'ping');
51
+ assert.equal(await roundTrip(tunnel.host, tunnel.port, 'pong'), 'pong');
52
+ assert.equal(opened, 2);
53
+ } finally {
54
+ await tunnel.close();
55
+ }
56
+ await assert.rejects(
57
+ roundTrip(tunnel.host, tunnel.port, 'late'),
58
+ 'closed: nothing listens any more'
59
+ );
60
+ });
61
+
62
+ it('drops a client whose connection could not be opened, and runs onClose once closed', async () => {
63
+ let closed = false;
64
+ const tunnel = await localForwarder(
65
+ async () => {
66
+ throw new Error('refused by the agent');
67
+ },
68
+ async () => {
69
+ closed = true;
70
+ }
71
+ );
72
+ try {
73
+ await assert.rejects(
74
+ new Promise((resolve, reject) => {
75
+ const socket = connect({ host: tunnel.host, port: tunnel.port });
76
+ socket.once('close', () => reject(new Error('dropped')));
77
+ socket.once('data', resolve);
78
+ })
79
+ );
80
+ } finally {
81
+ await tunnel.close();
82
+ }
83
+ assert.equal(closed, true);
84
+ });
85
+ });
86
+
87
+ describe('openDeviceTunnel', () => {
88
+ it('probes the target through the relay first, so a refusal is said in the relay’s words', async () => {
89
+ const relay: DeviceRelay = async () => {
90
+ throw new Error('L’appareil « Serveur » est hors ligne.');
91
+ };
92
+ await assert.rejects(
93
+ openDeviceTunnel(relay, { host: '127.0.0.1', port: 1 }, 'cette base'),
94
+ {
95
+ message: 'L’appareil « Serveur » est hors ligne.'
96
+ }
97
+ );
98
+ await assert.rejects(openDeviceTunnel(null, { host: '127.0.0.1', port: 1 }, 'cette base'), {
99
+ message: 'Aucun appareil n’est choisi pour joindre cette base.'
100
+ });
101
+ });
102
+
103
+ it('then relays every connection to the target the relay opens', async () => {
104
+ const targets: { host: string; port: number }[] = [];
105
+ const relay: DeviceRelay = async (target) => {
106
+ targets.push(target);
107
+ return connect(target);
108
+ };
109
+ const tunnel = await openDeviceTunnel(
110
+ relay,
111
+ { host: '127.0.0.1', port: echoPort },
112
+ 'cette base'
113
+ );
114
+ try {
115
+ assert.equal(await roundTrip(tunnel.host, tunnel.port, 'hello'), 'hello');
116
+ } finally {
117
+ await tunnel.close();
118
+ }
119
+ // The probe, then the connection.
120
+ assert.equal(targets.length, 2);
121
+ assert.deepEqual(targets[1], { host: '127.0.0.1', port: echoPort });
122
+ });
123
+ });
124
+
125
+ function device(over: Partial<SdkDevice> = {}): SdkDevice {
126
+ return {
127
+ id: 'd1',
128
+ name: 'Serveur',
129
+ online: true,
130
+ report: { agent: { probes: [AGENT_TUNNEL_PROBE], policy: { tunnel: true } } },
131
+ ...over
132
+ } as unknown as SdkDevice;
133
+ }
134
+
135
+ const agents = {
136
+ openTcp: async () => connect({ host: '127.0.0.1', port: echoPort })
137
+ } as unknown as AgentsFacade;
138
+
139
+ describe('relayOf', () => {
140
+ it('refuses an offline device and an agent that predates tunnels, before any connection', () => {
141
+ assert.throws(() => relayOf(agents, device(), false, 'cette base'), {
142
+ message: 'L’appareil « Serveur » est hors ligne.'
143
+ });
144
+ assert.throws(
145
+ () =>
146
+ relayOf(
147
+ agents,
148
+ device({ report: { agent: { probes: [], policy: {} } } } as never),
149
+ true,
150
+ 'cette base'
151
+ ),
152
+ { message: 'L’agent de « Serveur » est à mettre à jour pour joindre cette base.' }
153
+ );
154
+ assert.equal(typeof relayOf(agents, device(), true, 'cette base'), 'function');
155
+ });
156
+ });
157
+
158
+ describe('relayForAuthor', () => {
159
+ type Deps = Pick<FeatureServiceDeps<unknown>, 'access' | 'agents' | 'devices'>;
160
+ const deps = (
161
+ verdict: { ok: true } | { ok: false; reason: 'not_granted' },
162
+ found: SdkDevice | null
163
+ ): Deps =>
164
+ ({
165
+ access: { device: async () => verdict },
166
+ agents,
167
+ devices: { find: async () => found, isOnline: () => true }
168
+ }) as unknown as Deps;
169
+
170
+ it('needs both the device and the member who chose it', async () => {
171
+ await assert.rejects(
172
+ relayForAuthor(deps({ ok: true }, device()), 1, { deviceId: 'd1' }, 'cette base'),
173
+ {
174
+ message: 'Aucun appareil n’est choisi pour joindre cette base.'
175
+ }
176
+ );
177
+ });
178
+
179
+ it('re-checks the author’s right on the device, and says what was lost', async () => {
180
+ await assert.rejects(
181
+ relayForAuthor(
182
+ deps({ ok: false, reason: 'not_granted' }, device()),
183
+ 1,
184
+ { deviceId: 'd1', authorUserId: 7 },
185
+ 'cette base'
186
+ ),
187
+ /la permission lui a été retirée/
188
+ );
189
+ await assert.rejects(
190
+ relayForAuthor(
191
+ deps({ ok: true }, null),
192
+ 1,
193
+ { deviceId: 'd1', authorUserId: 7 },
194
+ 'cette base'
195
+ ),
196
+ { message: 'L’appareil de cette base a été supprimé.' }
197
+ );
198
+ const relay = await relayForAuthor(
199
+ deps({ ok: true }, device()),
200
+ 1,
201
+ { deviceId: 'd1', authorUserId: 7 },
202
+ 'cette base'
203
+ );
204
+ assert.equal(typeof relay, 'function');
205
+ });
206
+ });
@@ -0,0 +1,210 @@
1
+ import { createServer, type AddressInfo, type Server } from 'node:net';
2
+ import type { Duplex } from 'node:stream';
3
+ import { AGENT_TUNNEL_PROBE } from '../protocol/agent';
4
+ import type { DeviceRelayOption } from './deviceRelayOption';
5
+ import {
6
+ FeatureError,
7
+ type AgentsFacade,
8
+ type FeatureServiceDeps,
9
+ type SdkAccessDenial,
10
+ type SdkDevice,
11
+ type SdkFeatureContext
12
+ } from './server';
13
+
14
+ /**
15
+ * Reaching a service through the agent of a device (`agents.openTcp`): a
16
+ * database on the machine's loopback, a Dokploy that only listens on the LAN.
17
+ * The server-side outbound guard does not apply, the device's agent bounds
18
+ * what it reaches (its loopback, plus the operator's `tunnel_targets`).
19
+ *
20
+ * A module stores the chosen device AND the member who chose it: the right to
21
+ * open the device's network is re-checked on that member at every use, so a
22
+ * saved choice is never a permission for good.
23
+ *
24
+ * Every message takes `what`, the thing being reached as a noun phrase with a
25
+ * demonstrative (`'cette base'`, `'cette instance Dokploy'`).
26
+ */
27
+
28
+ /** The Devices permission that opens a machine's network to another feature. */
29
+ export const DEVICE_NETWORK_RIGHT = 'network';
30
+
31
+ /** Why a member may no longer open a device's network, as a clause after "(...)". */
32
+ export const DEVICE_ACCESS_DENIALS: Record<SdkAccessDenial, string> = {
33
+ not_member: 'il n’est plus membre de cet espace',
34
+ suspended: 'son compte est suspendu',
35
+ level: 'son rôle ne le permet plus',
36
+ not_granted: 'la permission lui a été retirée',
37
+ hidden: 'cet appareil lui est fermé',
38
+ read_only: 'cet appareil est en lecture seule pour lui',
39
+ no_device: 'l’appareil n’est plus dans cet espace'
40
+ };
41
+
42
+ /**
43
+ * A connection opened by a device's agent to a host on ITS side. Rights,
44
+ * presence and agent version are checked before one is handed out.
45
+ */
46
+ export type DeviceRelay = (target: { host: string; port: number }) => Promise<Duplex>;
47
+
48
+ /** A local listener standing for the remote host, and how to close it. */
49
+ export interface LocalTunnel {
50
+ /** Always the loopback: what a driver or an HTTP client connects to. */
51
+ host: string;
52
+ port: number;
53
+ close: () => Promise<void>;
54
+ }
55
+
56
+ /** The device saved on an item, with the member who chose it. */
57
+ export interface SavedDeviceChoice {
58
+ deviceId?: string | null;
59
+ authorUserId?: number | null;
60
+ }
61
+
62
+ /** The chosen device, if the caller may open its network; a `validation` error when none is chosen. */
63
+ export async function authorizeRelayDevice(
64
+ ctx: SdkFeatureContext<unknown>,
65
+ deviceId: string | null,
66
+ what: string
67
+ ): Promise<SdkDevice> {
68
+ if (!deviceId) {
69
+ throw new FeatureError('validation', `Choisissez l’appareil par lequel joindre ${what}.`);
70
+ }
71
+ return ctx.deveye.devices.authorize(deviceId, { extras: [DEVICE_NETWORK_RIGHT] });
72
+ }
73
+
74
+ /**
75
+ * The workspace's devices, each with what keeps the caller from choosing it
76
+ * (right, agent version, machine policy). A device one cannot choose stays
77
+ * listed: that is how one learns why.
78
+ */
79
+ export async function relayDeviceOptions(
80
+ ctx: SdkFeatureContext<unknown>,
81
+ what: string
82
+ ): Promise<DeviceRelayOption[]> {
83
+ const devices = await ctx.deveye.devices.list();
84
+ return Promise.all(
85
+ devices.map(async (device): Promise<DeviceRelayOption> => {
86
+ const allowed = await ctx.deveye.devices
87
+ .authorize(device.id, { extras: [DEVICE_NETWORK_RIGHT] })
88
+ .then(
89
+ () => true,
90
+ () => false
91
+ );
92
+ const agent = device.report?.agent;
93
+ const blocked = !allowed
94
+ ? 'Vous n’avez pas le droit « Accès au réseau de l’appareil » sur cet appareil.'
95
+ : !agent?.probes.includes(AGENT_TUNNEL_PROBE)
96
+ ? `Son agent est à mettre à jour pour joindre ${what}.`
97
+ : !agent.policy.tunnel
98
+ ? 'La machine refuse les tunnels : allow_tunnel = false dans la configuration de son agent.'
99
+ : null;
100
+ return { id: device.id, name: device.name, online: device.online, blocked };
101
+ })
102
+ );
103
+ }
104
+
105
+ /** A device's relay, after what is better said before trying: offline, agent too old. */
106
+ export function relayOf(
107
+ agents: AgentsFacade,
108
+ device: SdkDevice,
109
+ online: boolean,
110
+ what: string
111
+ ): DeviceRelay {
112
+ if (!online) throw new Error(`L’appareil « ${device.name} » est hors ligne.`);
113
+ if (!device.report?.agent?.probes.includes(AGENT_TUNNEL_PROBE)) {
114
+ throw new Error(`L’agent de « ${device.name} » est à mettre à jour pour joindre ${what}.`);
115
+ }
116
+ return (target) => agents.openTcp(device.id, target);
117
+ }
118
+
119
+ /**
120
+ * The relay of a saved choice, for work without a session (a background job):
121
+ * valid as long as the member who chose the device still holds the right to
122
+ * open its network. Throws a readable message otherwise.
123
+ */
124
+ export async function relayForAuthor(
125
+ deps: Pick<FeatureServiceDeps<unknown>, 'access' | 'agents' | 'devices'>,
126
+ workspaceId: number,
127
+ saved: SavedDeviceChoice,
128
+ what: string
129
+ ): Promise<DeviceRelay> {
130
+ if (!saved.deviceId || !saved.authorUserId) {
131
+ throw new Error(`Aucun appareil n’est choisi pour joindre ${what}.`);
132
+ }
133
+ const may = await deps.access.device(workspaceId, saved.authorUserId, saved.deviceId, [
134
+ DEVICE_NETWORK_RIGHT
135
+ ]);
136
+ if (!may.ok) {
137
+ throw new Error(
138
+ `Le membre qui a choisi l’appareil de ${what} ne peut plus en ouvrir le réseau (${DEVICE_ACCESS_DENIALS[may.reason]}) : ` +
139
+ 'un membre qui en a le droit doit enregistrer l’accès de nouveau.'
140
+ );
141
+ }
142
+ const device = await deps.devices.find(saved.deviceId);
143
+ if (!device) throw new Error(`L’appareil de ${what} a été supprimé.`);
144
+ return relayOf(deps.agents, device, deps.devices.isOnline(device.id), what);
145
+ }
146
+
147
+ /**
148
+ * A local listener that hands every incoming connection to `connect`. For a
149
+ * client that only connects to a host (`pg`, `pg_dump`, an HTTP agent). An
150
+ * error on an established connection only drops that one, never the process.
151
+ * Always close it in a `finally`: forgotten, it leaves a listener behind.
152
+ */
153
+ export async function localForwarder(
154
+ connect: () => Promise<Duplex>,
155
+ onClose: () => Promise<void> = async () => {}
156
+ ): Promise<LocalTunnel> {
157
+ const server: Server = createServer((client) => {
158
+ void (async () => {
159
+ try {
160
+ const remote = await connect();
161
+ client.pipe(remote);
162
+ remote.pipe(client);
163
+ const drop = () => {
164
+ client.destroy();
165
+ remote.destroy();
166
+ };
167
+ client.on('error', drop);
168
+ remote.on('error', drop);
169
+ remote.on('close', () => client.destroy());
170
+ } catch {
171
+ client.destroy();
172
+ }
173
+ })();
174
+ });
175
+
176
+ await new Promise<void>((resolve, reject) => {
177
+ server.once('error', reject);
178
+ // `127.0.0.1`, never `0.0.0.0`: exposed, this listener would open the
179
+ // remote service to anyone, unauthenticated.
180
+ server.listen(0, '127.0.0.1', () => resolve());
181
+ });
182
+
183
+ const address = server.address() as AddressInfo;
184
+ return {
185
+ host: '127.0.0.1',
186
+ port: address.port,
187
+ close: async () => {
188
+ await new Promise<void>((resolve) => server.close(() => resolve()));
189
+ await onClose();
190
+ }
191
+ };
192
+ }
193
+
194
+ /**
195
+ * A local listener that reaches `target` through the device. One connection is
196
+ * opened right away: a refused or unreachable target is said here, in the
197
+ * agent's words, where a client behind the forwarder would only see a dropped
198
+ * connection.
199
+ */
200
+ export async function openDeviceTunnel(
201
+ relay: DeviceRelay | null,
202
+ target: { host: string; port: number },
203
+ what: string
204
+ ): Promise<LocalTunnel> {
205
+ if (!relay) throw new Error(`Aucun appareil n’est choisi pour joindre ${what}.`);
206
+ const connect = () => relay(target);
207
+ const probe = await connect();
208
+ probe.destroy();
209
+ return localForwarder(connect);
210
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A device as a module's form offers it for reaching a service through its
3
+ * agent (`@deveye/types/sdk/server`'s `relayDeviceOptions`). The pure half,
4
+ * shared by the command that lists them and the field that shows them.
5
+ */
6
+ import { z } from 'zod';
7
+
8
+ /**
9
+ * `blocked` says what keeps the caller from choosing this device (right,
10
+ * agent version, machine policy); a device one cannot choose stays listed,
11
+ * that is how one learns why.
12
+ */
13
+ export const deviceRelayOptionSchema = z.object({
14
+ id: z.uuid(),
15
+ name: z.string(),
16
+ online: z.boolean(),
17
+ blocked: z.string().nullable()
18
+ });
19
+ export type DeviceRelayOption = z.infer<typeof deviceRelayOptionSchema>;
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 './deviceRelayOption';
9
10
  export * from './ids';
10
11
  export * from './manifest';
11
12
  export * from './pageLook';
package/src/sdk/server.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Duplex } from 'node:stream';
1
2
  import type { FeatureAccountExport } from './accountExport';
2
3
  import type { ItemTree, ItemTreeRows } from './copy';
3
4
  import type { z, ZodType } from 'zod';
@@ -46,6 +47,19 @@ export {
46
47
  type SafeFetchOptions
47
48
  } from './net';
48
49
  export { mapLimit } from './pool';
50
+ export {
51
+ authorizeRelayDevice,
52
+ DEVICE_ACCESS_DENIALS,
53
+ DEVICE_NETWORK_RIGHT,
54
+ localForwarder,
55
+ openDeviceTunnel,
56
+ relayDeviceOptions,
57
+ relayForAuthor,
58
+ relayOf,
59
+ type DeviceRelay,
60
+ type LocalTunnel,
61
+ type SavedDeviceChoice
62
+ } from './deviceRelay';
49
63
  export {
50
64
  defineModuleEnv,
51
65
  MODULE_ENV_NAME_PATTERN,
@@ -655,6 +669,19 @@ export interface AgentsFacade {
655
669
  request: AgentFolderArchiveRequest,
656
670
  options?: { signal?: AbortSignal }
657
671
  ): AgentFolderArchive;
672
+ /**
673
+ * A TCP connection opened BY THE DEVICE to `host:port` and relayed by its
674
+ * agent: a service only the machine can reach (a database on its
675
+ * loopback) becomes a stream here, read at the consumer's pace. The agent
676
+ * only reaches its own loopback, plus the hosts its operator lists in
677
+ * `tunnel_targets`, and refuses everything under `allow_tunnel = false`.
678
+ * Rejects with the reason (offline, refused, unreachable, an agent that
679
+ * predates the order: check `report.agent.probes` for
680
+ * `AGENT_TUNNEL_PROBE` first to say so plainly). Once open, the stream is
681
+ * destroyed with an error when the device goes offline; ending or
682
+ * destroying it closes the connection on the machine.
683
+ */
684
+ openTcp(deviceId: string, target: { host: string; port: number }): Promise<Duplex>;
658
685
  /**
659
686
  * Bytes queued on the agent's socket, not yet on the wire. A sender that
660
687
  * streams towards an agent must watch it: the socket accepts everything,
@@ -242,6 +242,7 @@ interface TestAgents {
242
242
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
243
243
  /** By device id. A device without an entry answers nothing: its stream throws. */
244
244
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
245
+ openTcp?: DevEyeFacade['agents']['openTcp'];
245
246
  /** The plan `metricIntervals` applies. Default paid. */
246
247
  paid?: boolean;
247
248
  }
@@ -334,6 +335,12 @@ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevE
334
335
  recorded.agentRequests.push({ method: 'archiveFolder', deviceId });
335
336
  recorded.archiveRequests.push({ deviceId, ...request });
336
337
  return replayedArchive(docker.archives?.[deviceId]);
338
+ },
339
+ openTcp(deviceId, target) {
340
+ recorded.agentRequests.push({ method: 'openTcp', deviceId });
341
+ return docker.openTcp
342
+ ? docker.openTcp(deviceId, target)
343
+ : Promise.reject(new Error('La machine n’est pas connectée.'));
337
344
  }
338
345
  };
339
346
  }
@@ -481,6 +488,8 @@ export interface TestContextOverrides<Repo> {
481
488
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
482
489
  /** What `deveye.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
483
490
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
491
+ /** What `deveye.agents.openTcp` resolves. Default a rejection, as for an offline device. */
492
+ openTcp?: DevEyeFacade['agents']['openTcp'];
484
493
  /** Instants `deveye.telemetry.snapshot` answers (matched within a second). Default none. */
485
494
  snapshots?: readonly SdkTelemetrySnapshot[];
486
495
  /** Override facade members entirely when the defaults are not enough. */
@@ -758,6 +767,8 @@ export interface TestServiceOverrides<Repo> {
758
767
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
759
768
  /** What `deps.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
760
769
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
770
+ /** What `deps.agents.openTcp` resolves. Default a rejection, as for an offline device. */
771
+ openTcp?: DevEyeFacade['agents']['openTcp'];
761
772
  /** What `deps.access` answers. Default: every member holds every right. */
762
773
  access?: Partial<FeatureServiceDeps['access']>;
763
774
  /** The accounts `deps.accounts` knows, and `deps.accountMail` writes to. Default none. */