@x-tech-laboratories/x-app 0.120.0 → 0.121.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.
Files changed (38) hide show
  1. package/README.md +20 -1
  2. package/dist/app/daemon.d.ts +7 -1
  3. package/dist/app/daemon.js +76 -8
  4. package/dist/app/define.d.ts +22 -1
  5. package/dist/app/define.js +34 -1
  6. package/dist/app/desktop.d.ts +13 -0
  7. package/dist/app/desktop.js +35 -3
  8. package/dist/app/host_tables.d.ts +20 -0
  9. package/dist/app/host_tables.js +91 -0
  10. package/dist/app/preload.js +5 -0
  11. package/dist/app/protocol.d.ts +29 -1
  12. package/dist/app/protocol.js +8 -1
  13. package/dist/app/remote_access.d.ts +17 -0
  14. package/dist/app/remote_access.js +85 -0
  15. package/dist/app/server.d.ts +11 -3
  16. package/dist/app/server.js +49 -14
  17. package/dist/app/services.d.ts +15 -0
  18. package/dist/app/web/app_page.js +43 -6
  19. package/dist/app/web/hosts.d.ts +4 -2
  20. package/dist/app/web/hosts.js +33 -0
  21. package/dist/app/web/page.d.ts +3 -0
  22. package/dist/app/web/page.js +24 -4
  23. package/dist/app/web/portal.d.ts +14 -0
  24. package/dist/app/web/portal.js +115 -0
  25. package/dist/app/web/settings_page.d.ts +5 -1
  26. package/dist/app/web/settings_page.js +25 -6
  27. package/dist/change_checks.js +1 -1
  28. package/dist/github_targets.d.ts +12 -0
  29. package/dist/github_targets.js +90 -0
  30. package/dist/remote_access_protocol.d.ts +26 -0
  31. package/dist/remote_access_protocol.js +33 -0
  32. package/dist/server/github_webhook.d.ts +2 -12
  33. package/dist/server/github_webhook.js +2 -87
  34. package/dist/web/react/remote_access_settings.d.ts +5 -0
  35. package/dist/web/react/remote_access_settings.js +55 -0
  36. package/dist/web/remote_daemon.d.ts +26 -0
  37. package/dist/web/remote_daemon.js +105 -0
  38. package/package.json +1 -1
@@ -2,94 +2,9 @@
2
2
  // app's secret, never by a bearer token or another forge's header; an address that keeps failing waits; a delivery id
3
3
  // seen before is answered without being passed on again; and of each delivery only the repository and the pull
4
4
  // requests, branches and issues it names are kept, each checked for shape, for the app to look up for itself.
5
+ import { delivery_id_of, github_target_events, targets_of } from "../github_targets.js";
5
6
  import { AddressLockout, is_signed, parse_payload } from "./forge_webhook.js";
