clavarium 0.2.47-next.1 → 0.2.49-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config/launch/claude-code.sh +7 -0
- package/deploy/clavarium-host +10 -2
- package/npm-shrinkwrap.json +94 -6
- package/package.json +3 -2
- package/server/accounts.mjs +130 -0
- package/server/api.mjs +26 -2
- package/server/conversations.mjs +18 -3
- package/server/guide.mjs +2 -0
- package/server/imap.mjs +16 -0
- package/server/mailbox.mjs +58 -9
- package/server/main.mjs +36 -4
- package/server/oauth.mjs +224 -0
- package/server/parley.mjs +2 -0
- package/server/secret-scan.mjs +104 -0
- package/server/secrets.mjs +77 -8
- package/server/signin.mjs +38 -2
- package/server/talk.mjs +26 -5
- package/server/tethers.mjs +91 -0
- package/server/vm.mjs +4 -2
- package/web/app.js +164 -25
- package/web/index.html +38 -6
- package/web/style.css +23 -7
|
@@ -33,6 +33,13 @@ if [ -f "$chat/server.mjs" ] && command -v docket-mcp >/dev/null 2>&1 && ! grep
|
|
|
33
33
|
claude mcp add --scope user docket -- docket-mcp --dir "$docket" >/dev/null 2>&1 \
|
|
34
34
|
|| echo "launch: Docket was not given to Claude Code as tools: the command docket still works" >&2
|
|
35
35
|
fi
|
|
36
|
+
# ITS TETHER AS ITS OWN TOOLS (MCP): the accesses it was given -- a mailbox, a calendar, an address
|
|
37
|
+
# book, an online folder, a machine over SSH. The server holds the keys; it acts within its rights.
|
|
38
|
+
tether="/work/.tether"
|
|
39
|
+
if command -v tether-mcp >/dev/null 2>&1 && ! grep -q "\"$tether\"" "$HOME/.claude.json" 2>/dev/null; then
|
|
40
|
+
claude mcp add --scope user tether -- tether-mcp --dir "$tether" >/dev/null 2>&1 \
|
|
41
|
+
|| echo "launch: Tether was not given to Claude Code as tools: the command tether still works" >&2
|
|
42
|
+
fi
|
|
36
43
|
# ITS PULSE: Claude Code's own hooks say to the chat that it acts, and when its turn ends, so that
|
|
37
44
|
# the person sees "Working..." while it works without a word (parley pulse; nothing posted).
|
|
38
45
|
if [ -f "$chat/server.mjs" ]; then
|
package/deploy/clavarium-host
CHANGED
|
@@ -724,8 +724,16 @@ AREA="$1"; VERB="$2"; shift 2
|
|
|
724
724
|
|
|
725
725
|
case "$AREA $VERB" in
|
|
726
726
|
"vm launch")
|
|
727
|
-
|
|
728
|
-
|
|
727
|
+
# <vm> <memory> [<disk-gigabytes> <cores>]: the size chosen at creation;
|
|
728
|
+
# without the last two, the defaults (DISK, one core).
|
|
729
|
+
[ $# -eq 2 ] || [ $# -eq 4 ] || usage; vm_of "$1"; memory_ok "$2"
|
|
730
|
+
disk="$DISK"; cores=1
|
|
731
|
+
if [ $# -eq 4 ]; then
|
|
732
|
+
[[ "$3" =~ ^[0-9]{1,4}$ ]] && [ "$3" -ge 5 ] && [ "$3" -le "$DISK_MAX_GB" ] || refuse "disk out of bounds: $3"
|
|
733
|
+
[[ "$4" =~ ^[0-9]{1,3}$ ]] && [ "$4" -ge 1 ] && [ "$4" -le "$(nproc)" ] || refuse "cores out of bounds: $4 (the host has $(nproc))"
|
|
734
|
+
disk="${3}G"; cores="$4"
|
|
735
|
+
fi
|
|
736
|
+
run "$MULTIPASS" launch "$IMAGE" --name "$1" --memory "${2}M" --disk "$disk" --cpus "$cores" --timeout "$LAUNCH_SECONDS" ;;
|
|
729
737
|
"vm clone")
|
|
730
738
|
# <shelf> <vm> <memory>: a conversation's machine, copied from the
|
|
731
739
|
# ready-made one (which must be stopped: Multipass refuses otherwise).
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.49-beta.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.49-beta.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
13
13
|
"@xterm/xterm": "^6.0.0",
|
|
14
14
|
"clavarium-binder": "0.1.8-next.1",
|
|
15
15
|
"clavarium-docket": "0.1.1",
|
|
16
|
-
"clavarium-parley": "0.17.
|
|
16
|
+
"clavarium-parley": "0.17.9-next.1",
|
|
17
|
+
"clavarium-tether": "0.1.0-next.8",
|
|
17
18
|
"mermaid": "11.17.2",
|
|
18
19
|
"node-pty": "^1.1.0",
|
|
19
20
|
"pdfjs-dist": "6.4.299",
|
|
@@ -654,6 +655,15 @@
|
|
|
654
655
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
|
655
656
|
}
|
|
656
657
|
},
|
|
658
|
+
"node_modules/asn1": {
|
|
659
|
+
"version": "0.2.6",
|
|
660
|
+
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
|
|
661
|
+
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
|
|
662
|
+
"license": "MIT",
|
|
663
|
+
"dependencies": {
|
|
664
|
+
"safer-buffer": "~2.1.0"
|
|
665
|
+
}
|
|
666
|
+
},
|
|
657
667
|
"node_modules/asn1.js": {
|
|
658
668
|
"version": "5.4.1",
|
|
659
669
|
"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz",
|
|
@@ -666,6 +676,15 @@
|
|
|
666
676
|
"safer-buffer": "^2.1.0"
|
|
667
677
|
}
|
|
668
678
|
},
|
|
679
|
+
"node_modules/bcrypt-pbkdf": {
|
|
680
|
+
"version": "1.0.2",
|
|
681
|
+
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
|
|
682
|
+
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
|
|
683
|
+
"license": "BSD-3-Clause",
|
|
684
|
+
"dependencies": {
|
|
685
|
+
"tweetnacl": "^0.14.3"
|
|
686
|
+
}
|
|
687
|
+
},
|
|
669
688
|
"node_modules/bn.js": {
|
|
670
689
|
"version": "4.12.5",
|
|
671
690
|
"resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz",
|
|
@@ -678,6 +697,15 @@
|
|
|
678
697
|
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
|
679
698
|
"license": "BSD-3-Clause"
|
|
680
699
|
},
|
|
700
|
+
"node_modules/buildcheck": {
|
|
701
|
+
"version": "0.0.7",
|
|
702
|
+
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
|
|
703
|
+
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
|
|
704
|
+
"optional": true,
|
|
705
|
+
"engines": {
|
|
706
|
+
"node": ">=10.0.0"
|
|
707
|
+
}
|
|
708
|
+
},
|
|
681
709
|
"node_modules/camelcase": {
|
|
682
710
|
"version": "5.3.1",
|
|
683
711
|
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
|
@@ -714,9 +742,9 @@
|
|
|
714
742
|
}
|
|
715
743
|
},
|
|
716
744
|
"node_modules/clavarium-parley": {
|
|
717
|
-
"version": "0.17.
|
|
718
|
-
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.
|
|
719
|
-
"integrity": "sha512
|
|
745
|
+
"version": "0.17.9-next.1",
|
|
746
|
+
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.9-next.1.tgz",
|
|
747
|
+
"integrity": "sha512-pKwFQnq/6JO2nA37u9RNCO6ddgCUvpqmmmqRPQMa5GGT1nL0dFGDs1hY+Wed3TqKYRKxLmCgUWgts0aQBYihqw==",
|
|
720
748
|
"license": "MIT",
|
|
721
749
|
"bin": {
|
|
722
750
|
"parley": "bin/parley.mjs",
|
|
@@ -726,6 +754,22 @@
|
|
|
726
754
|
"node": ">=22"
|
|
727
755
|
}
|
|
728
756
|
},
|
|
757
|
+
"node_modules/clavarium-tether": {
|
|
758
|
+
"version": "0.1.0-next.8",
|
|
759
|
+
"resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.8.tgz",
|
|
760
|
+
"integrity": "sha512-mVMfQ9xCQYARsE/KqfPPkEzssok1WhOkulBu37bnJpu2HtLctxb94NDdOhm43up100qRSZj99ks0KkzigjRRAg==",
|
|
761
|
+
"license": "MIT",
|
|
762
|
+
"bin": {
|
|
763
|
+
"tether": "bin/cli.mjs",
|
|
764
|
+
"tether-mcp": "server/mcp.mjs"
|
|
765
|
+
},
|
|
766
|
+
"engines": {
|
|
767
|
+
"node": ">=22"
|
|
768
|
+
},
|
|
769
|
+
"optionalDependencies": {
|
|
770
|
+
"ssh2": "1.17.0"
|
|
771
|
+
}
|
|
772
|
+
},
|
|
729
773
|
"node_modules/cliui": {
|
|
730
774
|
"version": "6.0.0",
|
|
731
775
|
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
|
|
@@ -773,6 +817,20 @@
|
|
|
773
817
|
"layout-base": "^1.0.0"
|
|
774
818
|
}
|
|
775
819
|
},
|
|
820
|
+
"node_modules/cpu-features": {
|
|
821
|
+
"version": "0.0.10",
|
|
822
|
+
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
|
|
823
|
+
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
|
|
824
|
+
"hasInstallScript": true,
|
|
825
|
+
"optional": true,
|
|
826
|
+
"dependencies": {
|
|
827
|
+
"buildcheck": "~0.0.6",
|
|
828
|
+
"nan": "^2.19.0"
|
|
829
|
+
},
|
|
830
|
+
"engines": {
|
|
831
|
+
"node": ">=10.0.0"
|
|
832
|
+
}
|
|
833
|
+
},
|
|
776
834
|
"node_modules/cytoscape": {
|
|
777
835
|
"version": "3.34.4",
|
|
778
836
|
"resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.34.4.tgz",
|
|
@@ -1598,6 +1656,13 @@
|
|
|
1598
1656
|
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
|
1599
1657
|
"license": "MIT"
|
|
1600
1658
|
},
|
|
1659
|
+
"node_modules/nan": {
|
|
1660
|
+
"version": "2.30.0",
|
|
1661
|
+
"resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz",
|
|
1662
|
+
"integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==",
|
|
1663
|
+
"license": "MIT",
|
|
1664
|
+
"optional": true
|
|
1665
|
+
},
|
|
1601
1666
|
"node_modules/node-addon-api": {
|
|
1602
1667
|
"version": "7.1.1",
|
|
1603
1668
|
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
|
|
@@ -1805,6 +1870,23 @@
|
|
|
1805
1870
|
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
|
1806
1871
|
"license": "ISC"
|
|
1807
1872
|
},
|
|
1873
|
+
"node_modules/ssh2": {
|
|
1874
|
+
"version": "1.17.0",
|
|
1875
|
+
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
|
|
1876
|
+
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
|
|
1877
|
+
"hasInstallScript": true,
|
|
1878
|
+
"dependencies": {
|
|
1879
|
+
"asn1": "^0.2.6",
|
|
1880
|
+
"bcrypt-pbkdf": "^1.0.2"
|
|
1881
|
+
},
|
|
1882
|
+
"engines": {
|
|
1883
|
+
"node": ">=10.16.0"
|
|
1884
|
+
},
|
|
1885
|
+
"optionalDependencies": {
|
|
1886
|
+
"cpu-features": "~0.0.10",
|
|
1887
|
+
"nan": "^2.23.0"
|
|
1888
|
+
}
|
|
1889
|
+
},
|
|
1808
1890
|
"node_modules/strictdom": {
|
|
1809
1891
|
"version": "1.0.1",
|
|
1810
1892
|
"resolved": "https://registry.npmjs.org/strictdom/-/strictdom-1.0.1.tgz",
|
|
@@ -1861,6 +1943,12 @@
|
|
|
1861
1943
|
"node": ">=6.10"
|
|
1862
1944
|
}
|
|
1863
1945
|
},
|
|
1946
|
+
"node_modules/tweetnacl": {
|
|
1947
|
+
"version": "0.14.5",
|
|
1948
|
+
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
|
|
1949
|
+
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
|
|
1950
|
+
"license": "Unlicense"
|
|
1951
|
+
},
|
|
1864
1952
|
"node_modules/uuid": {
|
|
1865
1953
|
"version": "14.0.3",
|
|
1866
1954
|
"resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.3.tgz",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.49-beta.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
|
|
@@ -46,7 +46,8 @@
|
|
|
46
46
|
"@xterm/xterm": "^6.0.0",
|
|
47
47
|
"clavarium-binder": "0.1.8-next.1",
|
|
48
48
|
"clavarium-docket": "0.1.1",
|
|
49
|
-
"clavarium-parley": "0.17.
|
|
49
|
+
"clavarium-parley": "0.17.9-next.1",
|
|
50
|
+
"clavarium-tether": "0.1.0-next.8",
|
|
50
51
|
"mermaid": "11.17.2",
|
|
51
52
|
"node-pty": "^1.1.0",
|
|
52
53
|
"pdfjs-dist": "6.4.299",
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/* CONNECTING AN ACCOUNT BY TOKEN: a mailbox, a calendar, an address book of a
|
|
2
|
+
* Google or Microsoft account, reached live through Tether -- not copied into a
|
|
3
|
+
* folder (that is the older mailbox.mjs, kept until this replaces it).
|
|
4
|
+
*
|
|
5
|
+
* THE TOKEN NEVER ENTERS A MACHINE. The person allows the account in their own
|
|
6
|
+
* browser; the code comes back here; this server trades it for a long-lived
|
|
7
|
+
* refresh token and keeps it as a HOST-ONLY secret (secrets.mjs): a secret that
|
|
8
|
+
* cannot be attached to a conversation, so it is never delivered to a VM. The
|
|
9
|
+
* agent is root in its machine, so a token in the machine would be a token lost;
|
|
10
|
+
* instead the keeper reveals it to the connector alone, host-side, and acts on
|
|
11
|
+
* the agent's behalf within the level and rules the person set.
|
|
12
|
+
*
|
|
13
|
+
* ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A Google consent for mail+calendar+
|
|
14
|
+
* contacts yields a single refresh token; this makes one host-only secret and a
|
|
15
|
+
* Tether target per kind, each naming that secret. Microsoft's Thunderbird client
|
|
16
|
+
* carries only the mail scope here, so a Microsoft consent makes the mail target
|
|
17
|
+
* alone (calendar and files over Graph need a deployment's own OAuth app, added
|
|
18
|
+
* later as config.clientId + an own client secret).
|
|
19
|
+
*
|
|
20
|
+
* A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
|
|
21
|
+
* its own level, from the page (Assets > Access) -- like git: one mailbox, many
|
|
22
|
+
* conversations, each its own rights.
|
|
23
|
+
*/
|
|
24
|
+
import { Refusal } from './conversations.mjs';
|
|
25
|
+
import { createHash } from 'node:crypto';
|
|
26
|
+
import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState, PROVIDERS } from './oauth.mjs';
|
|
27
|
+
|
|
28
|
+
/* The loopback the provider sends the code back to; nothing listens there. The
|
|
29
|
+
person's browser lands on a page that will not load, and they copy the whole
|
|
30
|
+
address -- which carries the code -- back into Clavarium. Desktop OAuth clients
|
|
31
|
+
accept any 127.0.0.1 port, and the same address trades the code, so it only has
|
|
32
|
+
to stay constant. (Shared, on purpose, with the older file-copy mailbox.) */
|
|
33
|
+
const REDIRECT = 'http://127.0.0.1:47813/';
|
|
34
|
+
const PENDING_MS = 10 * 60_000;
|
|
35
|
+
const PENDING_MAX = 20;
|
|
36
|
+
|
|
37
|
+
/* The kinds a provider can be connected for here, with the connector and the
|
|
38
|
+
Tether kind each becomes, and whether the target needs the email address. */
|
|
39
|
+
const KIND = {
|
|
40
|
+
mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
|
|
41
|
+
calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
|
|
42
|
+
contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
|
|
43
|
+
};
|
|
44
|
+
/* What each provider's built-in (Thunderbird) client grants a refresh token for. */
|
|
45
|
+
const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail'] };
|
|
46
|
+
|
|
47
|
+
const emailOk = (s) => /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(s);
|
|
48
|
+
/* A deterministic, valid secret name for an account's token: a short slug of the
|
|
49
|
+
address plus a hash of it, so reconnecting the same account reuses the name
|
|
50
|
+
(its value is replaced) and two different accounts never collide. */
|
|
51
|
+
function secretName(provider, user) {
|
|
52
|
+
const slug = user.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 8).replace(/_+$/, '') || 'X';
|
|
53
|
+
const hex = createHash('sha256').update(`${provider}:${user}`).digest('hex').slice(0, 6).toUpperCase();
|
|
54
|
+
return `OAUTH_${provider.toUpperCase()}_${slug}_${hex}`;
|
|
55
|
+
}
|
|
56
|
+
/* A stable target id per account and kind. */
|
|
57
|
+
const targetId = (kind, provider, user) => `${kind}-${provider}-${user.toLowerCase().normalize('NFD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`.slice(0, 60);
|
|
58
|
+
|
|
59
|
+
export class Accounts {
|
|
60
|
+
#secrets; #targets; #fetch; #pending = new Map();
|
|
61
|
+
|
|
62
|
+
/* `secrets`: the vault (set host-only, by name). `targets`: { put(spec) } onto
|
|
63
|
+
the Tether store. `fetch`: injected for tests. */
|
|
64
|
+
constructor({ secrets, targets, fetch = globalThis.fetch }) {
|
|
65
|
+
if (!secrets?.set) throw new Error('accounts needs the secret store');
|
|
66
|
+
if (!targets?.put) throw new Error('accounts needs the Tether target store');
|
|
67
|
+
this.#secrets = secrets; this.#targets = targets; this.#fetch = fetch;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/* Which kinds may be connected, per provider, for the page to offer. */
|
|
71
|
+
supported() { return { ...SUPPORTED }; }
|
|
72
|
+
|
|
73
|
+
/* Start a connection: build the provider's consent page for the kinds asked,
|
|
74
|
+
and keep the state and PKCE verifier until the person pastes the address. */
|
|
75
|
+
consent({ provider, user, kinds } = {}) {
|
|
76
|
+
const prov = String(provider ?? '');
|
|
77
|
+
if (!PROVIDERS[prov] || !SUPPORTED[prov]) throw new Refusal(400, 'Choose Google or Microsoft.');
|
|
78
|
+
const address = String(user ?? '').trim();
|
|
79
|
+
if (!emailOk(address)) throw new Refusal(400, 'The account needs its email address.');
|
|
80
|
+
const wanted = (Array.isArray(kinds) && kinds.length ? kinds : ['mail']).map(String);
|
|
81
|
+
const chosen = SUPPORTED[prov].filter((k) => wanted.includes(k));
|
|
82
|
+
if (!chosen.length) throw new Refusal(400, `${PROVIDERS[prov].label} can be connected here for: ${SUPPORTED[prov].join(', ')}.`);
|
|
83
|
+
this.#sweep();
|
|
84
|
+
if (this.#pending.size >= PENDING_MAX) throw new Refusal(429, 'Too many connections in progress; try again shortly.');
|
|
85
|
+
const { clientId } = thunderbird(prov);
|
|
86
|
+
const state = newState();
|
|
87
|
+
const { verifier, challenge } = pkcePair();
|
|
88
|
+
const url = consentUrl(prov, { clientId, redirectUri: REDIRECT, scope: scopeFor(prov, chosen), state, codeChallenge: challenge, loginHint: address });
|
|
89
|
+
this.#pending.set(state, { provider: prov, user: address, kinds: chosen, verifier, at: Date.now() });
|
|
90
|
+
return { url };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/* Finish it: from the pasted address read the code, trade it for a refresh
|
|
94
|
+
token, keep the token host-side, and make a Tether target per kind. */
|
|
95
|
+
async connect({ redirected } = {}) {
|
|
96
|
+
this.#sweep();
|
|
97
|
+
let state;
|
|
98
|
+
try { state = new URL(String(redirected ?? '').trim()).searchParams.get('state'); } catch { throw new Refusal(400, 'Paste the whole address from the bar, after you allow.'); }
|
|
99
|
+
const p = state && this.#pending.get(state);
|
|
100
|
+
if (!p) throw new Refusal(400, 'This connection has expired or was already used; start it again.');
|
|
101
|
+
this.#pending.delete(state);
|
|
102
|
+
let code;
|
|
103
|
+
try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
|
|
104
|
+
const { clientId, clientSecret } = thunderbird(p.provider);
|
|
105
|
+
let refreshToken;
|
|
106
|
+
try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
|
|
107
|
+
catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
|
|
108
|
+
if (!refreshToken) throw new Refusal(502, 'The account returned no lasting token; allow offline access and try again.');
|
|
109
|
+
/* The token is kept host-only: it can never be attached to a conversation,
|
|
110
|
+
so it is never delivered to a machine -- the keeper reveals it by name. */
|
|
111
|
+
const name = secretName(p.provider, p.user);
|
|
112
|
+
this.#secrets.set({ name, value: refreshToken, hostOnly: true });
|
|
113
|
+
const label = PROVIDERS[p.provider].label;
|
|
114
|
+
const made = [];
|
|
115
|
+
for (const k of p.kinds) {
|
|
116
|
+
const spec = KIND[k];
|
|
117
|
+
const config = { provider: p.provider };
|
|
118
|
+
if (spec.needsUser) config.user = p.user;
|
|
119
|
+
const target = this.#targets.put({
|
|
120
|
+
id: targetId(k, p.provider, p.user),
|
|
121
|
+
title: `${spec.title} — ${p.user} (${label})`,
|
|
122
|
+
kind: spec.kind, connector: spec.connector, config, secrets: { refresh: name },
|
|
123
|
+
});
|
|
124
|
+
made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
|
|
125
|
+
}
|
|
126
|
+
return { provider: p.provider, user: p.user, targets: made };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#sweep() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
|
|
130
|
+
}
|
package/server/api.mjs
CHANGED
|
@@ -146,7 +146,7 @@ function readBody(request, max = BODY_MAX) {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
/* Returns true when the request was an API request (answered here). */
|
|
149
|
-
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral) {
|
|
149
|
+
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts) {
|
|
150
150
|
const { pathname } = new URL(request.url ?? '/', 'http://local');
|
|
151
151
|
if (!pathname.startsWith('/api/')) return false;
|
|
152
152
|
let send = (status, body) => {
|
|
@@ -235,12 +235,17 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
235
235
|
if (pathname === '/api/tools') return send(200, conversations.tools()), true;
|
|
236
236
|
if (pathname === '/api/conversations') {
|
|
237
237
|
const lists = binders?.given() ?? {};
|
|
238
|
-
return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
|
|
238
|
+
return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], ephemeralSecrets: secrets?.liveFor(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
|
|
239
239
|
}
|
|
240
240
|
if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
|
|
241
241
|
if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
|
|
242
242
|
if (pathname === '/api/secrets' && secrets) return send(200, secrets.list()), true;
|
|
243
243
|
if (pathname === '/api/mailboxes' && mailboxes) return send(200, mailboxes.list()), true;
|
|
244
|
+
/* Which providers and kinds an account can be connected for here. */
|
|
245
|
+
if (pathname === '/api/accounts' && accounts) return send(200, { supported: accounts.supported() }), true;
|
|
246
|
+
/* Assets > Access: the targets, who was given each at which level, the
|
|
247
|
+
calls waiting, and the recent journal -- all the page needs to read. */
|
|
248
|
+
if (pathname === '/api/tether' && tethers) { const r = await tethers.act('state', { agent: query.get('agent') ?? undefined }, ''); return send(200, { given: tethers.given(), changes: tethers.changes(), ...(r.data ?? {}) }), true; }
|
|
244
249
|
/* Every device, each with all it was given. */
|
|
245
250
|
if (pathname === '/api/devices' && sharing) return send(200, sharing.devices.all()), true;
|
|
246
251
|
if (pathname === '/api/git-keys' && gitAccess) return send(200, gitAccess.keys()), true;
|
|
@@ -408,8 +413,19 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
408
413
|
return send(200, { ok: true }), true;
|
|
409
414
|
}
|
|
410
415
|
if (pathname === '/api/mailboxes' && mailboxes) { const made = await mailboxes.add(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
|
|
416
|
+
if (pathname === '/api/mailboxes/consent' && mailboxes) return send(200, mailboxes.consent(body)), true;
|
|
417
|
+
if (pathname === '/api/mailboxes/connect' && mailboxes) { const made = await mailboxes.connect(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
|
|
411
418
|
const fetched = /^\/api\/mailboxes\/([a-z0-9-]{1,32})\/sync$/.exec(pathname);
|
|
412
419
|
if (fetched && mailboxes) return send(200, await mailboxes.sync(fetched[1])), true;
|
|
420
|
+
/* Connecting an account by token (consent in the owner's browser, the token
|
|
421
|
+
kept host-only, a Tether target made): see accounts.mjs. */
|
|
422
|
+
if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
|
|
423
|
+
if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
|
|
424
|
+
/* Assets > Access: the owner sets a conversation's level and rules on a
|
|
425
|
+
target, decides a call that waited, or removes a target. Each is an op the
|
|
426
|
+
keeper runs as the owner (person), never as an agent. */
|
|
427
|
+
const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume)$/.exec(pathname);
|
|
428
|
+
if (tetherOp && tethers) { const r = await tethers.act(tetherOp[1], body, ''); if (!r.ok) throw new Refusal(400, r.text); return send(200, r.data ?? { ok: true }), true; }
|
|
413
429
|
if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
|
|
414
430
|
if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
|
|
415
431
|
const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
|
|
@@ -505,6 +521,14 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
505
521
|
retell(conversation);
|
|
506
522
|
return send(200, { ok: true, secrets: secrets.of(conversation) }), true;
|
|
507
523
|
}
|
|
524
|
+
/* Forget an ephemeral secret now (its stars in the chat have a button): gone from the vault and the machine. */
|
|
525
|
+
const forgetSecret = /^\/api\/conversations\/([^/]+)\/secrets\/([^/]+)\/forget$/.exec(pathname);
|
|
526
|
+
if (forgetSecret && secrets) {
|
|
527
|
+
const conversation = decodeURIComponent(forgetSecret[1]);
|
|
528
|
+
if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
|
|
529
|
+
await secrets.drop(conversation, decodeURIComponent(forgetSecret[2]));
|
|
530
|
+
return send(200, { ok: true }), true;
|
|
531
|
+
}
|
|
508
532
|
const share = /^\/api\/conversations\/([^/]+)\/share$/.exec(pathname);
|
|
509
533
|
if (share && sharing) {
|
|
510
534
|
const conversation = decodeURIComponent(share[1]);
|
package/server/conversations.mjs
CHANGED
|
@@ -260,7 +260,7 @@ export class Conversations {
|
|
|
260
260
|
return { name: id, title: title !== undefined && title !== id ? title : undefined };
|
|
261
261
|
}
|
|
262
262
|
|
|
263
|
-
create({ name: given, title: read, tool, memoryMb, workOnDisk, group }) {
|
|
263
|
+
create({ name: given, title: read, tool, memoryMb, cpus, diskGb, workOnDisk, group }) {
|
|
264
264
|
const { name, title } = this.#naming({ name: given, title: read });
|
|
265
265
|
if (group !== undefined) { const problem = groupProblem(group); if (problem) throw new Refusal(400, problem); }
|
|
266
266
|
if (!isConversationName(name)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
|
|
@@ -270,9 +270,14 @@ export class Conversations {
|
|
|
270
270
|
if (!Number.isInteger(memory) || memory < chosen.memoryMb || memory > 16384) {
|
|
271
271
|
throw new Refusal(400, `This tool needs at least ${chosen.memoryMb} MB of memory.`);
|
|
272
272
|
}
|
|
273
|
+
/* Cores and disk, chosen at creation like the memory; their defaults when not given. */
|
|
274
|
+
const cores = cpus ?? 1;
|
|
275
|
+
if (!Number.isInteger(cores) || cores < 1 || cores > availableParallelism()) throw new Refusal(400, `Cores are 1 to ${availableParallelism()} (what this server has).`);
|
|
276
|
+
const disk = diskGb ?? DISK_GB;
|
|
277
|
+
if (!Number.isInteger(disk) || disk < DISK_GB || disk > DISK_MAX_GB) throw new Refusal(400, `Disk is ${DISK_GB} to ${DISK_MAX_GB} GB.`);
|
|
273
278
|
if (this.#store.get(name)) throw new Refusal(409, 'A conversation already has this name.');
|
|
274
279
|
const now = new Date().toISOString();
|
|
275
|
-
const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, diskGb:
|
|
280
|
+
const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, cpus: cores, diskGb: disk, fixed: FIXES, work: workOnDisk === true ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
|
|
276
281
|
/* A new one comes first in its folder (or first of those in none). */
|
|
277
282
|
const { order, groups } = this.#order();
|
|
278
283
|
this.#store.put(conversation);
|
|
@@ -284,6 +289,11 @@ export class Conversations {
|
|
|
284
289
|
/* `again`: a machine built anew for a conversation that had one. */
|
|
285
290
|
async #build(name, tool, memoryMb, again = false) {
|
|
286
291
|
const fail = (what, r) => { this.#store.patch(name, { phase: 'failed', step: undefined, progress: undefined, error: `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}` }); };
|
|
292
|
+
/* The size chosen at creation (stored by create, kept on a rebuild): launched with it, or, for a
|
|
293
|
+
copy of a ready-made machine, brought to it while the copy is still stopped. */
|
|
294
|
+
const made = this.#store.get(name);
|
|
295
|
+
const diskGb = made?.diskGb ?? DISK_GB; const cpus = made?.cpus ?? 1;
|
|
296
|
+
const custom = diskGb !== DISK_GB || cpus !== 1;
|
|
287
297
|
/* A COPY OF THE READY-MADE MACHINE when there is one that holds this
|
|
288
298
|
tool (see shelf.mjs): it only has to boot. Anything wrong with the
|
|
289
299
|
copy -- an older VM manager without "clone", a copy that does not
|
|
@@ -293,13 +303,18 @@ export class Conversations {
|
|
|
293
303
|
let readyMade = false;
|
|
294
304
|
if (from) {
|
|
295
305
|
const cloned = await this.#vms.clone(name, from, memoryMb);
|
|
306
|
+
if (cloned.code === 0 && custom) {
|
|
307
|
+
/* Still stopped, like the memory the clone set: its cores, and its disk grown to the chosen size. */
|
|
308
|
+
if (cpus !== 1) await this.#vms.setCpus(name, cpus).catch(() => {});
|
|
309
|
+
if (diskGb !== DISK_GB) await this.#vms.setDisk(name, diskGb).catch(() => {});
|
|
310
|
+
}
|
|
296
311
|
const started = cloned.code === 0 ? await this.#vms.start(name) : cloned;
|
|
297
312
|
readyMade = started.code === 0;
|
|
298
313
|
if (!readyMade && await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
|
|
299
314
|
if (!this.#store.get(name)) return undefined; /* archived meanwhile */
|
|
300
315
|
}
|
|
301
316
|
if (!readyMade) {
|
|
302
|
-
const launched = await this.#vms.launch(name, memoryMb);
|
|
317
|
+
const launched = await this.#vms.launch(name, memoryMb, custom ? diskGb : undefined, custom ? cpus : undefined);
|
|
303
318
|
if (launched.code !== 0) return fail('The machine did not start', launched);
|
|
304
319
|
}
|
|
305
320
|
this.#store.patch(name, { step: 'Preparing the machine', readyMade: readyMade || undefined });
|
package/server/guide.mjs
CHANGED
|
@@ -129,6 +129,8 @@ export function ownText({ name, tool, workKept, resources = [], chat, online, se
|
|
|
129
129
|
if (chat) out.push('- When you work in batches: keep them in a binder of batches, shown beside the chat. None yet: make it once (binder new batches; MCP: new-list, template batches). Then one card each (binder add Batches "title"), kept up to date; start only those the person ticked.');
|
|
130
130
|
out.push(online === false ? '- Internet: off.' : '- Internet: on.');
|
|
131
131
|
if (secrets.length) out.push(`- Secrets given, by name only: ${list(secrets.map((s) => plain(s, 40)))}.`);
|
|
132
|
+
/* A secret pasted in the chat is lifted out (talk.mjs, secret-scan.mjs): the message shows a marker, the value waits in /run/secrets. */
|
|
133
|
+
if (chat) out.push('- A secret the person pastes in the chat is kept OUT of it: the message shows ⟨secret:NAME⟩ and the value waits at /run/secrets/NAME for a few minutes. Use it only from there, inside a command (clv-run, or $(cat /run/secrets/NAME)); never write its value back into the chat. It clears itself when its time runs out, or at once with `parley forget NAME` when you are done.');
|
|
132
134
|
const own = lines.map((l) => plain(l)).filter(Boolean).slice(0, LINES_MAX);
|
|
133
135
|
if (own.length) out.push('', '## From the owner', '', ...own.map((l) => `- ${l}`));
|
|
134
136
|
out.push('');
|
package/server/imap.mjs
CHANGED
|
@@ -72,4 +72,20 @@ export class Exchange {
|
|
|
72
72
|
if (!new RegExp(`^${tag} OK`, 'i').test(lines.at(-1) ?? '')) throw new Refusal(502, failure);
|
|
73
73
|
return lines;
|
|
74
74
|
}
|
|
75
|
+
/* AUTHENTICATE XOAUTH2 with the base64 SASL response given inline (initial
|
|
76
|
+
response, which Gmail and Outlook accept). On success the server answers the
|
|
77
|
+
tag with OK. On failure it first sends a `+ <base64 error>` challenge and
|
|
78
|
+
waits for an empty line before the tagged NO, so we finish that exchange and
|
|
79
|
+
then surface the refusal, rather than hang. */
|
|
80
|
+
async authenticateXoauth2(initial, failure) {
|
|
81
|
+
const tag = `c${++this.#n}`;
|
|
82
|
+
this.#socket.write(`${tag} AUTHENTICATE XOAUTH2 ${initial}\r\n`);
|
|
83
|
+
let lines = await this.#until((l) => l.startsWith(`${tag} `) || l.startsWith('+ '));
|
|
84
|
+
if ((lines.at(-1) ?? '').startsWith('+ ')) {
|
|
85
|
+
this.#socket.write('\r\n');
|
|
86
|
+
lines = await this.#until((l) => l.startsWith(`${tag} `));
|
|
87
|
+
}
|
|
88
|
+
if (!new RegExp(`^${tag} OK`, 'i').test(lines.at(-1) ?? '')) throw new Refusal(502, failure);
|
|
89
|
+
return lines;
|
|
90
|
+
}
|
|
75
91
|
}
|
package/server/mailbox.mjs
CHANGED
|
@@ -21,8 +21,18 @@ import { connect as tlsConnect } from 'node:tls';
|
|
|
21
21
|
import { mkdirSync, readdirSync, writeFileSync, renameSync, rmSync, existsSync } from 'node:fs';
|
|
22
22
|
import { Refusal } from './conversations.mjs';
|
|
23
23
|
import { Exchange, quoted } from './imap.mjs';
|
|
24
|
-
import { readSettings, TIMEOUT_MS } from './signin.mjs';
|
|
24
|
+
import { readSettings, oauthSettings, imapAuthenticate, PROVIDER_IMAP, TIMEOUT_MS } from './signin.mjs';
|
|
25
25
|
import { isConversationName } from './names.mjs';
|
|
26
|
+
import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState } from './oauth.mjs';
|
|
27
|
+
|
|
28
|
+
/* The loopback address the provider sends the code back to. Nothing listens on it:
|
|
29
|
+
the person's browser lands there (a page that will not load), and they copy the
|
|
30
|
+
address -- which carries the code -- back into Clavarium. Desktop OAuth clients
|
|
31
|
+
(Thunderbird's) accept any 127.0.0.1 port, and the same address is used again to
|
|
32
|
+
trade the code, so it only has to be constant. */
|
|
33
|
+
const REDIRECT = 'http://127.0.0.1:47813/';
|
|
34
|
+
const PENDING_MS = 10 * 60_000;
|
|
35
|
+
const PENDING_MAX = 20;
|
|
26
36
|
|
|
27
37
|
export const MESSAGES = 50;
|
|
28
38
|
/* A message is kept up to this size; a longer one is cut (its text comes first). */
|
|
@@ -33,13 +43,13 @@ const SYNC_TIMEOUT_MS = TIMEOUT_MS * 6;
|
|
|
33
43
|
/* ---------- reading ---------- */
|
|
34
44
|
|
|
35
45
|
/* The most recent messages, oldest first: [{ uid, receivedAt, raw }]. */
|
|
36
|
-
export async function recentMessages(settings, { connect = tlsConnect, ca, limit = MESSAGES } = {}) {
|
|
46
|
+
export async function recentMessages(settings, { connect = tlsConnect, ca, limit = MESSAGES, fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
37
47
|
const socket = connect({ host: settings.host, port: settings.port, servername: settings.host, ...(ca ? { ca } : {}) });
|
|
38
48
|
const timer = setTimeout(() => socket.destroy(new Error('timeout')), SYNC_TIMEOUT_MS);
|
|
39
49
|
try {
|
|
40
50
|
const imap = new Exchange(socket, limit * (MESSAGE_BYTES + 4096) + 2_000_000);
|
|
41
51
|
await imap.greeting();
|
|
42
|
-
await imap
|
|
52
|
+
await imapAuthenticate(imap, settings, { fetch: fetchImpl });
|
|
43
53
|
await imap.command('EXAMINE INBOX', 'The inbox could not be opened.');
|
|
44
54
|
const found = await imap.command('UID SEARCH ALL', 'The mailbox could not be searched.');
|
|
45
55
|
const uids = (found.find((l) => /^\* SEARCH/i.test(l)) ?? '').split(' ').slice(2).map(Number).filter((n) => Number.isInteger(n) && n > 0).slice(-limit);
|
|
@@ -115,13 +125,13 @@ export function writeFolder(folder, user, messages) {
|
|
|
115
125
|
/* ---------- the mailboxes kept ---------- */
|
|
116
126
|
|
|
117
127
|
export class Mailboxes {
|
|
118
|
-
#store; #vault; #resources; #reader; #busy = new Set();
|
|
128
|
+
#store; #vault; #resources; #reader; #fetch; #pending = new Map(); #busy = new Set();
|
|
119
129
|
|
|
120
|
-
constructor({ store, vault, resources, reader = recentMessages }) { this.#store = store; this.#vault = vault; this.#resources = resources; this.#reader = reader; }
|
|
130
|
+
constructor({ store, vault, resources, reader = recentMessages, fetch = globalThis.fetch }) { this.#store = store; this.#vault = vault; this.#resources = resources; this.#reader = reader; this.#fetch = fetch; }
|
|
121
131
|
|
|
122
132
|
/* What the page may know. Never the password. */
|
|
123
133
|
list() {
|
|
124
|
-
return this.#store.all().map((m) => ({ name: m.name, host: m.host, port: m.port ?? 993, user: m.user, messages: m.messages ?? 0, syncedAt: m.syncedAt ?? null, failure: m.failure ?? null }));
|
|
134
|
+
return this.#store.all().map((m) => ({ name: m.name, host: m.host, port: m.port ?? 993, user: m.user, provider: m.provider ?? null, messages: m.messages ?? 0, syncedAt: m.syncedAt ?? null, failure: m.failure ?? null }));
|
|
125
135
|
}
|
|
126
136
|
|
|
127
137
|
/* Adds a mailbox after proving it can be read, as a folder of that name. */
|
|
@@ -129,14 +139,53 @@ export class Mailboxes {
|
|
|
129
139
|
const name = String(body?.name ?? '');
|
|
130
140
|
if (!isConversationName(name)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
|
|
131
141
|
if (this.#resources.list().some((r) => r.name === name)) throw new Refusal(409, 'A folder already has this name.');
|
|
132
|
-
const settings = readSettings(body);
|
|
142
|
+
const settings = body?.provider ? oauthSettings(body) : readSettings(body);
|
|
133
143
|
const messages = await this.#reader(settings);
|
|
134
144
|
await this.#resources.create({ name, type: 'mailbox' });
|
|
135
|
-
this.#store.put({ name, host: settings.host, port: settings.port, user: settings.user, sealed: this.#vault.seal(settings.password) });
|
|
145
|
+
this.#store.put({ name, host: settings.host, port: settings.port, user: settings.user, provider: settings.provider, sealed: this.#vault.seal(settings.password) });
|
|
136
146
|
this.#write(name, settings.user, messages);
|
|
137
147
|
return this.list().find((m) => m.name === name);
|
|
138
148
|
}
|
|
139
149
|
|
|
150
|
+
/* Start connecting a mailbox by token: build the provider's consent page and
|
|
151
|
+
keep the state and PKCE verifier until the person pastes the address back. */
|
|
152
|
+
consent({ name, provider, user }) {
|
|
153
|
+
const nm = String(name ?? '');
|
|
154
|
+
if (!isConversationName(nm)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
|
|
155
|
+
if (this.#resources.list().some((r) => r.name === nm)) throw new Refusal(409, 'A folder already has this name.');
|
|
156
|
+
if (!PROVIDER_IMAP[String(provider ?? '')]) throw new Refusal(400, 'Choose Gmail or Microsoft.');
|
|
157
|
+
const address = String(user ?? '').trim();
|
|
158
|
+
if (address === '' || address.length > 200) throw new Refusal(400, 'The mailbox needs its email address.');
|
|
159
|
+
this.#sweepPending();
|
|
160
|
+
if (this.#pending.size >= PENDING_MAX) throw new Refusal(429, 'Too many connections in progress; try again shortly.');
|
|
161
|
+
const { clientId } = thunderbird(provider);
|
|
162
|
+
const state = newState();
|
|
163
|
+
const { verifier, challenge } = pkcePair();
|
|
164
|
+
const url = consentUrl(provider, { clientId, redirectUri: REDIRECT, scope: scopeFor(provider, ['mail']), state, codeChallenge: challenge, loginHint: address });
|
|
165
|
+
this.#pending.set(state, { name: nm, provider: String(provider), user: address, verifier, at: Date.now() });
|
|
166
|
+
return { url };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/* Finish it: from the pasted address, read the code, trade it for a refresh
|
|
170
|
+
token, and add the mailbox (which proves it can be read). */
|
|
171
|
+
async connect({ redirected }) {
|
|
172
|
+
this.#sweepPending();
|
|
173
|
+
let state;
|
|
174
|
+
try { state = new URL(String(redirected ?? '').trim()).searchParams.get('state'); } catch { throw new Refusal(400, 'Paste the whole address from the bar, after you allow.'); }
|
|
175
|
+
const p = state && this.#pending.get(state);
|
|
176
|
+
if (!p) throw new Refusal(400, 'This connection has expired or was already used; start it again.');
|
|
177
|
+
this.#pending.delete(state);
|
|
178
|
+
let code;
|
|
179
|
+
try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
|
|
180
|
+
const { clientId, clientSecret } = thunderbird(p.provider);
|
|
181
|
+
let refreshToken;
|
|
182
|
+
try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
|
|
183
|
+
catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
|
|
184
|
+
return this.add({ name: p.name, provider: p.provider, user: p.user, refresh: refreshToken });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
#sweepPending() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
|
|
188
|
+
|
|
140
189
|
#write(name, user, messages) {
|
|
141
190
|
writeFolder(this.#resources.folder(name), user, messages);
|
|
142
191
|
this.#store.patch(name, { messages: messages.length, syncedAt: new Date().toISOString(), failure: undefined });
|
|
@@ -150,7 +199,7 @@ export class Mailboxes {
|
|
|
150
199
|
if (this.#busy.has(name)) return this.list().find((x) => x.name === name);
|
|
151
200
|
this.#busy.add(name);
|
|
152
201
|
try {
|
|
153
|
-
const messages = await this.#reader({ host: m.host, port: m.port, user: m.user, password: this.#vault.open(m.sealed) });
|
|
202
|
+
const messages = await this.#reader({ host: m.host, port: m.port, user: m.user, provider: m.provider, password: this.#vault.open(m.sealed) });
|
|
154
203
|
this.#write(name, m.user, messages);
|
|
155
204
|
} catch (error) {
|
|
156
205
|
this.#store.patch(name, { failure: error instanceof Refusal ? error.message : 'The mailbox could not be read.' });
|