@domicile-desktop/system-network 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ // NetworkManager's Wi-Fi device over the system bus: its networks and
2
+ // connection, kept current, and the requests that change them. See
3
+ // docs/SHELL-SYSTEM-ACCESS.md.
4
+ import { None, Ok, Result, Some } from "@cprussin/option-result";
5
+ import { Bus } from "@domicile-desktop/sdk/system";
6
+ import { z } from "zod";
7
+ import { followBus } from "./follow";
8
+ import { variant } from "./variant";
9
+ import { WifiBackend } from "./wifi-state";
10
+ const SERVICE = "org.freedesktop.NetworkManager";
11
+ const ROOT = "/org/freedesktop/NetworkManager";
12
+ const DEVICE = `${SERVICE}.Device`;
13
+ const WIRELESS = `${SERVICE}.Device.Wireless`;
14
+ /** The object path NetworkManager uses for "none". */
15
+ const NO_OBJECT = "/";
16
+ /** `NM_DEVICE_TYPE_WIFI`. */
17
+ const WIFI_DEVICE = 2;
18
+ /**
19
+ * Calls `onWifi` with the first Wi-Fi device now and after each change, and
20
+ * returns a function that stops watching. `None` is a machine without one.
21
+ *
22
+ * An `Err` is a D-Bus failure, such as NetworkManager not running. The watch
23
+ * keeps listening after one, so a later change reads again.
24
+ */
25
+ export const watchNetworkManagerWifi = (domicile, onWifi) => followBus(domicile, { bus: Bus.System, sender: SERVICE }, () => read(domicile), onWifi);
26
+ /** Turn the Wi-Fi radio on or off. */
27
+ export const setNetworkManagerWifiEnabled = async (domicile, _wifi, enabled) => done(await domicile.dbus.call(request(ROOT, "org.freedesktop.DBus.Properties", "Set", "ssv", [
28
+ SERVICE,
29
+ "WirelessEnabled",
30
+ { signature: "b", value: enabled },
31
+ ])));
32
+ /** Ask for a scan. Networks it finds arrive as changes. */
33
+ export const scanNetworkManagerWifi = async (domicile, wifi) => done(await domicile.dbus.call(request(wifi.device, WIRELESS, "RequestScan", "a{sv}", [{}])));
34
+ /**
35
+ * Join `network`: through its saved profile if it has one, or with a new
36
+ * profile, which needs `passphrase` when the network is secured.
37
+ */
38
+ export const connectNetworkManagerWifi = async (domicile, wifi, network, passphrase) => done(await domicile.dbus.call(network.profile === undefined
39
+ ? request(ROOT, SERVICE, "AddAndActivateConnection", "a{sa{sv}}oo", [
40
+ newProfile(network, passphrase),
41
+ wifi.device,
42
+ network.path,
43
+ ])
44
+ : request(ROOT, SERVICE, "ActivateConnection", "ooo", [
45
+ network.profile,
46
+ wifi.device,
47
+ network.path,
48
+ ])));
49
+ /** Leave the current network, until asked to join one. */
50
+ export const disconnectNetworkManagerWifi = async (domicile, wifi) => done(await domicile.dbus.call({
51
+ bus: Bus.System,
52
+ destination: SERVICE,
53
+ interface: DEVICE,
54
+ member: "Disconnect",
55
+ path: wifi.device,
56
+ }));
57
+ const request = (path, iface, member, signature, body) => ({
58
+ body,
59
+ bus: Bus.System,
60
+ destination: SERVICE,
61
+ interface: iface,
62
+ member,
63
+ path,
64
+ signature,
65
+ });
66
+ const done = (reply) => reply.map(() => "done");
67
+ /** The settings NetworkManager fills in a profile from, past the access point. */
68
+ const newProfile = (network, passphrase) => {
69
+ if (!network.secured) {
70
+ return {};
71
+ }
72
+ else if (passphrase === undefined) {
73
+ throw new Error(`joining ${network.ssid} needs a passphrase`);
74
+ }
75
+ else {
76
+ return {
77
+ "802-11-wireless-security": {
78
+ "key-mgmt": { signature: "s", value: "wpa-psk" },
79
+ psk: { signature: "s", value: passphrase },
80
+ },
81
+ };
82
+ }
83
+ };
84
+ /**
85
+ * Read Wi-Fi. A property change on an object read for it matters, as does an
86
+ * access point or a device coming or going.
87
+ */
88
+ const read = async (domicile) => {
89
+ const paths = new Set([ROOT]);
90
+ const value = await readWifi(domicile, paths);
91
+ return { matters: (signal) => matters(paths, signal), value };
92
+ };
93
+ const matters = (paths, signal) => {
94
+ switch (signal.member) {
95
+ case "AccessPointAdded":
96
+ case "AccessPointRemoved":
97
+ case "DeviceAdded":
98
+ case "DeviceRemoved": {
99
+ return true;
100
+ }
101
+ case "PropertiesChanged": {
102
+ return (signal.interface === "org.freedesktop.DBus.Properties" &&
103
+ paths.has(signal.path));
104
+ }
105
+ default: {
106
+ return false;
107
+ }
108
+ }
109
+ };
110
+ /** Read Wi-Fi, adding each object read to `paths`. */
111
+ const readWifi = async (domicile, paths) => (await properties(domicile, ROOT, SERVICE, rootSchema)).andThenAsync(async ({ WirelessEnabled: enabled }) => (await call(domicile, ROOT, SERVICE, "GetDevices")).andThenAsync(async ({ body }) => {
112
+ const listed = devicesSchema.parse(body)[0];
113
+ for (const path of listed) {
114
+ paths.add(path);
115
+ }
116
+ const devices = Result.collect(await Promise.all(listed.map(async (path) => (await properties(domicile, path, DEVICE, deviceSchema)).map((device) => ({ device, path })))));
117
+ return devices.andThenAsync(async (read) => {
118
+ const found = read.find(({ device }) => device.DeviceType === WIFI_DEVICE);
119
+ return found === undefined
120
+ ? Ok(None())
121
+ : (await wifiOf(domicile, paths, found.path, found.device, enabled)).map((wifi) => Some(wifi));
122
+ });
123
+ }));
124
+ /** The Wi-Fi device at `path`. */
125
+ const wifiOf = async (domicile, paths, path, device, enabled) => (await properties(domicile, path, WIRELESS, wirelessSchema)).andThenAsync(async (radio) => {
126
+ for (const point of radio.AccessPoints) {
127
+ paths.add(point);
128
+ }
129
+ paths.add(device.Ip4Config);
130
+ const [points, profiles, ip] = await Promise.all([
131
+ accessPoints(domicile, radio.AccessPoints),
132
+ savedProfiles(domicile, device.AvailableConnections),
133
+ radio.ActiveAccessPoint === NO_OBJECT || device.Ip4Config === NO_OBJECT
134
+ ? Promise.resolve(Ok(None()))
135
+ : ipOf(domicile, device.Ip4Config),
136
+ ]);
137
+ return points.andThen((read) => profiles.andThen((saved) => ip.map((address) => ({
138
+ backend: WifiBackend.NetworkManager,
139
+ connection: connectionOf(read, radio, address),
140
+ device: path,
141
+ enabled,
142
+ hardwareAddress: device.HwAddress,
143
+ interface: device.Interface,
144
+ networks: networksOf(read, saved, radio.ActiveAccessPoint),
145
+ scanning: false,
146
+ }))));
147
+ });
148
+ const accessPoints = async (domicile, listed) => Result.collect(await Promise.all(listed.map(async (path) => (await properties(domicile, path, `${SERVICE}.AccessPoint`, accessPointSchema)).map((point) => ({ ...point, path })))));
149
+ /** Each saved Wi-Fi profile's path, by its network's name. */
150
+ const savedProfiles = async (domicile, listed) => Result.collect(await Promise.all(listed.map(async (path) => (await call(domicile, path, `${SERVICE}.Settings.Connection`, "GetSettings")).map(({ body }) => ({
151
+ path,
152
+ settings: settingsSchema.parse(body)[0],
153
+ }))))).map((saved) => new Map(saved.flatMap(({ path, settings }) => {
154
+ const ssid = settings["802-11-wireless"]?.ssid;
155
+ return ssid === undefined ? [] : [[ssid, path]];
156
+ })));
157
+ const ipOf = async (domicile, path) => (await properties(domicile, path, `${SERVICE}.IP4Config`, ip4Schema)).map((config) => Some({
158
+ addresses: config.AddressData.map(({ address, prefix }) => `${address}/${prefix}`),
159
+ dns: config.NameserverData.map(({ address }) => address),
160
+ gateway: config.Gateway === "" ? undefined : config.Gateway,
161
+ }));
162
+ /** The named networks, one per name: its strongest access point. */
163
+ const networksOf = (points, profiles, active) => {
164
+ const byName = new Map();
165
+ for (const point of points.filter(({ Ssid }) => Ssid !== "")) {
166
+ byName.set(point.Ssid, [...(byName.get(point.Ssid) ?? []), point]);
167
+ }
168
+ return [...byName.values()]
169
+ .map((named) => {
170
+ const [strongest] = named.toSorted((a, b) => b.Strength - a.Strength);
171
+ if (strongest === undefined) {
172
+ throw new Error("a network with no access point");
173
+ }
174
+ else {
175
+ return {
176
+ connected: named.some(({ path }) => path === active),
177
+ path: strongest.path,
178
+ profile: profiles.get(strongest.Ssid),
179
+ secured: isSecured(strongest),
180
+ ssid: strongest.Ssid,
181
+ strength: strongest.Strength / 100,
182
+ };
183
+ }
184
+ })
185
+ .toSorted((a, b) => b.strength - a.strength);
186
+ };
187
+ const connectionOf = (points, radio, ip) => {
188
+ const active = points.find(({ path }) => path === radio.ActiveAccessPoint);
189
+ return active === undefined
190
+ ? undefined
191
+ : {
192
+ bitrate: radio.Bitrate / 1000,
193
+ frequency: active.Frequency,
194
+ ip: ip.match({ None: () => undefined, Some: (address) => address }),
195
+ ssid: active.Ssid,
196
+ strength: active.Strength / 100,
197
+ };
198
+ };
199
+ /** `NM_802_11_AP_FLAGS_PRIVACY`, or any WPA or RSN flag. */
200
+ const isSecured = (point) => (point.Flags & 1) !== 0 || point.WpaFlags !== 0 || point.RsnFlags !== 0;
201
+ const call = (domicile, path, iface, member) => domicile.dbus.call({
202
+ bus: Bus.System,
203
+ destination: SERVICE,
204
+ interface: iface,
205
+ member,
206
+ path,
207
+ });
208
+ /** `Properties.GetAll` on one of NetworkManager's objects, parsed. */
209
+ const properties = async (domicile, path, interfaceName, schema) => (await domicile.dbus.call({
210
+ body: [interfaceName],
211
+ bus: Bus.System,
212
+ destination: SERVICE,
213
+ interface: "org.freedesktop.DBus.Properties",
214
+ member: "GetAll",
215
+ path,
216
+ signature: "s",
217
+ })).map(({ body }) => z.tuple([schema]).parse(body)[0]);
218
+ /** An SSID's bytes, as text. */
219
+ const ssid = z
220
+ .array(z.number())
221
+ .transform((bytes) => new TextDecoder().decode(new Uint8Array(bytes)));
222
+ const rootSchema = z.object({ WirelessEnabled: variant(z.boolean()) });
223
+ const devicesSchema = z.tuple([z.array(z.string())]);
224
+ const deviceSchema = z.object({
225
+ AvailableConnections: variant(z.array(z.string())),
226
+ DeviceType: variant(z.number()),
227
+ HwAddress: variant(z.string()),
228
+ Interface: variant(z.string()),
229
+ Ip4Config: variant(z.string()),
230
+ });
231
+ const wirelessSchema = z.object({
232
+ AccessPoints: variant(z.array(z.string())),
233
+ ActiveAccessPoint: variant(z.string()),
234
+ /** In kbit/s. */
235
+ Bitrate: variant(z.number()),
236
+ });
237
+ const accessPointSchema = z.object({
238
+ Flags: variant(z.number()),
239
+ Frequency: variant(z.number()),
240
+ RsnFlags: variant(z.number()),
241
+ Ssid: variant(ssid),
242
+ Strength: variant(z.number()),
243
+ WpaFlags: variant(z.number()),
244
+ });
245
+ const settingsSchema = z.tuple([
246
+ z.object({
247
+ "802-11-wireless": z.object({ ssid: variant(ssid).optional() }).optional(),
248
+ }),
249
+ ]);
250
+ const ip4Schema = z.object({
251
+ AddressData: variant(z.array(z.object({
252
+ address: variant(z.string()),
253
+ prefix: variant(z.number()),
254
+ }))),
255
+ Gateway: variant(z.string()),
256
+ NameserverData: variant(z.array(z.object({ address: variant(z.string()) }))),
257
+ });
@@ -0,0 +1,11 @@
1
+ import type { Result } from "@cprussin/option-result";
2
+ import type { SystemError } from "@domicile-desktop/sdk/system";
3
+ import type { Network, NetworkDesktop } from "./network-state";
4
+ /**
5
+ * Calls `onNetwork` with NetworkManager's network now and after each change,
6
+ * and returns a function that stops watching.
7
+ *
8
+ * An `Err` is a D-Bus failure, such as NetworkManager not running. The watch
9
+ * keeps listening after one, so a later change reads again.
10
+ */
11
+ export declare const watchNetworkManager: (domicile: NetworkDesktop, onNetwork: (network: Result<Network, SystemError>) => void) => (() => void);
@@ -0,0 +1,126 @@
1
+ // NetworkManager over the system bus: connectivity and the primary
2
+ // connection, kept current. See docs/SHELL-SYSTEM-ACCESS.md.
3
+ import { Err, Ok } from "@cprussin/option-result";
4
+ import { Bus } from "@domicile-desktop/sdk/system";
5
+ import { z } from "zod";
6
+ import { followBus } from "./follow";
7
+ import { Connectivity, Link } from "./network-state";
8
+ import { variant } from "./variant";
9
+ const SERVICE = "org.freedesktop.NetworkManager";
10
+ const ROOT = "/org/freedesktop/NetworkManager";
11
+ /** The object path NetworkManager uses for "none". */
12
+ const NO_OBJECT = "/";
13
+ /**
14
+ * Calls `onNetwork` with NetworkManager's network now and after each change,
15
+ * and returns a function that stops watching.
16
+ *
17
+ * An `Err` is a D-Bus failure, such as NetworkManager not running. The watch
18
+ * keeps listening after one, so a later change reads again.
19
+ */
20
+ export const watchNetworkManager = (domicile, onNetwork) => followBus(domicile, {
21
+ bus: Bus.System,
22
+ interface: "org.freedesktop.DBus.Properties",
23
+ member: "PropertiesChanged",
24
+ sender: SERVICE,
25
+ }, () => read(domicile), onNetwork);
26
+ /** Read the network; a change to any object read for it matters. */
27
+ const read = async (domicile) => {
28
+ const root = await properties(domicile, ROOT, SERVICE, rootSchema);
29
+ return root.match({
30
+ Err: (error) => Promise.resolve({
31
+ matters: ({ path }) => path === ROOT,
32
+ value: Err(error),
33
+ }),
34
+ Ok: async ({ Connectivity: connectivity, PrimaryConnection: primary }) => {
35
+ const link = await linkOf(domicile, primary);
36
+ const paths = new Set([ROOT, ...link.paths]);
37
+ return {
38
+ matters: ({ path }) => paths.has(path),
39
+ value: link.result.map((found) => ({
40
+ connectivity,
41
+ link: found,
42
+ })),
43
+ };
44
+ },
45
+ });
46
+ };
47
+ /** The primary connection at `path`. */
48
+ const linkOf = async (domicile, path) => {
49
+ if (path === NO_OBJECT) {
50
+ return { paths: [], result: Ok(Link.None()) };
51
+ }
52
+ else {
53
+ const active = await properties(domicile, path, `${SERVICE}.Connection.Active`, activeSchema);
54
+ return active.match({
55
+ Err: (error) => Promise.resolve({ paths: [path], result: Err(error) }),
56
+ Ok: async ({ Id: name, SpecificObject: specific, Type: type, }) => {
57
+ switch (type) {
58
+ case "802-11-wireless": {
59
+ const point = await properties(domicile, specific, `${SERVICE}.AccessPoint`, accessPointSchema);
60
+ return {
61
+ paths: [path, specific],
62
+ result: point.map(({ Ssid: ssid, Strength: strength }) => Link.Wifi(new TextDecoder().decode(new Uint8Array(ssid)), strength / 100)),
63
+ };
64
+ }
65
+ case "802-3-ethernet": {
66
+ return { paths: [path], result: Ok(Link.Wired(name)) };
67
+ }
68
+ default: {
69
+ return { paths: [path], result: Ok(Link.Other(name)) };
70
+ }
71
+ }
72
+ },
73
+ });
74
+ }
75
+ };
76
+ /** `Properties.GetAll` on one of NetworkManager's objects, parsed. */
77
+ const properties = async (domicile, path, interfaceName, schema) => (await domicile.dbus.call({
78
+ body: [interfaceName],
79
+ bus: Bus.System,
80
+ destination: SERVICE,
81
+ interface: "org.freedesktop.DBus.Properties",
82
+ member: "GetAll",
83
+ path,
84
+ signature: "s",
85
+ })).map(({ body }) => z.tuple([schema]).parse(body)[0]);
86
+ /** NetworkManager's `NMConnectivityState`. */
87
+ const connectivityOf = (value) => {
88
+ switch (value) {
89
+ case 0: {
90
+ return Connectivity.Unknown;
91
+ }
92
+ case 1: {
93
+ return Connectivity.None;
94
+ }
95
+ case 2: {
96
+ return Connectivity.Portal;
97
+ }
98
+ case 3: {
99
+ return Connectivity.Limited;
100
+ }
101
+ case 4: {
102
+ return Connectivity.Full;
103
+ }
104
+ }
105
+ };
106
+ const rootSchema = z.object({
107
+ Connectivity: variant(z
108
+ .union([
109
+ z.literal(0),
110
+ z.literal(1),
111
+ z.literal(2),
112
+ z.literal(3),
113
+ z.literal(4),
114
+ ])
115
+ .transform(connectivityOf)),
116
+ PrimaryConnection: variant(z.string()),
117
+ });
118
+ const activeSchema = z.object({
119
+ Id: variant(z.string()),
120
+ SpecificObject: variant(z.string()),
121
+ Type: variant(z.string()),
122
+ });
123
+ const accessPointSchema = z.object({
124
+ Ssid: variant(z.array(z.number())),
125
+ Strength: variant(z.number()),
126
+ });
@@ -0,0 +1,15 @@
1
+ import type { Option, Result } from "@cprussin/option-result";
2
+ import type { Processes } from "@domicile-desktop/sdk/desktop/processes";
3
+ import type { SystemError } from "@domicile-desktop/sdk/system";
4
+ /** Chrome's portal probe: `204 No Content` on the open internet. Plain http, so a portal can intercept it. */
5
+ export declare const PORTAL_PROBE = "http://www.gstatic.com/generate_204";
6
+ /**
7
+ * Where to sign in to the network's captive portal, or `None` when there is
8
+ * none.
9
+ *
10
+ * Retries a probe that gets no answer, since an address or a route can arrive
11
+ * a moment after the network does. An `Err` is a probe that never got one.
12
+ */
13
+ export declare const checkPortal: (domicile: {
14
+ readonly processes: Pick<Processes, "run">;
15
+ }) => Promise<Result<Option<string>, SystemError>>;
package/dist/portal.js ADDED
@@ -0,0 +1,47 @@
1
+ // Whether a captive portal holds the network, found by asking for a page that
2
+ // the open internet answers with nothing. A portal answers it with its sign-in
3
+ // page or a redirect to one. iwd and wpa_supplicant report no portal, so the
4
+ // check runs `curl` rather than asking the network service.
5
+ import { Err, None, Ok, Some } from "@cprussin/option-result";
6
+ import { SystemErrorKind } from "@domicile-desktop/sdk/system";
7
+ /** Chrome's portal probe: `204 No Content` on the open internet. Plain http, so a portal can intercept it. */
8
+ export const PORTAL_PROBE = "http://www.gstatic.com/generate_204";
9
+ /** Seconds each try may take, and how many more tries follow a failed one. */
10
+ const PATIENCE = "5";
11
+ const RETRIES = "3";
12
+ /**
13
+ * Where to sign in to the network's captive portal, or `None` when there is
14
+ * none.
15
+ *
16
+ * Retries a probe that gets no answer, since an address or a route can arrive
17
+ * a moment after the network does. An `Err` is a probe that never got one.
18
+ */
19
+ export const checkPortal = async (domicile) => (await domicile.processes.run([
20
+ "curl",
21
+ "--silent",
22
+ "--output",
23
+ "/dev/null",
24
+ "--max-time",
25
+ PATIENCE,
26
+ "--retry",
27
+ RETRIES,
28
+ "--retry-all-errors",
29
+ "--write-out",
30
+ "%{http_code} %{redirect_url}",
31
+ PORTAL_PROBE,
32
+ ])).andThen(({ code, stdout }) => code === 0
33
+ ? Ok(signInOf(stdout))
34
+ : Err({
35
+ kind: SystemErrorKind.Other,
36
+ message: `curl exited ${String(code)} asking for the portal probe`,
37
+ }));
38
+ /** The sign-in address in curl's `<status> <redirect>`, or `None` for `204`. */
39
+ const signInOf = (written) => {
40
+ const [status, redirect = ""] = written.split(" ");
41
+ if (status === "204") {
42
+ return None();
43
+ }
44
+ else {
45
+ return Some(redirect === "" ? PORTAL_PROBE : redirect);
46
+ }
47
+ };
@@ -0,0 +1,30 @@
1
+ import type { Option, Result } from "@cprussin/option-result";
2
+ import type { SharedWatch } from "@domicile-desktop/react/shared-watch";
3
+ import type { Domicile } from "@domicile-desktop/sdk/desktop/desktop";
4
+ import type { SystemError } from "@domicile-desktop/sdk/system";
5
+ import type { Addressing, NetworkInterface } from "./interfaces";
6
+ import type { Network } from "./network-state";
7
+ import type { Wifi } from "./wifi-state";
8
+ export type DeskNetwork = {
9
+ network: SharedWatch<Result<Network, SystemError>>;
10
+ /** The network hardware. */
11
+ interfaces: SharedWatch<Result<NetworkInterface[], SystemError>>;
12
+ /** Each interface's addresses, by name. */
13
+ addresses: SharedWatch<Result<Map<string, Addressing>, SystemError>>;
14
+ /** The Wi-Fi device; `None` without one. */
15
+ wifi: SharedWatch<Result<Option<Wifi>, SystemError>>;
16
+ };
17
+ /**
18
+ * The network service and hardware, watched once per desktop. The calls that
19
+ * reach past `/sys` are refused while the desktop is locked, so those watches
20
+ * start again on unlock.
21
+ */
22
+ export declare const deskNetwork: (domicile: Domicile) => DeskNetwork;
23
+ /** NetworkManager's state, or `undefined` before it says. */
24
+ export declare const useNetwork: () => Result<Network, SystemError> | undefined;
25
+ /** The network hardware, or `undefined` before it was read. */
26
+ export declare const useNetworkInterfaces: () => Result<NetworkInterface[], SystemError> | undefined;
27
+ /** Each interface's addresses by name, or `undefined` before they were read. */
28
+ export declare const useAddresses: () => Result<Map<string, Addressing>, SystemError> | undefined;
29
+ /** The Wi-Fi device (`None` without one), or `undefined` before it was read. */
30
+ export declare const useWifi: () => Result<Option<Wifi>, SystemError> | undefined;
package/dist/react.js ADDED
@@ -0,0 +1,29 @@
1
+ // The network for a React shell: one watch per desktop, however many parts
2
+ // read it.
3
+ import { perDesktop } from "@domicile-desktop/react/per-desktop";
4
+ import { sharedWatch } from "@domicile-desktop/react/shared-watch";
5
+ import { useDeskWatch } from "@domicile-desktop/react/use-shared-watch";
6
+ import { watchAcrossLocks } from "./across-locks";
7
+ import { watchAddresses, watchInterfaces } from "./interfaces";
8
+ import { watchNetwork } from "./network";
9
+ import { watchWifi } from "./wifi";
10
+ /**
11
+ * The network service and hardware, watched once per desktop. The calls that
12
+ * reach past `/sys` are refused while the desktop is locked, so those watches
13
+ * start again on unlock.
14
+ */
15
+ export const deskNetwork = perDesktop((domicile) => ({
16
+ addresses: sharedWatch(watchAcrossLocks(domicile, (onAddresses) => watchAddresses(domicile, onAddresses))),
17
+ interfaces: sharedWatch((onInterfaces) => watchInterfaces(domicile, onInterfaces)),
18
+ network: sharedWatch(watchAcrossLocks(domicile, (onNetwork) => watchNetwork(domicile, onNetwork))),
19
+ wifi: sharedWatch(watchAcrossLocks(domicile, (onWifi) => watchWifi(domicile, onWifi))),
20
+ }));
21
+ const part = (key) => (domicile) => deskNetwork(domicile)[key];
22
+ /** NetworkManager's state, or `undefined` before it says. */
23
+ export const useNetwork = () => useDeskWatch(part("network"));
24
+ /** The network hardware, or `undefined` before it was read. */
25
+ export const useNetworkInterfaces = () => useDeskWatch(part("interfaces"));
26
+ /** Each interface's addresses by name, or `undefined` before they were read. */
27
+ export const useAddresses = () => useDeskWatch(part("addresses"));
28
+ /** The Wi-Fi device (`None` without one), or `undefined` before it was read. */
29
+ export const useWifi = () => useDeskWatch(part("wifi"));
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A Wi-Fi signal in dBm as 0 through 1, graded as NetworkManager grades it:
3
+ * -100 dBm or weaker is 0, -40 dBm or stronger is 1.
4
+ */
5
+ export declare const strengthOfDbm: (dbm: number) => number;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A Wi-Fi signal in dBm as 0 through 1, graded as NetworkManager grades it:
3
+ * -100 dBm or weaker is 0, -40 dBm or stronger is 1.
4
+ */
5
+ export const strengthOfDbm = (dbm) => (Math.min(Math.max(dbm, -100), -40) + 100) / 60;
@@ -0,0 +1,7 @@
1
+ import { z } from "zod";
2
+ /** A `v`, as `domicile_host::dbus_json` writes it, read as its value. */
3
+ export declare const variant: <T>(value: z.ZodType<T>) => z.ZodPipe<z.ZodObject<{
4
+ value: z.ZodType<T, unknown, z.core.$ZodTypeInternals<T, unknown>>;
5
+ }, z.core.$strip>, z.ZodTransform<Awaited<T>, {
6
+ value: T;
7
+ }>>;
@@ -0,0 +1,3 @@
1
+ import { z } from "zod";
2
+ /** A `v`, as `domicile_host::dbus_json` writes it, read as its value. */
3
+ export const variant = (value) => z.object({ value }).transform(({ value: held }) => held);
@@ -0,0 +1,58 @@
1
+ import type { Dbus } from "@domicile-desktop/sdk/desktop/dbus";
2
+ import type { Processes } from "@domicile-desktop/sdk/desktop/processes";
3
+ /** The service that manages the Wi-Fi device. */
4
+ export declare enum WifiBackend {
5
+ NetworkManager = 0,
6
+ Iwd = 1
7
+ }
8
+ /** A network in range. */
9
+ export type WifiNetwork = {
10
+ /** The service's object for it: an access point (NetworkManager) or a network (iwd). */
11
+ path: string;
12
+ ssid: string;
13
+ /** 0 through 1. */
14
+ strength: number;
15
+ secured: boolean;
16
+ /** The saved profile: a connection (NetworkManager) or a known network (iwd). */
17
+ profile: string | undefined;
18
+ connected: boolean;
19
+ };
20
+ /** The addresses the service configured. */
21
+ export type Ip = {
22
+ /** Each with its prefix, as `192.168.1.23/24`. */
23
+ addresses: string[];
24
+ gateway: string | undefined;
25
+ dns: string[];
26
+ };
27
+ export type WifiConnection = {
28
+ ssid: string;
29
+ /** 0 through 1. */
30
+ strength: number;
31
+ /** In MHz. */
32
+ frequency: number | undefined;
33
+ /** In Mbit/s. */
34
+ bitrate: number | undefined;
35
+ /** `undefined` from iwd, which does not report addresses over D-Bus. */
36
+ ip: Ip | undefined;
37
+ };
38
+ export type Wifi = {
39
+ backend: WifiBackend;
40
+ /** The device's object, which requests address. */
41
+ device: string;
42
+ interface: string;
43
+ hardwareAddress: string;
44
+ /** Whether the radio is on. */
45
+ enabled: boolean;
46
+ /** Whether a scan is running. Always `false` from NetworkManager, which does not say. */
47
+ scanning: boolean;
48
+ /** One per name, strongest first. Hidden networks are left out. */
49
+ networks: WifiNetwork[];
50
+ connection: WifiConnection | undefined;
51
+ };
52
+ /** What a request needs of the device. */
53
+ export type WifiDevice = Pick<Wifi, "backend" | "device" | "interface">;
54
+ /** The calls this library makes for Wi-Fi. */
55
+ export type WifiDesktop = {
56
+ readonly dbus: Pick<Dbus, "call" | "match">;
57
+ readonly processes: Pick<Processes, "run">;
58
+ };
@@ -0,0 +1,8 @@
1
+ // The Wi-Fi device as every backend reports it: its networks and its
2
+ // connection. See docs/SHELL-SYSTEM-ACCESS.md.
3
+ /** The service that manages the Wi-Fi device. */
4
+ export var WifiBackend;
5
+ (function (WifiBackend) {
6
+ WifiBackend[WifiBackend["NetworkManager"] = 0] = "NetworkManager";
7
+ WifiBackend[WifiBackend["Iwd"] = 1] = "Iwd";
8
+ })(WifiBackend || (WifiBackend = {}));
package/dist/wifi.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Option, Result } from "@cprussin/option-result";
2
+ import type { SystemError } from "@domicile-desktop/sdk/system";
3
+ import type { Wifi, WifiDesktop, WifiDevice, WifiNetwork } from "./wifi-state";
4
+ export type { Ip, Wifi, WifiConnection, WifiDesktop, WifiDevice, WifiNetwork, } from "./wifi-state";
5
+ export { WifiBackend } from "./wifi-state";
6
+ /**
7
+ * Calls `onWifi` with the Wi-Fi device now and after each change, and returns
8
+ * a function that stops watching.
9
+ *
10
+ * Watches the first of NetworkManager and iwd on the system bus when called.
11
+ * `None` is no Wi-Fi device, or neither service: wpa_supplicant alone is not
12
+ * controlled. An `Err` is a D-Bus failure.
13
+ */
14
+ export declare const watchWifi: (domicile: WifiDesktop, onWifi: (wifi: Result<Option<Wifi>, SystemError>) => void) => (() => void);
15
+ /** Turn the radio on or off. */
16
+ export declare const setWifiEnabled: (domicile: WifiDesktop, wifi: WifiDevice, enabled: boolean) => Promise<Result<"done", SystemError>>;
17
+ /** Ask for a scan. Networks it finds arrive through the watch. */
18
+ export declare const scanWifi: (domicile: WifiDesktop, wifi: WifiDevice) => Promise<Result<"done", SystemError>>;
19
+ /**
20
+ * Join `network`. A secured network with no saved profile needs `passphrase`;
21
+ * the call throws without one.
22
+ */
23
+ export declare const connectWifi: (domicile: WifiDesktop, wifi: WifiDevice, network: WifiNetwork, passphrase: string | undefined) => Promise<Result<"done", SystemError>>;
24
+ /** Leave the current network. */
25
+ export declare const disconnectWifi: (domicile: WifiDesktop, wifi: WifiDevice) => Promise<Result<"done", SystemError>>;