6
- // ── Shapes ───────────────────────────────────────────────────────────────────
7
- // The events that name pull requests, branches or issues, for the app to tick on GitHub.
8
- export const github_target_events = ["pull_request", "check_suite", "check_run", "status", "workflow_run", "issues", "issue_comment"];
9
- const repository_pattern = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
10
- const branch_pattern = /^[A-Za-z0-9._/-]{1,255}$/;
11
- const delivery_pattern = /^[A-Za-z0-9-]{1,100}$/;
12
- const most_targets = 50;
13
- function fields_of(value) {
14
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
15
- }
16
- function number_of(value) {
17
- return typeof value === "number" && Number.isInteger(value) && value > 0 && value < 2 ** 31 ? value : null;
18
- }
19
- function branch_of(value) {
20
- return typeof value === "string" && branch_pattern.test(value) && !value.includes("..") && !value.startsWith("-") ? value : null;
21
- }
22
- // The pull request numbers in a list such as check_suite.pull_requests, left out where they are not plain numbers.
23
- function numbers_in(list) {
24
- return (Array.isArray(list) ? list : []).map((entry) => number_of(fields_of(entry).number)).filter((number) => number !== null);
25
- }
26
- // Whether a name is a repository as owner/name.
27
- export function is_repository_name(name) {
28
- return repository_pattern.test(name);
29
- }
30
- // The repository a payload names as owner/name, or null when it names none that looks like one.
31
- export function repository_of(payload) {
32
- const name = fields_of(fields_of(payload).repository).full_name;
33
- return typeof name === "string" && repository_pattern.test(name) ? name : null;
34
- }
35
- // The delivery id as GitHub sends it, or "" when it is missing or not an id.
36
- export function delivery_id_of(header) {
37
- return typeof header === "string" && delivery_pattern.test(header) ? header : "";
38
- }
39
- // The repository and the pull requests, branches and issues a delivery names, or null; nothing else in it is kept.
40
- export function targets_of(event, payload) {
41
- const repository = repository_of(payload);
42
- if (repository === null)
43
- return null;
44
- const values = fields_of(payload);
45
- const pull_requests = [];
46
- const branches = [];
47
- const issues = [];
48
- if (event === "ping") {
49
- // Only says the hook works.
50
- }
51
- else if (event === "pull_request") {
52
- const pull = fields_of(values.pull_request);
53
- const head = fields_of(pull.head);
54
- pull_requests.push(number_of(pull.number) ?? number_of(values.number));
55
- // A fork's branch is not one of the repository's own, so only a branch of the same repository counts.
56
- if (fields_of(head.repo).full_name === repository)
57
- branches.push(branch_of(head.ref));
58
- }
59
- else if (event === "check_suite" || event === "workflow_run") {
60
- const suite = fields_of(values[event]);
61
- branches.push(branch_of(suite.head_branch));
62
- pull_requests.push(...numbers_in(suite.pull_requests));
63
- }
64
- else if (event === "check_run") {
65
- const run = fields_of(values.check_run);
66
- branches.push(branch_of(fields_of(run.check_suite).head_branch));
67
- pull_requests.push(...numbers_in(run.pull_requests));
68
- }
69
- else if (event === "status") {
70
- branches.push(...(Array.isArray(values.branches) ? values.branches : []).map((branch) => branch_of(fields_of(branch).name)));
71
- }
72
- else if (event === "issues" || event === "issue_comment") {
73
- issues.push(number_of(fields_of(values.issue).number));
74
- }
75
- else
76
- return null;
77
- const kept = (list) => [...new Set(list.filter((value) => value !== null))].slice(0, most_targets);
78
- return { repository, pull_requests: kept(pull_requests), branches: kept(branches), issues: kept(issues) };
79
- }
80
- // A delivery's targets as stored, each list left empty where the stored text is damaged.
81
- export function read_targets(repository, stored) {
82
- let fields = {};
83
- try {
84
- fields = fields_of(JSON.parse(stored));
85
- }
86
- catch {
87
- fields = {};
88
- }
89
- const numbers = (value) => (Array.isArray(value) ? value.map(number_of).filter((number) => number !== null) : []);
90
- const names = Array.isArray(fields.branches) ? fields.branches.map(branch_of).filter((branch) => branch !== null) : [];
91
- return { repository, pull_requests: numbers(fields.pull_requests), branches: names, issues: numbers(fields.issues) };
92
- }
7
+ export { github_target_events, is_repository_name, repository_of, delivery_id_of, targets_of, read_targets } from "../github_targets.js";
93
8
  // ── Addresses ────────────────────────────────────────────────────────────────
94
9
  // A public address as saved: http or https with a host and maybe a path, no query, fragment or user; anything else throws.
