meta-sovereign 0.49.18 → 0.50.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.
- package/README.hi.md +5 -2
- package/README.md +5 -2
- package/README.ru.md +5 -2
- package/README.zh.md +5 -2
- package/js/src/cli/browser-open.js +25 -0
- package/js/src/cli/contact-commands.js +42 -0
- package/js/src/cli/index.js +18 -4
- package/js/src/cli/trust-commands.js +76 -1
- package/js/src/index.d.ts +6 -0
- package/js/src/server/aggregate.js +12 -1
- package/js/src/server/confirmations.js +2 -1
- package/js/src/server/cors.js +33 -13
- package/js/src/server/hosted-ui.js +17 -10
- package/js/src/server/index.js +46 -13
- package/js/src/server/local-key-enclave.swift +98 -0
- package/js/src/server/local-key.js +85 -0
- package/js/src/server/local-tls.js +78 -16
- package/js/src/server/native-helper.js +100 -0
- package/js/src/server/routes-contacts-import.js +110 -0
- package/js/src/server/routes-derived.js +5 -2
- package/js/src/server/routes-passcode.js +5 -1
- package/js/src/sources/contacts-import.js +173 -0
- package/js/src/sources/system-contacts.js +66 -0
- package/js/src/sources/system-contacts.plist +7 -0
- package/js/src/sources/system-contacts.swift +74 -0
- package/js/src/sources/vcard.js +203 -0
- package/js/src/web/app.min.js +89 -89
- package/js/src/web/chat-account.js +38 -0
- package/js/src/web/chat-state.js +11 -2
- package/js/src/web/chat-view.js +2 -1
- package/js/src/web/chat-window.js +49 -12
- package/js/src/web/connection-guides.js +3 -0
- package/js/src/web/contacts-import.js +279 -0
- package/js/src/web/contacts-live.js +63 -0
- package/js/src/web/discover.js +32 -8
- package/js/src/web/dom.js +15 -0
- package/js/src/web/download/copy.js +4 -4
- package/js/src/web/locales/en-chat.js +2 -0
- package/js/src/web/locales/en.js +25 -2
- package/js/src/web/locales/hi-chat.js +2 -0
- package/js/src/web/locales/hi.js +27 -2
- package/js/src/web/locales/ru-chat.js +2 -0
- package/js/src/web/locales/ru.js +28 -2
- package/js/src/web/locales/zh-chat.js +1 -0
- package/js/src/web/locales/zh.js +25 -2
- package/js/src/web/views.js +74 -20
- package/js/src/web/web-mode-banner.js +3 -1
- package/js/src/web/web-mode.js +5 -9
- package/package.json +4 -2
package/README.hi.md
CHANGED
|
@@ -55,9 +55,11 @@ node js/bin/meta-sovereign.js serve
|
|
|
55
55
|
|
|
56
56
|
Package npm पर publish होने के बाद `npx -y meta-sovereign serve` (या `npm install -g meta-sovereign && meta-sovereign serve`) काम करेगा। तब तक toolchain के बिना server चलाने का तरीका desktop app (ऊपर) है।
|
|
57
57
|
|
|
58
|
-
दोनों backend default रूप से <http://127.0.0.1:8787> पर listen करते हैं। JS server hosted app के origin (`https://link-foundation.github.io`) को CORS headers के साथ जवाब देता है; दूसरे origins `meta-sovereign serve --allow-origin=<origins>` या `MS_ALLOW_ORIGINS` से allow करें। Safari `https` pages को `http://127.0.0.1` तक नहीं पहुँचने देता, लेकिन `https://127.0.0.1` तक पहुँचने देता है; server अब उसी port पर HTTPS का भी जवाब देता है और इसके लिए localhost का अपना certificate बनाता है। एक बार `node js/bin/meta-sovereign.js trust` चलाएँ (macOS login keychain में जोड़ता है; दूसरे systems पर certificate का path print होता है) या Safari में `https://127.0.0.1:8787/trust` खोलें और prompts follow करें — उसके बाद hosted app Safari में सीधे server से connect हो जाता है। Trust से पहले notice server का नाम
|
|
58
|
+
दोनों backend default रूप से <http://127.0.0.1:8787> पर listen करते हैं। JS server hosted app के origin (`https://link-foundation.github.io`) को CORS headers के साथ जवाब देता है; दूसरे origins `meta-sovereign serve --allow-origin=<origins>` या `MS_ALLOW_ORIGINS` से allow करें। Safari `https` pages को `http://127.0.0.1` तक नहीं पहुँचने देता, लेकिन `https://127.0.0.1` तक पहुँचने देता है; server अब उसी port पर HTTPS का भी जवाब देता है और इसके लिए localhost का अपना certificate बनाता है। एक बार `node js/bin/meta-sovereign.js trust` चलाएँ (macOS login keychain में जोड़ता है; दूसरे systems पर certificate का path print होता है) या Safari में `https://127.0.0.1:8787/trust` खोलें और prompts follow करें — उसके बाद hosted app Safari में सीधे server से connect हो जाता है। Trust से पहले notice server का नाम और **सर्वर पर भरोसा करें** (<https://127.0.0.1:8787/trust>) दिखाता है; localhost UI का link तभी मिलता है जब वह स्पष्ट रूप से enable हो। `--tls=false` / `MS_TLS=off` HTTPS बंद करता है। Safari trusted local HTTPS API से hosted app उपयोग करता है; localhost UI वैकल्पिक है। Hosted SPA `discoverServer()` से local server खोजता है (saved override → `127.0.0.1` ports)। अगर browser auto-connect नहीं करता, app में **Settings → Server** खोलें और binary द्वारा print किया गया URL paste करें।
|
|
59
59
|
|
|
60
|
-
Default UI hosted app है: `serve` उसका पता छापता है, <https://link-foundation.github.io/meta-sovereign/>, और app हमारे port 8787 पर server को खुद ढूँढ लेता है (वह 8788, 7001, 7002 और 3000 भी देखता है; किसी दूसरे port पर `serve` बताता है कि उसे **Settings → Server** में set करें), इसलिए server को web site host नहीं करनी पड़ती।
|
|
60
|
+
Default UI hosted app है: `serve` उसका पता छापता है, <https://link-foundation.github.io/meta-sovereign/>, और app हमारे port 8787 पर server को खुद ढूँढ लेता है (वह 8788, 7001, 7002 और 3000 भी देखता है; किसी दूसरे port पर `serve` बताता है कि उसे **Settings → Server** में set करें), इसलिए server को web site host नहीं करनी पड़ती। Default रूप से `/` GitHub Pages पर redirect करता है और server केवल API, sync transports और connection helpers देता है। बिना internet के लिए localhost web app वैकल्पिक है: `serve --local-ui=true` (या `MS_LOCAL_UI=on`) से enable करें; फिर वह <http://127.0.0.1:8787> पर मिलता है। Desktop shell अपना bundled UI स्पष्ट रूप से enable करता है। `--ui-url=<url>` (या `MS_UI_URL`) कोई दूसरी hosted copy बताता है, जैसे किसी fork का Pages, और उसके origin को अनुमति देता है।
|
|
61
|
+
|
|
62
|
+
macOS पर interactive `serve` पूरा setup करता है: इस installation की TLS key को Secure Enclave से protect करता है, certificate trust जाँचता है, जरूरत पर ही trust माँगता है और GitHub Pages app खोलता है। Headless launch: `node js/bin/meta-sovereign.js serve --trust=true --open=true`। `--trust=false` और `--open=false` से opt out करें। Swift helper को macOS Command Line Tools चाहिए; unsupported Mac पर `--hardware-key=false` स्पष्ट रूप से file key चुनता है। Hardware protection disk की key पर लागू है; Node key को memory में उपयोग करता है। नियम और सीमाएँ: [local server setup और security](docs/LOCAL-SERVER-SECURITY.md)।
|
|
61
63
|
|
|
62
64
|
## SPA को server से जोड़ें
|
|
63
65
|
|
|
@@ -78,6 +80,7 @@ SPA server को इस क्रम में चुनता है ([`js/src
|
|
|
78
80
|
- **एकीकृत इनबॉक्स**: VK, Telegram, X, WhatsApp, Facebook, Instagram, LinkedIn, ईमेल, GitHub, Upwork, PeoplePerHour और जॉब बोर्ड; जहाँ नेटवर्क अनुमति देता है वहाँ लाइव अपडेट (Telegram, VK Long Poll, incremental IMAP, GitHub), बाकी के लिए किसी भी आकार के आर्काइव का आयात।
|
|
79
81
|
- **Telegram के अपने ऐप जैसी चैट**: हर संदेश एक बार भेजा जाता है, डिलीवरी टिक, लाइव अपडेट और अंतराल के बाद catch-up, पढ़ा-चिह्न, cloud ड्राफ़्ट, reload के बाद भी बचे रहने वाले retry ([`docs/CHAT-REFERENCES.hi.md`](docs/CHAT-REFERENCES.hi.md))।
|
|
80
82
|
- **CRM**: किसी संपर्क के बारे में सब कुछ एक दृश्य में, अलग-अलग नेटवर्क पर वही व्यक्ति, communities और सदस्यताएँ, खोज, नियम से ऑडियंस (`friends:vk & chat:vk:… - list:blocked`)।
|
|
83
|
+
- **संपर्क आयात**: macOS Contacts (सिंक किए गए iCloud खातों सहित) या किसी भी प्लेटफ़ॉर्म के vCard निर्यात का पूर्वावलोकन करके आयात करें। दोबारा आयात करने पर रिकॉर्ड की पहचान बनी रहती है। निर्देशिका सिंक के दौरान अपडेट होती है और बिना संदेश वाले लोग भी दिखाती है। [संपर्क आयात](docs/CONTACTS-IMPORT.md) देखें।
|
|
81
84
|
- **Outreach, broadcast और ऑटोमेशन**: किसे, कब, किन शर्तों पर और किस पाठ से लिखना है; कौन क्या पाएगा इसका preview; डिफ़ॉल्ट रूप से सुरक्षित ड्राफ़्ट, या quiet hours, हर चैट का cooldown, दैनिक सीमा और opt-out सूची के साथ धीमी गति से स्वचालित भेजना। हर स्वचालित भेजना एक ही outbox से जाता है: अधिक से अधिक एक बार, और अस्पष्ट परिणाम अपने आप दोहराया नहीं जाता ([`docs/USER-GUIDE.hi.md`](docs/USER-GUIDE.hi.md), §11)।
|
|
82
85
|
- **Operator कतार और उत्तर**: अपठित संदेश चैट-दर-चैट, आपके पिछले उत्तरों से सुझाव (Tab एक चुनता है), पैटर्न और उत्तर के रूप, मिलते संदेश पर auto-reply।
|
|
83
86
|
- **व्यवसाय और community खाते**: VK community token Bots Long Poll चलाता है; Telegram Business के quick replies, स्वागत और अनुपस्थिति संदेश, कार्य-समय और chatbots।
|
package/README.md
CHANGED
|
@@ -55,9 +55,11 @@ node js/bin/meta-sovereign.js serve
|
|
|
55
55
|
|
|
56
56
|
Once the package is published to npm, `npx -y meta-sovereign serve` (or `npm install -g meta-sovereign && meta-sovereign serve`) will work. Until then, the desktop app (above) is the way to run the server without a toolchain.
|
|
57
57
|
|
|
58
|
-
Either backend listens on <http://127.0.0.1:8787> by default. The JS server answers the hosted app's origin (`https://link-foundation.github.io`) with CORS headers; allow other origins with `meta-sovereign serve --allow-origin=<origins>` or `MS_ALLOW_ORIGINS`. Safari does not let `https` pages reach `http://127.0.0.1`, but it allows `https://127.0.0.1`; the server also answers HTTPS on the same port with its own certificate for localhost — run `node js/bin/meta-sovereign.js trust` once (macOS adds it to the login keychain; other systems print the certificate path), or open `https://127.0.0.1:8787/trust` in Safari and follow the prompts, and the hosted app connects directly. Before trusting, the notice names the server
|
|
58
|
+
Either backend listens on <http://127.0.0.1:8787> by default. The JS server answers the hosted app's origin (`https://link-foundation.github.io`) with CORS headers; allow other origins with `meta-sovereign serve --allow-origin=<origins>` or `MS_ALLOW_ORIGINS`. Safari does not let `https` pages reach `http://127.0.0.1`, but it allows `https://127.0.0.1`; the server also answers HTTPS on the same port with its own certificate for localhost — run `node js/bin/meta-sovereign.js trust` once (macOS adds it to the login keychain; other systems print the certificate path), or open `https://127.0.0.1:8787/trust` in Safari and follow the prompts, and the hosted app connects directly. Before trusting, the notice names the server and offers **Trust the server** (<https://127.0.0.1:8787/trust>); it links a localhost UI only if that UI was explicitly enabled. `--tls=false` / `MS_TLS=off` turns HTTPS off. Safari uses the hosted app through the trusted local HTTPS API; the localhost UI is optional. The hosted SPA discovers the local server automatically through `discoverServer()` (saved override → `127.0.0.1` ports). If your browser does not auto-connect, open the in-app **Settings → Server** prompt and paste the URL the binary printed.
|
|
59
59
|
|
|
60
|
-
The hosted app is the default UI: `serve` prints its address, <https://link-foundation.github.io/meta-sovereign/>, and the app finds the server on our port 8787 by itself (it also looks at 8788, 7001, 7002 and 3000; on another port `serve` says to set it in **Settings → Server**), so the server does not have to host a web site.
|
|
60
|
+
The hosted app is the default UI: `serve` prints its address, <https://link-foundation.github.io/meta-sovereign/>, and the app finds the server on our port 8787 by itself (it also looks at 8788, 7001, 7002 and 3000; on another port `serve` says to set it in **Settings → Server**), so the server does not have to host a web site. By default `/` redirects to GitHub Pages and the server serves only its API, sync transports and connection helpers. To opt into a localhost web app for offline use, run `serve --local-ui=true` (or set `MS_LOCAL_UI=on`); that copy is then available at <http://127.0.0.1:8787>. Desktop shells explicitly enable their bundled UI. `--ui-url=<url>` (or `MS_UI_URL`) names another hosted copy, such as a fork's Pages, and allows its origin.
|
|
61
|
+
|
|
62
|
+
On macOS, interactive `serve` now handles the full setup: it protects this installation’s TLS key with Secure Enclave, detects existing certificate trust, requests trust only when needed, and opens the GitHub Pages app. For a headless launch use `node js/bin/meta-sovereign.js serve --trust=true --open=true`. `--trust=false` and `--open=false` opt out. The Swift helper needs the macOS Command Line Tools; `--hardware-key=false` explicitly opts into a file key on unsupported Macs. Hardware protection applies to the key on disk; Node uses it in memory. See [local server setup and security](docs/LOCAL-SERVER-SECURITY.md) for the exact access rules and limits.
|
|
61
63
|
|
|
62
64
|
## Connect the SPA to your server
|
|
63
65
|
|
|
@@ -78,6 +80,7 @@ The full user-facing flow — install nothing, install Rust server, install JS s
|
|
|
78
80
|
- **Unified inbox** across VK, Telegram, X, WhatsApp, Facebook, Instagram, LinkedIn, email, GitHub, Upwork, PeoplePerHour and job boards, with live updates where the network allows (Telegram, the VK Long Poll, incremental IMAP, GitHub) and full-size archive imports for the rest.
|
|
79
81
|
- **Chat that behaves like Telegram's own apps**: each message sent once, delivery ticks, live updates and catch-up after a gap, read marking, cloud drafts, retries that survive a reload. How the open-source Telegram, Signal and Element clients do it, pinned to the commits we read, is in [`docs/CHAT-REFERENCES.md`](docs/CHAT-REFERENCES.md).
|
|
80
82
|
- **CRM**: everything known about a contact in one view, the same person across networks, communities and memberships, search, audiences by rule (`friends:vk & chat:vk:… - list:blocked`).
|
|
83
|
+
- **Contact imports**: preview and import macOS Contacts (including synced iCloud accounts) or vCard exports from any platform; repeated imports keep stable identities. The directory updates during sync and includes people without messages. See [contact imports](docs/CONTACTS-IMPORT.md).
|
|
81
84
|
- **Outreach, broadcasts and automations**: who to message, when, on what conditions and with which text; a preview of who gets what; safe drafts by default or paced auto-send with quiet hours, a per-chat cooldown, daily caps and an opt-out list. Every automated send goes through one outbox, so it happens at most once and an unclear result is never retried by itself ([`docs/USER-GUIDE.md` §11](docs/USER-GUIDE.md#11-automations-message-people-by-rule-safely)).
|
|
82
85
|
- **Operator queue and replies**: walk unread messages chat by chat, reply suggestions from your own past answers (Tab takes one), patterns and reply variations, auto-replies on a matching message.
|
|
83
86
|
- **Business and community accounts**: a VK community token runs the Bots Long Poll; Telegram Business quick replies, greeting and away messages, hours and chatbots.
|
package/README.ru.md
CHANGED
|
@@ -55,9 +55,11 @@ node js/bin/meta-sovereign.js serve
|
|
|
55
55
|
|
|
56
56
|
Когда пакет будет опубликован в npm, заработают `npx -y meta-sovereign serve` (или `npm install -g meta-sovereign && meta-sovereign serve`). До тех пор запустить server без toolchain можно через desktop app (выше).
|
|
57
57
|
|
|
58
|
-
Оба backend по умолчанию слушают <http://127.0.0.1:8787>. JS server отвечает origin hosted app (`https://link-foundation.github.io`) с CORS headers; другие origins разрешаются через `meta-sovereign serve --allow-origin=<origins>` или `MS_ALLOW_ORIGINS`. Safari не пускает `https` страницы на `http://127.0.0.1`, но пускает на `https://127.0.0.1`; сервер теперь отвечает по HTTPS на том же порту с собственным сертификатом для localhost. Выполните `node js/bin/meta-sovereign.js trust` один раз (macOS добавляет сертификат в login keychain; на других системах печатается путь к сертификату) или откройте `https://127.0.0.1:8787/trust` в Safari и следуйте подсказкам — после этого hosted app в Safari подключается к серверу напрямую. До того уведомление называет
|
|
58
|
+
Оба backend по умолчанию слушают <http://127.0.0.1:8787>. JS server отвечает origin hosted app (`https://link-foundation.github.io`) с CORS headers; другие origins разрешаются через `meta-sovereign serve --allow-origin=<origins>` или `MS_ALLOW_ORIGINS`. Safari не пускает `https` страницы на `http://127.0.0.1`, но пускает на `https://127.0.0.1`; сервер теперь отвечает по HTTPS на том же порту с собственным сертификатом для localhost. Выполните `node js/bin/meta-sovereign.js trust` один раз (macOS добавляет сертификат в login keychain; на других системах печатается путь к сертификату) или откройте `https://127.0.0.1:8787/trust` в Safari и следуйте подсказкам — после этого hosted app в Safari подключается к серверу напрямую. До того уведомление называет сервер и предлагает **Доверять серверу** (<https://127.0.0.1:8787/trust>); ссылка на localhost-копию появляется только при её явном включении. `--tls=false` / `MS_TLS=off` отключает HTTPS. Safari использует размещённое приложение через доверенный локальный HTTPS API; localhost-интерфейс необязателен. Hosted SPA автоматически находит локальный сервер через `discoverServer()` (сохраненный override → порты `127.0.0.1`). Если браузер не подключился сам, откройте **Settings → Server** в приложении и вставьте URL, который напечатал сервер.
|
|
59
59
|
|
|
60
|
-
По умолчанию интерфейс — размещённое приложение: `serve` печатает его адрес, <https://link-foundation.github.io/meta-sovereign/>, а приложение само находит сервер на нашем порту 8787 (а также смотрит 8788, 7001, 7002 и 3000; на другом порту `serve` подскажет указать его в **Settings → Server**), так что серверу не нужно держать сайт.
|
|
60
|
+
По умолчанию интерфейс — размещённое приложение: `serve` печатает его адрес, <https://link-foundation.github.io/meta-sovereign/>, а приложение само находит сервер на нашем порту 8787 (а также смотрит 8788, 7001, 7002 и 3000; на другом порту `serve` подскажет указать его в **Settings → Server**), так что серверу не нужно держать сайт. По умолчанию `/` перенаправляет на GitHub Pages, а сервер предоставляет API, синхронизацию и вспомогательные маршруты подключения. Копия на localhost для работы без интернета включается отдельно: `serve --local-ui=true` (или `MS_LOCAL_UI=on`), после чего она доступна на <http://127.0.0.1:8787>. Desktop-оболочка явно включает свой встроенный интерфейс. `--ui-url=<url>` (или `MS_UI_URL`) задаёт другую размещённую копию, например Pages форка, и разрешает её origin.
|
|
61
|
+
|
|
62
|
+
В macOS интерактивный `serve` выполняет настройку целиком: защищает TLS-ключ этой установки через Secure Enclave, проверяет доверие сертификату, запрашивает его только при необходимости и открывает приложение на GitHub Pages. Без интерактивного терминала: `node js/bin/meta-sovereign.js serve --trust=true --open=true`. `--trust=false` и `--open=false` отключают эти действия. Для Swift-помощника нужны macOS Command Line Tools; `--hardware-key=false` явно выбирает файловый ключ на неподдерживаемом Mac. Аппаратная защита действует на диске; Node использует ключ в памяти. Правила и ограничения: [настройка и безопасность локального сервера](docs/LOCAL-SERVER-SECURITY.md).
|
|
61
63
|
|
|
62
64
|
## Подключение SPA к серверу
|
|
63
65
|
|
|
@@ -78,6 +80,7 @@ SPA выбирает сервер в таком порядке ([`js/src/web/dis
|
|
|
78
80
|
- **Единый inbox** для VK, Telegram, X, WhatsApp, Facebook, Instagram, LinkedIn, почты, GitHub, Upwork, PeoplePerHour и сайтов вакансий: живые обновления там, где сеть это позволяет (Telegram, VK Long Poll, инкрементальный IMAP, GitHub), и импорт архивов любого размера для остальных.
|
|
79
81
|
- **Чат, который ведёт себя как приложения Telegram**: каждое сообщение отправляется один раз, галочки доставки, живые обновления и догрузка после разрыва, отметки о прочтении, облачные черновики, повторы, переживающие перезагрузку ([`docs/CHAT-REFERENCES.ru.md`](docs/CHAT-REFERENCES.ru.md)).
|
|
80
82
|
- **CRM**: всё о контакте в одном окне, один и тот же человек в разных сетях, сообщества и членства, поиск, аудитории по правилам (`friends:vk & chat:vk:… - list:blocked`).
|
|
83
|
+
- **Импорт контактов**: предпросмотр и импорт из Контактов macOS (включая синхронизированные учётные записи iCloud) или файлов vCard на любой платформе; повторный импорт сохраняет идентичность записей. Список обновляется при синхронизации и включает людей без сообщений. См. [импорт контактов](docs/CONTACTS-IMPORT.md).
|
|
81
84
|
- **Рассылки, broadcast и автоматизации**: кому писать, когда, при каких условиях и каким текстом; предпросмотр, кто что получит; по умолчанию безопасные черновики или отправка с паузами, тихими часами, перерывом для каждого чата, дневными лимитами и списком отписавшихся. Каждая автоматическая отправка идёт через один outbox: не больше одного раза, а неясный результат сам не повторяется ([`docs/USER-GUIDE.ru.md`](docs/USER-GUIDE.ru.md), §11).
|
|
82
85
|
- **Очередь оператора и ответы**: непрочитанные сообщения чат за чатом, подсказки ответов из ваших прошлых ответов (Tab берёт подсказку), паттерны и варианты ответов, автоответы на подходящее сообщение.
|
|
83
86
|
- **Аккаунты бизнеса и сообществ**: токен сообщества VK запускает Bots Long Poll; Telegram Business: быстрые ответы, приветствие и сообщение об отсутствии, часы работы, чат-боты.
|
package/README.zh.md
CHANGED
|
@@ -55,9 +55,11 @@ node js/bin/meta-sovereign.js serve
|
|
|
55
55
|
|
|
56
56
|
包发布到 npm 之后,`npx -y meta-sovereign serve`(或 `npm install -g meta-sovereign && meta-sovereign serve`)才会可用。在此之前,不想装工具链的话可以使用桌面 app(见上文)。
|
|
57
57
|
|
|
58
|
-
两个后端默认监听 <http://127.0.0.1:8787>。JS 服务器会对托管 app 的 origin(`https://link-foundation.github.io`)返回 CORS 头;其他 origin 可以用 `meta-sovereign serve --allow-origin=<origins>` 或 `MS_ALLOW_ORIGINS` 允许。Safari 不允许 `https` 页面访问 `http://127.0.0.1`,但允许访问 `https://127.0.0.1`;服务器现在也在同一端口上提供 HTTPS 服务,并使用专为 localhost 颁发的自签名证书。运行一次 `node js/bin/meta-sovereign.js trust`(macOS:将证书添加到 login keychain;其他系统:打印证书路径),或在 Safari 中打开 `https://127.0.0.1:8787/trust` 并按提示操作,之后托管 app 在 Safari
|
|
58
|
+
两个后端默认监听 <http://127.0.0.1:8787>。JS 服务器会对托管 app 的 origin(`https://link-foundation.github.io`)返回 CORS 头;其他 origin 可以用 `meta-sovereign serve --allow-origin=<origins>` 或 `MS_ALLOW_ORIGINS` 允许。Safari 不允许 `https` 页面访问 `http://127.0.0.1`,但允许访问 `https://127.0.0.1`;服务器现在也在同一端口上提供 HTTPS 服务,并使用专为 localhost 颁发的自签名证书。运行一次 `node js/bin/meta-sovereign.js trust`(macOS:将证书添加到 login keychain;其他系统:打印证书路径),或在 Safari 中打开 `https://127.0.0.1:8787/trust` 并按提示操作,之后托管 app 在 Safari 中即可直接连接服务器。信任之前,提示会显示服务器地址及 **信任服务器**(<https://127.0.0.1:8787/trust>)链接;仅当显式启用 localhost 界面时才显示其链接。`--tls=false` / `MS_TLS=off` 可关闭 HTTPS。Safari 通过受信任的本地 HTTPS API 使用托管应用;localhost 界面是可选的。托管的 SPA 会通过 `discoverServer()` 自动发现本地服务器(保存的覆盖值 → `127.0.0.1` 端口)。如果浏览器没有自动连接,请打开应用内 **Settings → Server**,粘贴服务器打印的 URL。
|
|
59
59
|
|
|
60
|
-
默认界面是托管的应用:`serve` 会打印其地址 <https://link-foundation.github.io/meta-sovereign/>,应用会自行在我们的端口 8787 上找到服务器(也会查看 8788、7001、7002 和 3000;若使用其他端口,`serve` 会提示在 **Settings → Server**
|
|
60
|
+
默认界面是托管的应用:`serve` 会打印其地址 <https://link-foundation.github.io/meta-sovereign/>,应用会自行在我们的端口 8787 上找到服务器(也会查看 8788、7001、7002 和 3000;若使用其他端口,`serve` 会提示在 **Settings → Server** 中设置),因此服务器无需自己托管网站。默认情况下,`/` 重定向到 GitHub Pages,服务器只提供 API、同步传输和连接辅助路由。如需离线使用 localhost 网页,请显式运行 `serve --local-ui=true`(或设置 `MS_LOCAL_UI=on`),随后可在 <http://127.0.0.1:8787> 访问该副本。桌面壳会显式启用其内置界面。`--ui-url=<url>`(或 `MS_UI_URL`)指定另一个托管副本(例如某个 fork 的 Pages),并允许其 origin。
|
|
61
|
+
|
|
62
|
+
在 macOS 交互式终端中,`serve` 会完成整个设置:使用 Secure Enclave 保护本次安装的 TLS 私钥,检测证书是否已受信任,仅在需要时请求信任,并打开 GitHub Pages 应用。无交互终端时可运行 `node js/bin/meta-sovereign.js serve --trust=true --open=true`。`--trust=false` 和 `--open=false` 可关闭相应操作。Swift 辅助程序需要 macOS Command Line Tools;不支持的 Mac 可显式使用 `--hardware-key=false` 选择文件密钥。硬件保护针对磁盘上的密钥;Node 在内存中使用密钥。详见[本地服务器设置与安全](docs/LOCAL-SERVER-SECURITY.md)。
|
|
61
63
|
|
|
62
64
|
## 将 SPA 连接到服务器
|
|
63
65
|
|
|
@@ -78,6 +80,7 @@ SPA 按以下顺序选择服务器([`js/src/web/discover.js`](js/src/web/disco
|
|
|
78
80
|
- **统一收件箱**:覆盖 VK、Telegram、X、WhatsApp、Facebook、Instagram、LinkedIn、电子邮件、GitHub、Upwork、PeoplePerHour 和招聘网站;网络允许时实时更新(Telegram、VK Long Poll、增量 IMAP、GitHub),其余可导入任意大小的存档。
|
|
79
81
|
- **像 Telegram 官方应用一样的聊天**:每条消息只发送一次,送达对勾,实时更新与断线后补齐,已读标记,云端草稿,刷新后仍保留的重试([`docs/CHAT-REFERENCES.zh.md`](docs/CHAT-REFERENCES.zh.md))。
|
|
80
82
|
- **CRM**:一个视图看到联系人的全部信息,跨网络识别同一个人,社区与成员关系,搜索,按规则定义受众(`friends:vk & chat:vk:… - list:blocked`)。
|
|
83
|
+
- **导入联系人**:预览并导入 macOS 通讯录(包括已同步的 iCloud 账户)或任何平台导出的 vCard;重复导入保留记录身份。目录在同步期间自动更新,也包含没有消息的联系人。参见[联系人导入](docs/CONTACTS-IMPORT.md)。
|
|
81
84
|
- **外联、群发与自动化**:给谁发、何时发、在什么条件下发、发什么内容;预览谁会收到什么;默认生成安全草稿,或按节奏自动发送,并有安静时段、每个聊天的冷却期、每日上限和退订名单。每次自动发送都经过同一个发件箱:最多发送一次,结果不明时不会自行重试([`docs/USER-GUIDE.zh.md`](docs/USER-GUIDE.zh.md) 第 11 节)。
|
|
82
85
|
- **Operator 队列与回复**:逐个聊天处理未读消息,根据您以往的回答给出回复建议(按 Tab 采用),模式与回复变体,对匹配消息自动回复。
|
|
83
86
|
- **企业与社区账号**:VK 社区令牌运行 Bots Long Poll;Telegram Business 的快捷回复、问候与离开消息、营业时间和聊天机器人。
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Open the hosted face of the app, including when the local UI is enabled.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
|
|
4
|
+
export const maybeOpenHostedApp = (args, handle, log) => {
|
|
5
|
+
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
6
|
+
const enabled =
|
|
7
|
+
args.open === undefined ? interactive : String(args.open) !== 'false';
|
|
8
|
+
if (args.foreground === false || !enabled) {
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
const [program, ...prefix] =
|
|
12
|
+
process.platform === 'darwin'
|
|
13
|
+
? ['open']
|
|
14
|
+
: process.platform === 'win32'
|
|
15
|
+
? ['rundll32.exe', 'url.dll,FileProtocolHandler']
|
|
16
|
+
: ['xdg-open'];
|
|
17
|
+
const browser = spawn(program, [...prefix, handle.uiUrl], {
|
|
18
|
+
detached: true,
|
|
19
|
+
stdio: 'ignore',
|
|
20
|
+
});
|
|
21
|
+
browser.on('error', () =>
|
|
22
|
+
log(`open the app in your browser → ${handle.uiUrl}`)
|
|
23
|
+
);
|
|
24
|
+
browser.unref();
|
|
25
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Local address-book imports, with the same parser and plan as the app.
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import { decodeVcard, parseVcard } from '../sources/vcard.js';
|
|
4
|
+
import { readSystemContacts } from '../sources/system-contacts.js';
|
|
5
|
+
import {
|
|
6
|
+
planContactsImport,
|
|
7
|
+
applyContactsImport,
|
|
8
|
+
} from '../sources/contacts-import.js';
|
|
9
|
+
|
|
10
|
+
export const CONTACTS_HELP = ` contacts-import [--file=<contacts.vcf> | --system] [--store=<dir>] [--preview]
|
|
11
|
+
import a vCard export or macOS Contacts (including synced iCloud accounts); nothing is uploaded`;
|
|
12
|
+
|
|
13
|
+
export const createContactCommands = ({ openStore }) => ({
|
|
14
|
+
'contacts-import': async (args, log) => {
|
|
15
|
+
const system = args.system === true || args.system === 'true';
|
|
16
|
+
if (system === Boolean(args.file)) {
|
|
17
|
+
log('choose --file=<contacts.vcf> or --system');
|
|
18
|
+
return 1;
|
|
19
|
+
}
|
|
20
|
+
const storeDir = args.store ?? '.meta-sovereign';
|
|
21
|
+
const store = await openStore(storeDir);
|
|
22
|
+
try {
|
|
23
|
+
const rows = system
|
|
24
|
+
? await readSystemContacts(storeDir)
|
|
25
|
+
: parseVcard(decodeVcard(await fs.readFile(args.file)));
|
|
26
|
+
const plan = await planContactsImport(store, rows, {
|
|
27
|
+
source: system ? 'system' : 'vcard',
|
|
28
|
+
});
|
|
29
|
+
const preview = args.preview === true || args.preview === 'true';
|
|
30
|
+
log(
|
|
31
|
+
JSON.stringify(
|
|
32
|
+
preview
|
|
33
|
+
? { preview: true, ...plan.stats }
|
|
34
|
+
: await applyContactsImport(store, plan)
|
|
35
|
+
)
|
|
36
|
+
);
|
|
37
|
+
return 0;
|
|
38
|
+
} finally {
|
|
39
|
+
await store.close?.();
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
});
|
package/js/src/cli/index.js
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import path from 'node:path';
|
|
17
|
+
import { maybeOpenHostedApp } from './browser-open.js';
|
|
18
|
+
import { CONTACTS_HELP, createContactCommands } from './contact-commands.js';
|
|
17
19
|
import { promises as fs } from 'node:fs';
|
|
18
20
|
import { parseArgs } from './lino-args.js';
|
|
19
21
|
import { CV_HELP, createCvCommands } from './cv-commands.js';
|
|
@@ -25,7 +27,11 @@ import {
|
|
|
25
27
|
GREETINGS_HELP,
|
|
26
28
|
createGreetingCommands,
|
|
27
29
|
} from './greetings-commands.js';
|
|
28
|
-
import {
|
|
30
|
+
import {
|
|
31
|
+
TRUST_HELP,
|
|
32
|
+
createTrustCommands,
|
|
33
|
+
setupLocalCertificate,
|
|
34
|
+
} from './trust-commands.js';
|
|
29
35
|
import {
|
|
30
36
|
MIGRATE_HELP,
|
|
31
37
|
SCHEMA_ERROR_CODES,
|
|
@@ -83,10 +89,13 @@ Commands:
|
|
|
83
89
|
backup --store=<dir> --archive=<dir> [--keep=<n>]
|
|
84
90
|
restore --file=<path> --store=<dir> [--replace]
|
|
85
91
|
passcode --clear [--store=<dir>] (remove a forgotten local passcode)
|
|
86
|
-
serve [--port=<n>] [--store=<dir>] [--allow-origin=<origins|none>] [--ui-url=<url>] [--local-ui=
|
|
92
|
+
serve [--port=<n>] [--store=<dir>] [--allow-origin=<origins|none>] [--ui-url=<url>] [--local-ui=true] [--tls=false] [--trust=true|false] [--hardware-key=false] [--open=true|false] [--quiet-logs]
|
|
93
|
+
open https://link-foundation.github.io/meta-sovereign/; the localhost UI is opt-in
|
|
94
|
+
on macOS: protect the TLS key with Secure Enclave; detect trust, set it up once in an interactive terminal
|
|
87
95
|
verbose logs are written to <store>/logs/meta-sovereign.log by default
|
|
88
96
|
https is served on the same port (for Safari); --tls=false or MS_TLS=off turns it off
|
|
89
97
|
${TRUST_HELP}
|
|
98
|
+
${CONTACTS_HELP}
|
|
90
99
|
sources
|
|
91
100
|
source-pull --source=<name> [--protocol=<p>] [--host=<mail-host>] [--owner=<o>] [--repo=<r>] [--state=<s>] [--offset=<n>] [--limit=<n>] [--store=<dir>]
|
|
92
101
|
email-send --protocol=<gmail|microsoft-graph|jmap|smtp> --to=<email> --subject=<s> --text=<body> [--host=<mail-host>]
|
|
@@ -196,7 +205,7 @@ const serveOptions = (args) => ({
|
|
|
196
205
|
// back to MS_ALLOW_ORIGINS and then the built-in defaults.
|
|
197
206
|
...(args['allow-origin'] ? { allowOrigins: args['allow-origin'] } : {}),
|
|
198
207
|
// The hosted app is the UI; the server's own copy is a fallback
|
|
199
|
-
//
|
|
208
|
+
// enabled with `--local-ui=true` (R-Y58, R-Y59).
|
|
200
209
|
...(args['ui-url'] ? { uiUrl: args['ui-url'] } : {}),
|
|
201
210
|
...(args['local-ui'] !== undefined ? { localUi: args['local-ui'] } : {}),
|
|
202
211
|
// https beside http on the same port, for Safari (R-Y64).
|
|
@@ -221,7 +230,7 @@ const logAddresses = (handle, log) => {
|
|
|
221
230
|
log(
|
|
222
231
|
handle.localUi
|
|
223
232
|
? `local copy (fallback, e.g. for Safari or offline) → ${origin}/`
|
|
224
|
-
: `local copy off: ${origin}/ opens the app above`
|
|
233
|
+
: `local copy off: ${origin}/ opens the app above (enable with --local-ui=true)`
|
|
225
234
|
);
|
|
226
235
|
};
|
|
227
236
|
|
|
@@ -242,6 +251,9 @@ const serveCmd = async (args, log) => {
|
|
|
242
251
|
}
|
|
243
252
|
let handle;
|
|
244
253
|
try {
|
|
254
|
+
if (args.foreground !== false) {
|
|
255
|
+
await setupLocalCertificate(args, log);
|
|
256
|
+
}
|
|
245
257
|
handle = await startServer({
|
|
246
258
|
port: Number(args.port ?? 8787),
|
|
247
259
|
storeDir,
|
|
@@ -256,6 +268,7 @@ const serveCmd = async (args, log) => {
|
|
|
256
268
|
return 1;
|
|
257
269
|
}
|
|
258
270
|
logAddresses(handle, log);
|
|
271
|
+
maybeOpenHostedApp(args, handle, log);
|
|
259
272
|
if (serverLog) {
|
|
260
273
|
log(`verbose logs → ${serverLog.file}`);
|
|
261
274
|
}
|
|
@@ -816,6 +829,7 @@ const COMMANDS = {
|
|
|
816
829
|
...createGreetingCommands({ openStore }),
|
|
817
830
|
// Let Safari trust the server's own certificate (R-Y64).
|
|
818
831
|
...createTrustCommands(),
|
|
832
|
+
...createContactCommands({ openStore }),
|
|
819
833
|
// Bring a store to the current data schema, or look first (R-Z17).
|
|
820
834
|
...createMigrateCommands(),
|
|
821
835
|
help: async (_a, log) => {
|
|
@@ -15,11 +15,81 @@ import { spawnSync } from 'node:child_process';
|
|
|
15
15
|
import os from 'node:os';
|
|
16
16
|
import path from 'node:path';
|
|
17
17
|
|
|
18
|
-
import { loadLocalTls } from '../server/local-tls.js';
|
|
18
|
+
import { canShareTlsPort, loadLocalTls } from '../server/local-tls.js';
|
|
19
|
+
import { createDeviceKeyProtector } from '../server/local-key.js';
|
|
19
20
|
|
|
20
21
|
export const TRUST_HELP = ` trust [--store=<dir>] [--remove=true]
|
|
21
22
|
lets Safari use the server from the hosted app: trusts the server's own certificate (localhost and 127.0.0.1 only) once`;
|
|
22
23
|
|
|
24
|
+
const enabled = (value, fallback = true) =>
|
|
25
|
+
value === undefined ? fallback : String(value) !== 'false';
|
|
26
|
+
|
|
27
|
+
/** Ask macOS to evaluate this exact leaf certificate for local TLS only. */
|
|
28
|
+
export const certificateIsTrusted = (
|
|
29
|
+
certPath,
|
|
30
|
+
{ platform = process.platform, run = spawnSync } = {}
|
|
31
|
+
) =>
|
|
32
|
+
platform === 'darwin' &&
|
|
33
|
+
['localhost', '127.0.0.1'].every(
|
|
34
|
+
(name) =>
|
|
35
|
+
run(
|
|
36
|
+
'security',
|
|
37
|
+
['verify-cert', '-c', certPath, '-p', 'ssl', '-n', name, '-L', '-q'],
|
|
38
|
+
{ stdio: 'ignore', timeout: 10_000 }
|
|
39
|
+
).status === 0
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
/** Full certificate setup used by serve; tests inject every OS operation. */
|
|
43
|
+
export const setupLocalCertificate = async (args, log, options = {}) => {
|
|
44
|
+
const {
|
|
45
|
+
platform,
|
|
46
|
+
deviceProtector,
|
|
47
|
+
load,
|
|
48
|
+
trusted,
|
|
49
|
+
trust,
|
|
50
|
+
interactive,
|
|
51
|
+
supported,
|
|
52
|
+
} = {
|
|
53
|
+
platform: process.platform,
|
|
54
|
+
deviceProtector: createDeviceKeyProtector,
|
|
55
|
+
load: loadLocalTls,
|
|
56
|
+
trusted: certificateIsTrusted,
|
|
57
|
+
trust: (a, out) => createTrustCommands().trust(a, out),
|
|
58
|
+
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
59
|
+
supported: canShareTlsPort(),
|
|
60
|
+
...options,
|
|
61
|
+
};
|
|
62
|
+
if (!enabled(args.tls) || process.env.MS_TLS === 'off' || !supported) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
const storeDir = args.store ?? '.meta-sovereign';
|
|
66
|
+
const protector =
|
|
67
|
+
enabled(args['hardware-key']) && platform === 'darwin'
|
|
68
|
+
? await deviceProtector(storeDir)
|
|
69
|
+
: null;
|
|
70
|
+
const local = await load(storeDir, { protector });
|
|
71
|
+
log(`local TLS identity (SHA-256) → ${local.fingerprint}`);
|
|
72
|
+
log(`local TLS key protection → ${local.protection}`);
|
|
73
|
+
if (platform !== 'darwin' || trusted(local.certPath)) {
|
|
74
|
+
return local;
|
|
75
|
+
}
|
|
76
|
+
// Interactive serve sets up Safari by default; headless runs opt in.
|
|
77
|
+
const shouldTrust = enabled(args.trust, interactive);
|
|
78
|
+
if (shouldTrust) {
|
|
79
|
+
const code = await trust({ store: storeDir }, log);
|
|
80
|
+
if (code !== 0) {
|
|
81
|
+
log(
|
|
82
|
+
'certificate trust was not granted; use the app’s Trust the server link when ready'
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
log(
|
|
87
|
+
'Safari setup → run serve --trust=true, or node js/bin/meta-sovereign.js trust'
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
return local;
|
|
91
|
+
};
|
|
92
|
+
|
|
23
93
|
const runCommand = (cmd, args) => {
|
|
24
94
|
const done = spawnSync(cmd, args, { stdio: 'inherit' });
|
|
25
95
|
return done.status ?? 1;
|
|
@@ -54,6 +124,7 @@ export const createTrustCommands = ({
|
|
|
54
124
|
run = runCommand,
|
|
55
125
|
platform = process.platform,
|
|
56
126
|
home = os.homedir(),
|
|
127
|
+
trusted = certificateIsTrusted,
|
|
57
128
|
} = {}) => ({
|
|
58
129
|
trust: async (args, log) => {
|
|
59
130
|
const remove = String(args.remove ?? 'false') !== 'false';
|
|
@@ -62,6 +133,10 @@ export const createTrustCommands = ({
|
|
|
62
133
|
log(manualSteps(certPath));
|
|
63
134
|
return 0;
|
|
64
135
|
}
|
|
136
|
+
if (!remove && trusted(certPath)) {
|
|
137
|
+
log('this local server certificate is already trusted');
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
65
140
|
log(
|
|
66
141
|
remove
|
|
67
142
|
? `no longer trusting ${certPath}`
|
package/js/src/index.d.ts
CHANGED
|
@@ -21,6 +21,12 @@ export declare const runCli: (argv: string[]) => Promise<number>;
|
|
|
21
21
|
export declare const startServer: (opts: {
|
|
22
22
|
port?: number;
|
|
23
23
|
storeDir?: string;
|
|
24
|
+
/** Serve the bundled web UI; defaults to false (GitHub Pages is the UI). */
|
|
25
|
+
localUi?: boolean | string;
|
|
26
|
+
/** Override the default GitHub Pages app URL. */
|
|
27
|
+
uiUrl?: string;
|
|
28
|
+
/** Inject a local system address-book reader; used only after an import request. */
|
|
29
|
+
systemContactsReader?: (storeDir: string) => Promise<unknown[]>;
|
|
24
30
|
emailLiveFactory?: (config: unknown) => unknown;
|
|
25
31
|
/** Periodic pull of a connected mailbox; `false` turns it off. */
|
|
26
32
|
emailPoll?: false | { intervalMs?: number; firstMs?: number };
|
|
@@ -63,7 +63,18 @@ const addPerson = (entry, person) => {
|
|
|
63
63
|
entry.name ??= person.name ?? null;
|
|
64
64
|
entry.handle ??= person.handle ?? null;
|
|
65
65
|
// A private chat is addressed by the person's own id.
|
|
66
|
-
|
|
66
|
+
if (person.source !== 'addressbook') {
|
|
67
|
+
entry.open ??= { source: person.source, chat: String(person.user) };
|
|
68
|
+
}
|
|
69
|
+
if (person.emails?.length) {
|
|
70
|
+
entry.emails = person.emails;
|
|
71
|
+
}
|
|
72
|
+
if (person.phones?.length) {
|
|
73
|
+
entry.phones = person.phones;
|
|
74
|
+
}
|
|
75
|
+
if (person.organization) {
|
|
76
|
+
entry.organization = person.organization;
|
|
77
|
+
}
|
|
67
78
|
if (person.contact) {
|
|
68
79
|
entry.contact = true;
|
|
69
80
|
}
|
|
@@ -46,6 +46,7 @@ export const withoutToken = (body = {}) => {
|
|
|
46
46
|
export const createConfirmations = ({
|
|
47
47
|
ttlMs = CONFIRM_TTL_MS,
|
|
48
48
|
now = () => Date.now(),
|
|
49
|
+
maxPending = MAX_PENDING,
|
|
49
50
|
} = {}) => {
|
|
50
51
|
const pending = new Map();
|
|
51
52
|
const digest = (action, payload) =>
|
|
@@ -55,7 +56,7 @@ export const createConfirmations = ({
|
|
|
55
56
|
const prune = () => {
|
|
56
57
|
const at = now();
|
|
57
58
|
for (const [token, entry] of pending) {
|
|
58
|
-
if (entry.expires <= at || pending.size
|
|
59
|
+
if (entry.expires <= at || pending.size >= maxPending) {
|
|
59
60
|
pending.delete(token);
|
|
60
61
|
}
|
|
61
62
|
}
|
package/js/src/server/cors.js
CHANGED
|
@@ -15,23 +15,23 @@
|
|
|
15
15
|
* - origins on the allow-list get `Access-Control-Allow-Origin`
|
|
16
16
|
* echoed back, plus a preflight answer that also opts in to
|
|
17
17
|
* Chrome's Private Network Access check;
|
|
18
|
-
* - every other origin gets no CORS headers
|
|
19
|
-
*
|
|
18
|
+
* - every other origin gets no CORS headers and a 403 on every method,
|
|
19
|
+
* so a random website cannot
|
|
20
20
|
* post `text/plain` bodies (which skip preflight) to the store.
|
|
21
21
|
*
|
|
22
|
-
* The allow-list defaults to the official
|
|
23
|
-
*
|
|
22
|
+
* The allow-list defaults only to the official GitHub Pages origin.
|
|
23
|
+
* Same-origin localhost is checked separately. Other embedders explicitly
|
|
24
|
+
* configure their WebView origin. The list can be replaced with the
|
|
24
25
|
* `MS_ALLOW_ORIGINS` environment variable or `serve --allow-origin=`
|
|
25
26
|
* (comma/space separated; `none` disables cross-origin access).
|
|
26
27
|
*/
|
|
27
28
|
|
|
29
|
+
import { fail } from './util.js';
|
|
30
|
+
|
|
28
31
|
export const DEFAULT_ALLOWED_ORIGINS = Object.freeze([
|
|
29
32
|
'https://link-foundation.github.io',
|
|
30
|
-
'https://localhost',
|
|
31
|
-
'capacitor://localhost',
|
|
32
33
|
]);
|
|
33
34
|
|
|
34
|
-
const SAFE_METHODS = new Set(['GET', 'HEAD']);
|
|
35
35
|
const ALLOWED_METHODS = 'GET, HEAD, PUT, POST, DELETE, OPTIONS';
|
|
36
36
|
const ALLOWED_HEADERS = 'content-type';
|
|
37
37
|
|
|
@@ -75,7 +75,11 @@ const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
|
75
75
|
const parseHost = (value) => {
|
|
76
76
|
try {
|
|
77
77
|
const url = new URL(`http://${String(value ?? '')}`);
|
|
78
|
-
return url.username ||
|
|
78
|
+
return url.username ||
|
|
79
|
+
url.password ||
|
|
80
|
+
url.pathname !== '/' ||
|
|
81
|
+
url.search ||
|
|
82
|
+
url.hash
|
|
79
83
|
? null
|
|
80
84
|
: { hostname: url.hostname, port: url.port };
|
|
81
85
|
} catch {
|
|
@@ -117,7 +121,7 @@ const isSameOrigin = (req, origin) => {
|
|
|
117
121
|
const host = String(req.headers.host ?? '');
|
|
118
122
|
return (
|
|
119
123
|
hostAllowed(req) &&
|
|
120
|
-
|
|
124
|
+
origin === `${req.socket?.encrypted ? 'https' : 'http'}://${host}`
|
|
121
125
|
);
|
|
122
126
|
};
|
|
123
127
|
|
|
@@ -147,14 +151,24 @@ const writeEmpty = (res, status) => {
|
|
|
147
151
|
*/
|
|
148
152
|
export const handleCors = (req, res, allowed) => {
|
|
149
153
|
const verdict = classifyOrigin(req, allowed);
|
|
154
|
+
res.setHeader('vary', 'Origin');
|
|
150
155
|
if (verdict === 'allowed') {
|
|
151
156
|
res.setHeader('access-control-allow-origin', req.headers.origin);
|
|
152
|
-
res.setHeader('vary', 'Origin');
|
|
153
157
|
}
|
|
154
158
|
const preflight =
|
|
155
159
|
req.method === 'OPTIONS' && req.headers['access-control-request-method'];
|
|
156
160
|
if (preflight) {
|
|
157
|
-
|
|
161
|
+
const method = req.headers['access-control-request-method'];
|
|
162
|
+
const headers = String(req.headers['access-control-request-headers'] ?? '')
|
|
163
|
+
.toLowerCase()
|
|
164
|
+
.split(',')
|
|
165
|
+
.map((h) => h.trim())
|
|
166
|
+
.filter(Boolean);
|
|
167
|
+
if (
|
|
168
|
+
verdict !== 'allowed' ||
|
|
169
|
+
!ALLOWED_METHODS.split(', ').includes(method) ||
|
|
170
|
+
headers.some((h) => h !== ALLOWED_HEADERS)
|
|
171
|
+
) {
|
|
158
172
|
writeEmpty(res, 403);
|
|
159
173
|
return true;
|
|
160
174
|
}
|
|
@@ -167,8 +181,14 @@ export const handleCors = (req, res, allowed) => {
|
|
|
167
181
|
writeEmpty(res, 204);
|
|
168
182
|
return true;
|
|
169
183
|
}
|
|
170
|
-
|
|
171
|
-
|
|
184
|
+
// Cross-site no-cors image/form requests omit Origin. Only the tiny
|
|
185
|
+
// public discovery beacon may be read this way; no API or stream may.
|
|
186
|
+
const foreignWithoutOrigin =
|
|
187
|
+
verdict === 'none' &&
|
|
188
|
+
req.headers['sec-fetch-site'] === 'cross-site' &&
|
|
189
|
+
req.url?.split('?')[0] !== '/api/beacon.svg';
|
|
190
|
+
if (verdict === 'denied' || foreignWithoutOrigin) {
|
|
191
|
+
fail(res, 403, 'forbidden', 'origin is not allowed');
|
|
172
192
|
return true;
|
|
173
193
|
}
|
|
174
194
|
return false;
|
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
* By default it is the hosted one on GitHub Pages: a static bundle that
|
|
5
5
|
* finds this server (./../web/discover.js) and becomes the full app
|
|
6
6
|
* through it, so the server does not have to host a web site. The copy
|
|
7
|
-
* the server serves itself
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* the server serves itself is an opt-in fallback for offline use:
|
|
8
|
+
* `serve --local-ui=true` or `MS_LOCAL_UI=on`. By default `/` sends the
|
|
9
|
+
* browser to the hosted app. Safari uses the local HTTPS API after the
|
|
10
|
+
* server's certificate is trusted; it does not need the local UI.
|
|
11
11
|
*
|
|
12
12
|
* The hosted app finds the server by itself, on our port (8787) and the
|
|
13
13
|
* few others it looks at (DEFAULT_PORTS in ../web/discover.js); no
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
* Safari refuses the hosted page's requests to http://127.0.0.1 but
|
|
20
20
|
* still shows it images from there, so the server answers one small
|
|
21
21
|
* picture (BEACON_PATH) whose size says "here I am" and whether its own
|
|
22
|
-
* copy is on; the hosted page
|
|
22
|
+
* copy is on; the hosted page offers certificate setup and links the
|
|
23
|
+
* optional local copy only when enabled (../web/discover.js).
|
|
23
24
|
* With cross-origin use off (`--allow-origin=none`) there is no picture.
|
|
24
25
|
*
|
|
25
26
|
* With HTTPS on (./local-tls.js, R-Y64) Safari can use the server at
|
|
@@ -49,10 +50,10 @@ export const hostedUiUrl = (value = process.env.MS_UI_URL) => {
|
|
|
49
50
|
}
|
|
50
51
|
};
|
|
51
52
|
|
|
52
|
-
/** Whether the server serves its own copy of the app (default
|
|
53
|
+
/** Whether the server serves its own copy of the app (default no). */
|
|
53
54
|
export const localUiEnabled = (value = process.env.MS_LOCAL_UI) =>
|
|
54
55
|
value === undefined || value === null || value === true
|
|
55
|
-
? true
|
|
56
|
+
? value === true
|
|
56
57
|
: !OFF.has(String(value).trim().toLowerCase());
|
|
57
58
|
|
|
58
59
|
/** Whether the hosted app looks for a server on this port by itself. */
|
|
@@ -105,9 +106,10 @@ export const serveBeacon = (req, res, p, ctx) => {
|
|
|
105
106
|
return true;
|
|
106
107
|
};
|
|
107
108
|
|
|
108
|
-
const TRUST_PAGE = (secure, port, uiUrl) => `<!doctype html>
|
|
109
|
+
const TRUST_PAGE = (secure, port, uiUrl, fingerprint) => `<!doctype html>
|
|
109
110
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
110
111
|
<title>meta-sovereign server</title></head><body>
|
|
112
|
+
<p>Certificate SHA-256: <code>${fingerprint}</code></p>
|
|
111
113
|
${
|
|
112
114
|
secure
|
|
113
115
|
? `<h1>This browser trusts the meta-sovereign server</h1>
|
|
@@ -117,7 +119,7 @@ ${
|
|
|
117
119
|
<p>To let Safari reach this server from the app, open
|
|
118
120
|
<a href="https://127.0.0.1:${port}/trust">https://127.0.0.1:${port}/trust</a>,
|
|
119
121
|
choose Show Details, then visit this website, and enter your password.
|
|
120
|
-
Or run <code>
|
|
122
|
+
Or run <code>node js/bin/meta-sovereign.js trust</code>.</p>`
|
|
121
123
|
}
|
|
122
124
|
</body></html>
|
|
123
125
|
`;
|
|
@@ -131,7 +133,12 @@ export const serveTrust = (req, res, p, ctx) => {
|
|
|
131
133
|
return false;
|
|
132
134
|
}
|
|
133
135
|
const port = req.socket?.localPort ?? 8787;
|
|
134
|
-
const body = TRUST_PAGE(
|
|
136
|
+
const body = TRUST_PAGE(
|
|
137
|
+
Boolean(req.socket?.encrypted),
|
|
138
|
+
port,
|
|
139
|
+
ctx.uiUrl,
|
|
140
|
+
ctx.tls.fingerprint
|
|
141
|
+
);
|
|
135
142
|
res.writeHead(200, {
|
|
136
143
|
'content-type': 'text/html; charset=utf-8',
|
|
137
144
|
'cache-control': 'no-store',
|