95
10
  export function read_public_url(typed) {
@@ -0,0 +1,5 @@
1
+ import type { RemoteAccessClient } from "../../remote_access_protocol.ts";
2
+ export declare function RemoteAccessSettings({ remote, reach }: {
3
+ remote: RemoteAccessClient;
4
+ reach?: string;
5
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,55 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // "Let other devices connect": whether this computer's daemon listens on the network, where, over https or not, and
3
+ // the admins a phone, a browser or another computer signs in as, for Settings on the desktop.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { useEffect, useState } from "react";
6
+ import { StatusPill } from "./badges.js";
7
+ import { Switch } from "./controls.js";
8
+ import { confirm_dialog } from "./dialog.js";
9
+ import { SettingRow } from "./layout.js";
10
+ import { attempt_value as attempt, show_error } from "./toasts.js";
11
+ // What other devices can do once signed in, for the switch's hint.
12
+ const default_reach = "Phones, browsers and other computers sign in as an admin below and work on this computer's data with its rights.";
13
+ // ── Section ──────────────────────────────────────────────────────────────────
14
+ export function RemoteAccessSettings({ remote, reach = default_reach }) {
15
+ const [status, set_status] = useState(null);
16
+ const [draft, set_draft] = useState(null);
17
+ const [name, set_name] = useState("");
18
+ const [password, set_password] = useState("");
19
+ useEffect(() => {
20
+ void remote.get_remote_access().then((found) => {
21
+ set_status(found);
22
+ set_draft(found.settings);
23
+ }, show_error);
24
+ }, [remote]);
25
+ if (!status || !draft)
26
+ return null;
27
+ async function save(next) {
28
+ const saved = await attempt(() => remote.set_remote_access(next));
29
+ if (saved) {
30
+ set_status(saved);
31
+ set_draft(saved.settings);
32
+ }
33
+ }
34
+ async function add_admin() {
35
+ const saved = await attempt(() => remote.set_remote_admin(name, password), `${name.trim()} can sign in from other devices.`);
36
+ if (!saved)
37
+ return;
38
+ set_status(saved);
39
+ set_name("");
40
+ set_password("");
41
+ }
42
+ function remove_admin(admin) {
43
+ confirm_dialog({
44
+ title: `Remove ${admin}?`,
45
+ message: "Devices signed in as them can no longer reach this computer.",
46
+ confirm_label: "Remove",
47
+ danger: true,
48
+ run: async () => void (await attempt(() => remote.remove_remote_admin(admin)).then((saved) => saved && set_status(saved))),
49
+ });
50
+ }
51
+ const field = (key, label, hint, placeholder = "") => (_jsx(SettingRow, { label: label, hint: hint, as_label: true, children: _jsx("input", { type: "text", spellCheck: false, placeholder: placeholder, value: draft[key], onChange: (event) => set_draft({ ...draft, [key]: event.currentTarget.value }) }) }));
52
+ const is_changed = JSON.stringify(draft) !== JSON.stringify(status.settings);
53
+ const state = status.listening ? _jsx(StatusPill, { tone: "good", label: `Listening on ${status.listening}` }) : status.problem ? _jsx(StatusPill, { tone: "bad", label: status.problem }) : _jsx(StatusPill, { label: "Off" });
54
+ return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Let other devices connect", hint: `${reach} Use https, a VPN or a reverse proxy; plain http sends passwords and tokens as they are.`, as_label: true, children: _jsx(Switch, { label: "Let other devices connect", checked: status.settings.enabled, on_change: (on) => void save({ ...draft, enabled: on }) }) }), _jsx(SettingRow, { label: "State", children: state }), field("host", "Address", "Where to listen: 0.0.0.0 for every network, or one address such as a VPN's.", "0.0.0.0"), _jsx(SettingRow, { label: "Port", as_label: true, children: _jsx("input", { type: "number", min: 1, max: 65535, value: draft.port, onChange: (event) => set_draft({ ...draft, port: Number(event.currentTarget.value) }) }) }), field("certificate_file", "Certificate file", "The https certificate, as a PEM file; empty for plain http.", "/path/to/cert.pem"), field("key_file", "Key file", "The certificate's private key, as a PEM file.", "/path/to/key.pem"), _jsx(SettingRow, { label: "Save", hint: "Listens again with these settings.", children: _jsx("button", { type: "button", disabled: !is_changed, onClick: () => void save(draft), children: "Save" }) }), status.admins.map((admin) => (_jsx(SettingRow, { label: admin, hint: "An admin who may sign in from other devices", children: _jsx("button", { type: "button", className: "danger", onClick: () => remove_admin(admin), children: "Remove" }) }, admin))), _jsxs("form", { onSubmit: (event) => { event.preventDefault(); void add_admin(); }, children: [_jsx(SettingRow, { label: "Admin name", hint: "Signing in again with a new password changes it.", as_label: true, children: _jsx("input", { type: "text", autoCapitalize: "none", spellCheck: false, autoComplete: "off", value: name, onChange: (event) => set_name(event.currentTarget.value) }) }), _jsx(SettingRow, { label: "Password", hint: "At least 10 characters.", as_label: true, children: _jsx("input", { type: "password", autoComplete: "new-password", value: password, onChange: (event) => set_password(event.currentTarget.value) }) }), _jsx(SettingRow, { label: "Add an admin", children: _jsx("button", { type: "submit", disabled: name.trim() === "" || password === "", children: "Add Admin" }) })] })] }));
55
+ }
@@ -0,0 +1,26 @@
1
+ export type RemoteRemoteClient<Methods> = {
2
+ [Name in keyof Methods]: Methods[Name] extends (...args: infer Args) => infer Result ? (...args: Args) => Promise<Awaited<Result>> : never;
3
+ };
4
+ export type RemoteClient<Methods> = {
5
+ [Name in keyof Methods]: Methods[Name] extends (...args: infer Args) => infer Result ? (...args: Args) => Promise<Awaited<Result>> : never;
6
+ };
7
+ export interface RemoteDaemon {
8
+ address: string;
9
+ token: string;
10
+ }
11
+ export interface RemoteLink {
12
+ daemon: () => RemoteDaemon | null;
13
+ client_id: () => string;
14
+ fetch?: typeof fetch;
15
+ }
16
+ export declare function call_remote(link: RemoteLink, path: string, args: unknown[]): Promise<unknown>;
17
+ export declare function remote_table<Methods extends Record<keyof Methods, (...args: never[]) => unknown>>(link: RemoteLink, prefix: string): RemoteClient<Methods>;
18
+ export interface FollowRemoteOptions {
19
+ retry_ms?: number;
20
+ on_connect?: () => void;
21
+ }
22
+ export declare function parse_remote_event(block: string): {
23
+ event: string;
24
+ data: string;
25
+ } | null;
26
+ export declare function follow_remote(link: RemoteLink, on_event: (event: string, data: string) => void, options?: FollowRemoteOptions): () => void;
@@ -0,0 +1,105 @@
1
+ // A page's calls to a daemon or server on another computer, made from the page itself with this device's token, as a
2
+ // phone that keeps no data makes them: each call posted under its table's path, and the host's events followed over a
3
+ // stream read by hand, since EventSource sends no token.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { LoginNeeded } from "./states.js";
6
+ const no_daemon_text = "No daemon is chosen yet. Add one under Settings → Connections.";
7
+ // One call to the daemon, its arguments as a JSON list; a refusal throws the daemon's words.
8
+ export async function call_remote(link, path, args) {
9
+ const daemon = link.daemon();
10
+ if (daemon === null)
11
+ throw new Error(no_daemon_text);
12
+ let response;
13
+ try {
14
+ response = await (link.fetch ?? fetch)(`${daemon.address}${path}`, {
15
+ method: "POST",
16
+ headers: { "content-type": "application/json", authorization: `Bearer ${daemon.token}`, "x-client-id": link.client_id() },
17
+ body: JSON.stringify(args),
18
+ });
19
+ }
20
+ catch {
21
+ throw new Error(`The daemon at ${daemon.address} did not answer.`);
22
+ }
23
+ const text = await response.text();
24
+ if (response.status === 401)
25
+ throw new LoginNeeded("This device's sign-in was refused; add the daemon again under Settings → Connections.");
26
+ if (!response.ok)
27
+ throw new Error(error_text(text) || `The daemon answered ${response.status}.`);
28
+ return text === "" ? undefined : JSON.parse(text);
29
+ }
30
+ // The words of a refusal, sent as JSON with an error or message, or as plain text.
31
+ function error_text(text) {
32
+ try {
33
+ const parsed = JSON.parse(text);
34
+ return String(parsed.error ?? parsed.message ?? text);
35
+ }
36
+ catch {
37
+ return text;
38
+ }
39
+ }
40
+ // Every call of a table by name, posted under its path, such as "/api/runner/"; the daemon refuses names it lacks.
41
+ export function remote_table(link, prefix) {
42
+ return new Proxy({}, {
43
+ get: (_target, name) => (typeof name === "string" && name !== "then" ? (...args) => call_remote(link, `${prefix}${name}`, args) : undefined),
44
+ });
45
+ }
46
+ // One server-sent event's name and data, or null for a comment or keep-alive.
47
+ export function parse_remote_event(block) {
48
+ let event = "message";
49
+ const data = [];
50
+ for (const line of block.split("\n")) {
51
+ if (line.startsWith("event:"))
52
+ event = line.slice(6).trim();
53
+ else if (line.startsWith("data:"))
54
+ data.push(line.slice(5).replace(/^ /, ""));
55
+ }
56
+ return data.length ? { event, data: data.join("\n") } : null;
57
+ }
58
+ // Follows the daemon's change events with the token, reconnecting whenever the stream ends; returns how to stop.
59
+ export function follow_remote(link, on_event, options = {}) {
60
+ const retry_ms = options.retry_ms ?? 5000;
61
+ let stopped = false;
62
+ let retry;
63
+ let stream = null;
64
+ async function read() {
65
+ const daemon = link.daemon();
66
+ if (daemon === null)
67
+ return;
68
+ stream = new AbortController();
69
+ const response = await (link.fetch ?? fetch)(`${daemon.address}/api/events`, { headers: { accept: "text/event-stream", authorization: `Bearer ${daemon.token}` }, signal: stream.signal });
70
+ if (!response.ok || !response.body)
71
+ return void (await response.body?.cancel());
72
+ options.on_connect?.();
73
+ const reader = response.body.getReader();
74
+ const decoder = new TextDecoder();
75
+ let buffer = "";
76
+ for (;;) {
77
+ const { value, done } = await reader.read();
78
+ if (done)
79
+ return;
80
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
81
+ let cut;
82
+ while ((cut = buffer.indexOf("\n\n")) >= 0) {
83
+ const parsed = parse_remote_event(buffer.slice(0, cut));
84
+ buffer = buffer.slice(cut + 2);
85
+ if (parsed)
86
+ on_event(parsed.event, parsed.data);
87
+ }
88
+ }
89
+ }
90
+ function open() {
91
+ void read()
92
+ .catch(() => undefined)
93
+ .finally(() => {
94
+ stream = null;
95
+ if (!stopped)
96
+ retry = setTimeout(open, retry_ms);
97
+ });
98
+ }
99
+ open();
100
+ return () => {
101
+ stopped = true;
102
+ clearTimeout(retry);
103
+ stream?.abort();
104
+ };
105
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.120.0",
3
+ "version": "0.121.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {