diff --git a/README.md b/README.md index f0ad63f..d3f758f 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,8 @@ The stable link follows the latest published release; it does not point to devel Read the [release notes](https://github.com/andre487/AndroidMessage487/releases/latest) for supported features. Release 0.0.1 predates Bearer authentication. -Guides: [Install from APK](docs/en/apk-installation.md) · [n8n webhook](docs/en/n8n-webhook.md) · [Telegram forwarding](docs/en/n8n-telegram.md). -На русском: [Установка из APK](docs/ru/apk-installation.md) · [n8n webhook](docs/ru/n8n-webhook.md) · [Пересылка в Telegram](docs/ru/n8n-telegram.md). +Guides: [Install from APK](docs/en/apk-installation.md) · [n8n Cloud](docs/en/n8n-cloud.md) · [Self-hosted n8n](docs/en/n8n-self-hosted.md) · [Telegram forwarding](docs/en/n8n-telegram.md). +На русском: [Установка из APK](docs/ru/apk-installation.md) · [n8n Cloud](docs/ru/n8n-cloud.md) · [Свой сервер n8n](docs/ru/n8n-self-hosted.md) · [Пересылка в Telegram](docs/ru/n8n-telegram.md). 1. Save the full published webhook URL, a Bearer token and a device code in **Connection**. Send a test event. 2. Check **Journal** and find the same event ID in n8n **Executions**. diff --git a/docs/en/n8n-cloud.md b/docs/en/n8n-cloud.md new file mode 100644 index 0000000..cb11f6f --- /dev/null +++ b/docs/en/n8n-cloud.md @@ -0,0 +1,143 @@ +# Connect Message487 to n8n Cloud + +[English](../en/n8n-cloud.md) | [Русский](../ru/n8n-cloud.md) + +You need a browser, an n8n Cloud account and a phone with [Message487 installed](apk-installation.md). +Every step uses the interface: no server installation, terminal or coding is required. +It is easiest to open n8n on a computer and the app on your phone. + +At the end, a test message from the app will appear in n8n's history. You can add +Telegram forwarding after checking the connection. + +## 1. Open your n8n + +Sign up for [n8n Cloud](https://docs.n8n.io/deploy/use-n8n-cloud/start-your-free-trial) +and open your instance's editor. If you already have an account, sign in. +Cloud provides an HTTPS address. Check [n8n pricing](https://n8n.io/pricing/) +for current trial conditions, prices and execution limits. + +In n8n, an automation is called a **workflow** and its individual steps are called +**nodes**. We will import a ready-made workflow with two nodes. + +## 2. Import the ready-made workflow + +1. Use **Create Workflow** to create a new, empty workflow. +2. Open **⋯ → Import from URL** in the editor's upper-right corner. +3. Paste this address and confirm the import: + + ```text + https://raw.githubusercontent.com/andre487/AndroidMessage487/main/DevServer/workflows/receive.json + ``` + +4. You should see two connected nodes: **Webhook → Respond**. The first receives + the message; the second confirms receipt to the phone. +5. Name the workflow, for example `Message487 — my phone`. + +If URL import is unavailable, open the [workflow file](../../DevServer/workflows/receive.json) +on GitHub, download it using **Download raw file**, then select +**⋯ → Import from File** in n8n. You do not need to edit the file contents. +[Official import guide](https://docs.n8n.io/build/manage-workflows/export-and-import). + +A warning about unconfigured credentials after import is expected: you will set +up your own secret next. The **Respond** node is already configured; leave it as it is. + +## 3. Set a secret for your phone connection + +The token is a separate secret password connecting the app to this workflow. +It is neither your n8n account password nor a Telegram bot token. + +1. Open the password generator in your password manager. Generate at least 32 + random letters and digits with no spaces. Save it as `Message487 webhook` + so you can copy it to your phone later. +2. Double-click **Webhook** and make sure **Authentication** is **Header Auth**. +3. Under **Credential for Header Auth**, select **Create new credential**. + Give the new record a recognizable name, such as `Message487 phone`. + Inside that record, fill in these two fields: + + | n8n field | What to enter | + | --- | --- | + | **Name** | `Authorization` | + | **Value** | The word `Bearer`, one ordinary space, then your generated token | + +4. Click **Save** and make sure the new credential is selected in Webhook. +5. Keep the imported Webhook settings: **HTTP Method → POST** and + **Respond → Using 'Respond to Webhook' Node**. If another published workflow + already uses the same **Path**, give this one a different path, such as `message487/second-phone`. + +Spell it **`Bearer`**, not `Bearier`. Do not add quotes or angle brackets. +n8n needs the `Bearer ` prefix; the app's token field **does not**: the app adds it +for you. Do not select the public test credential `Message487 local webhook`. +[Official Header Auth guide](https://docs.n8n.io/integrations/builtin/credentials/webhook/). + +## 4. Publish and copy the address + +1. Return to the workflow canvas and click **Publish**. Confirm publication if prompted. + Older n8n versions use an **Active** switch instead. +2. Open **Webhook** again, select **Production URL** and copy the complete address. +3. Transfer that address to your phone, for example using a synced note. + +Copy the address from the Webhook node, not the browser's address bar. +You do not need **Test URL** or **Listen for test event** for this setup. +Publish again after editing nodes. +[Official webhook URL guide](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/). + +## 5. Connect the app and send a test + +Open the **Connection** tab at the bottom of Message487 and fill in: + +| App field | What to enter | +| --- | --- | +| **Webhook URL** | The complete **Production URL** copied from n8n | +| **Webhook token** | Your generated token **without `Bearer `** | +| **Device code** | A recognizable phone name, such as `my-phone` | +| **n8n confirmation** | Leave enabled | + +Tap **Save and send test event**. Open **Journal**, then the new test event: success means +**Accepted by webhook** and **HTTP 200**. This test does not yet require notification +access or SMS permission. + +## 6. Find the message in n8n + +1. In your browser, open the workflow's **Executions** tab: this is its run history. +2. Select the latest execution after tapping the test button. +3. Select **Webhook**, open **Output** on the right, switch to **JSON** if needed, + then expand **body**. It contains the message text (`text`) and phone name + (`device_code`). Its `event_id` matches the event ID in the app journal. + +The imported workflow already saves successful executions. If history is empty, +open **⋯ → Settings** and check **Save successful production executions**: +saving must be enabled. Then send a **new** test from the phone. +[Official workflow settings](https://docs.n8n.io/build/manage-workflows/configure-workflow-settings). + +Message contents and headers containing the token may be stored in Cloud history. +Consider this when selecting apps to forward and granting access to your n8n. + +## 7. Enable your sources + +Open **Sources** in the app. For notifications, grant Android notification access +and select apps; for SMS, enable SMS capture and grant its permission. +Test with a new notification or SMS: old messages from your phone's history are not +forwarded retroactively. Selecting both SMS capture and your SMS app's notifications +can deliver the same SMS twice. + +The ready-made workflow currently only receives messages and acknowledges them to +the phone. Continue with [Telegram forwarding](n8n-telegram.md) to send them to a chat. +“Accepted by webhook” alone does not confirm Telegram delivery. + +## Troubleshooting + +| What you see | What to do | +| --- | --- | +| **401/403** in the journal | Check `Authorization`, the spelling of `Bearer`, and one space before the token in n8n. The app needs the same token without the prefix. Make sure Webhook uses your new credential. | +| **404** | Publish the workflow and copy **Production URL** again. Do not use the editor page address or **Test URL**. | +| **HTTP 200** but invalid confirmation | Check the **Webhook → Respond** connection and Webhook response mode from step 3. Keep the imported Respond settings. | +| No message visible in the editor | Open **Executions**, not just the workflow canvas; check history settings in step 6. | +| Network error or waiting | Check the phone's internet access and your n8n Cloud availability. Ensure the instance is running and its plan limit has not been exhausted. | +| Tests arrive but notifications do not | Check **Sources**, selected apps, Android permissions and the forwarding pause state. Then create a new notification. | + +After fixing the address or token, tap **Save and send test event** again. Existing events +keep their original connection settings; retrying them does not test the new address +or token. You can delete unwanted old records from the journal. + +The app's [diagnostic log](diagnostics.md) can help with further troubleshooting. +See the [technical guide](n8n-self-hosted.md) for message formats and acknowledgement details. diff --git a/docs/en/n8n-self-hosted.md b/docs/en/n8n-self-hosted.md new file mode 100644 index 0000000..535e84e --- /dev/null +++ b/docs/en/n8n-self-hosted.md @@ -0,0 +1,209 @@ +# Connect Message487 to self-hosted n8n + +[English](../en/n8n-self-hosted.md) | [Русский](../ru/n8n-self-hosted.md) + +Installing on a phone? See [APK installation and Android restrictions](apk-installation.md). + +This guide targets Message487 0.0.2 and later, with Bearer authentication. You need the n8n editor and an HTTPS endpoint +reachable from your phone. For a local Android emulator, use the debug build and +[DevServer](../../DevServer/README.md). Release APKs reject HTTP endpoints. + +## Prepare your server + +For the managed service, use the [n8n Cloud guide](n8n-cloud.md). +This guide is for the owner or administrator of a self-hosted n8n server. + +Follow the official [Docker Compose guide](https://docs.n8n.io/deploy/host-n8n/install-options/install-using-docker-compose) +or choose another [installation option](https://docs.n8n.io/deploy/host-n8n/install-options). +Configure persistent storage, backups and a public HTTPS endpoint with a trusted +certificate. It must be reachable from your phone, including over mobile data if +forwarding should work outside your home network. + +If someone else manages the server, ask them for editor access and the external +n8n address. The editor password and webhook token are separate settings. +[DevServer](../../DevServer/README.md) is for local development; do not expose it +publicly with its bundled test credentials. + +## 1. Create a receiving workflow + +Import [receive.json](../../DevServer/workflows/receive.json) using **Import from File** +in the editor menu. It validates basic fields and acknowledges the incoming `event_id`. +Import a separate workflow rather than replacing an existing production workflow. + +```mermaid +flowchart LR + W[Webhook: POST] --> R[Respond to Webhook: JSON ACK] +``` + +To configure the same two nodes manually, set **Webhook** as follows: + +| Field | Value | +| --- | --- | +| HTTP Method | `POST` | +| Path | A unique path such as `message487/receive-` | +| Authentication | `Header Auth` | +| Respond | `Using 'Respond to Webhook' Node` | + +Create a **Header Auth** credential: **Name** = `Authorization`, **Value** = `Bearer `. +Generate a private token with `openssl rand -hex 32` and replace ``. Select this +credential in Webhook, including after importing the fixture; do not use the bundled public +DevServer credential in production. The editor login is separate from webhook authentication. +See [official webhook credentials](https://docs.n8n.io/integrations/builtin/credentials/webhook/). + +Set **Respond to Webhook → Respond With → JSON**, **Response Code → 200**, and use +this **Expression** in **Response Body**: + +```javascript +{{ { status: 'accepted', event_id: $('Webhook').first().json.body.event_id } }} +``` + +`Webhook` is the trigger node's name; adjust the expression if you rename it. +This minimal manual example does not validate requests. The imported `receive.json` +also validates `schema_version`, `event_id`, `message_type` and `text`, returning +HTTP 400 for invalid input. + +The client expects an object, not an array, JSON-encoded string or HTML: + +```json +{"status":"accepted","event_id":"the-same-event_id-as-the-request"} +``` + +The status must be exactly `accepted` and the ID must match. The default n8n response +“Workflow got started” is not an ACK for this client. See the official +[Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/) and +[Respond to Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.respondtowebhook/) documentation. + +## 2. Publish and copy the URL + +Select **Publish** (or enable **Active** in older n8n versions), then copy the +Webhook node's **Production URL**, for example: + +```text +https://n8n.example.org/webhook/message487/receive- +``` + +The `/webhook-test/` **Test URL** is for temporary listening with **Listen for test event**. +Production requests use a published workflow and appear under **Executions**. +Publish again after editing the workflow. + +If a reverse proxy causes n8n to display an internal URL, configure `WEBHOOK_URL`, +`N8N_PROXY_HOPS` and forwarded headers using the official +[reverse-proxy guide](https://docs.n8n.io/deploy/host-n8n/configure-n8n/basic-configuration/configuration-examples/configure-webhook-urls-with-reverse-proxy). +Use the final HTTPS URL with a trusted certificate: Message487 does not follow +HTTP redirects or disable TLS verification. + +## 3. Configure the app + +1. Open **Connection** and paste the complete Production URL. +2. Enter the same token in **Webhook token**, without `Bearer `. +3. Set a recognizable **Device code**, such as `personal-phone`. +4. Keep **n8n confirmation** enabled. +5. Save and send a test event. +6. Open the event in **Journal** and check its acknowledgement and HTTP 200. + +After the test succeeds, enable your desired **Sources**. Notifications require +Android notification access and selected apps; SMS requires receive-SMS permission. +Enabling SMS and selecting your SMS app can produce two events for one message. + +The bundled emulator endpoint is `http://10.0.2.2:5678/webhook/message487/receive`, +which requires a debug build. On a physical phone, `localhost` means the phone +itself, and `10.0.2.2` is not your computer's address. + +## 4. Inspect received data + +Open **Executions → execution → Webhook → Output → body** in n8n. Match its +`event_id` with the app journal. Enable saving successful execution data if needed; +DevServer already does this. Execution history contains complete messages, so +configure access and retention accordingly. Request headers may contain the token too. + +Example notification body: + +```json +{ + "schema_version": 1, + "event_id": "5d8ee1a5-9360-4b0e-8412-942b2e1c99ab", + "device_id": "43b55766-95b6-40b8-8f4f-c0240f547914", + "device_code": "personal-phone", + "message_type": "notification", + "occurred_at": "2026-09-09T09:00:00Z", + "source": "org.example.chat", + "source_name": "Example Chat", + "title": "Test notification", + "text": "Connection check" +} +``` + +| Field | Meaning | +| --- | --- | +| `event_id` | Event ID, preserved across delivery retries | +| `device_id` | Installation ID | +| `device_code` | Editable device label | +| `message_type` | `test`, `notification` or `sms` | +| `occurred_at` | Event timestamp in ISO 8601 format | +| `source` / `source_name` | Source package / app name; SMS uses source `android` | +| `title` | Notification title; absent for SMS and tests | +| `sender` | SMS sender; absent for notifications and tests | +| `text` | Event text | + +Directly after Webhook use `{{ $json.body.text }}` or `{{ $json.body.device_code }}`. +If intermediate nodes replace the data, reference the original node explicitly: +`{{ $('Webhook').first().json.body.text }}`. + +## 5. Add message processing + +For a complete example, see [forwarding to Telegram](n8n-telegram.md). + +The bundled receiver only acknowledges requests; it does not send to Telegram, +store a separate durable queue or deduplicate. Put your actions before Respond to +Webhook, acknowledging only after the operation you consider acceptance succeeds. +For slow processing, persist the event to a durable queue/database first, ACK it, +and perform downstream work separately. + +The client uses 10-second connection and read timeouts. A lost response can cause +an already processed request to be retried. Use `event_id` as a unique storage key; +already accepted duplicates must receive the same successful ACK. A separate +“check then insert” without a unique constraint does not prevent concurrent duplicates. + +Acknowledging before processing removes the event body from the client's queue +once confirmed. A later n8n failure will not trigger a phone retry. Successful +n8n execution and successful client acknowledgement are different outcomes. + +## Test without a phone + +Use your actual Production URL and a new ID for each test. This request contains +synthetic data only: + +Set `WEBHOOK_TOKEN` in your shell to the same private token before running the command. + +```sh +curl --fail-with-body --max-time 10 \ + -X POST 'https://n8n.example.org/webhook/message487/YOUR-PATH' \ + -H 'Content-Type: application/json' \ + -H "Authorization: Bearer ${WEBHOOK_TOKEN:?Set WEBHOOK_TOKEN}" \ + --data '{"schema_version":1,"event_id":"manual-check-001","device_id":"manual-test","device_code":"test-phone","message_type":"test","occurred_at":"2026-09-09T09:00:00Z","source":"life.andre.message487","source_name":"Message487","text":"Synthetic connection test"}' +``` + +Expect HTTP 200 and `{"status":"accepted","event_id":"manual-check-001"}`. +This checks the server contract; also test the Android connection button and a new +notification or SMS to exercise actual app delivery. + +## Troubleshooting + +| Symptom | Check | +| --- | --- | +| HTTP 404 | Production URL, publication, POST method and path | +| HTTP 401/403 | Authentication and proxy/n8n access restrictions | +| HTTP 301/302 | Supply the final URL; redirects are not followed | +| `INVALID_ACK` with HTTP 200 | JSON object, `status: accepted`, matching ID and Webhook response mode | +| Timeout/network error | Phone connectivity, TLS, firewall and time until response | +| No execution in the editor | Executions tab and successful execution retention | +| Tests arrive, messages do not | Sources, Android permissions, selected apps and pause state | + +Network failures, timeouts, HTTP 408/425/429 and 5xx retry automatically. Invalid ACKs +and other HTTP errors require intervention and manual retry from the journal. +Changing the URL or token only affects new events; queued events retain both original values. +Old queued events created without authentication are blocked and cannot be sent anonymously. +After upgrading from 0.0.1, enter the token and send a new test; delete obsolete blocked events. +Send a new test after fixing configuration and delete old records separately if needed. +The top-bar bug icon opens [diagnostics](diagnostics.md), which records delivery +outcomes without message text. diff --git a/docs/en/n8n-telegram.md b/docs/en/n8n-telegram.md index 2a22d84..044f6d5 100644 --- a/docs/en/n8n-telegram.md +++ b/docs/en/n8n-telegram.md @@ -2,8 +2,8 @@ [English](../en/n8n-telegram.md) | [Русский](../ru/n8n-telegram.md) -First configure the [n8n webhook](n8n-webhook.md) and confirm a test event. That guide -also links to official documentation, n8n Cloud and self-hosted installation options. +First follow the [n8n Cloud](n8n-cloud.md) or [self-hosted n8n](n8n-self-hosted.md) +guide and confirm a test event. The following steps are the same for both setups. Keep the bot token in **n8n Credentials**; it is not needed in Android. Forwarded messages are available to the selected Telegram chat and may remain in n8n history. diff --git a/docs/en/n8n-webhook.md b/docs/en/n8n-webhook.md index 18003c6..808702c 100644 --- a/docs/en/n8n-webhook.md +++ b/docs/en/n8n-webhook.md @@ -2,204 +2,21 @@ [English](../en/n8n-webhook.md) | [Русский](../ru/n8n-webhook.md) -Installing on a phone? See [APK installation and Android restrictions](apk-installation.md). +Choose a guide based on where your n8n runs: -This guide targets Message487 0.0.2 and later, with Bearer authentication. You need the n8n editor and an HTTPS endpoint -reachable from your phone. For a local Android emulator, use the debug build and -[DevServer](../../DevServer/README.md). Release APKs reject HTTP endpoints. - -## Where to run n8n - -- [Official n8n documentation](https://docs.n8n.io/) covers nodes, expressions and workflows. -- [Get started with n8n Cloud](https://docs.n8n.io/deploy/use-n8n-cloud/start-your-free-trial) to use a managed instance. -- [Cloud or self-hosting](https://docs.n8n.io/choose-how-to-use-n8n) compares deployment options. -- [Self-hosted installation options](https://docs.n8n.io/deploy/host-n8n/install-options). -- Official [Docker Compose installation guide](https://docs.n8n.io/deploy/host-n8n/install-options/install-using-docker-compose). - -For Cloud, use your workspace's HTTPS Production URL. For self-hosting, configure -HTTPS, persistent storage and backups. DevServer is for local development; do not -expose it publicly with its bundled test credentials. - -## 1. Create a receiving workflow - -Import [receive.json](../../DevServer/workflows/receive.json) using **Import from File** -in the editor menu. It validates basic fields and acknowledges the incoming `event_id`. -Import a separate workflow rather than replacing an existing production workflow. - -```mermaid -flowchart LR - W[Webhook: POST] --> R[Respond to Webhook: JSON ACK] -``` - -To configure the same two nodes manually, set **Webhook** as follows: - -| Field | Value | -| --- | --- | -| HTTP Method | `POST` | -| Path | A unique path such as `message487/receive-` | -| Authentication | `Header Auth` | -| Respond | `Using 'Respond to Webhook' Node` | - -Create a **Header Auth** credential: **Name** = `Authorization`, **Value** = `Bearer `. -Generate a private token with `openssl rand -hex 32` and replace ``. Select this -credential in Webhook, including after importing the fixture; do not use the bundled public -DevServer credential in production. The editor login is separate from webhook authentication. -See [official webhook credentials](https://docs.n8n.io/integrations/builtin/credentials/webhook/). - -Set **Respond to Webhook → Respond With → JSON**, **Response Code → 200**, and use -this **Expression** in **Response Body**: - -```javascript -{{ { status: 'accepted', event_id: $('Webhook').first().json.body.event_id } }} -``` - -`Webhook` is the trigger node's name; adjust the expression if you rename it. -This minimal manual example does not validate requests. The imported `receive.json` -also validates `schema_version`, `event_id`, `message_type` and `text`, returning -HTTP 400 for invalid input. - -The client expects an object, not an array, JSON-encoded string or HTML: - -```json -{"status":"accepted","event_id":"the-same-event_id-as-the-request"} -``` - -The status must be exactly `accepted` and the ID must match. The default n8n response -“Workflow got started” is not an ACK for this client. See the official -[Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/) and -[Respond to Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.respondtowebhook/) documentation. - -## 2. Publish and copy the URL - -Select **Publish** (or enable **Active** in older n8n versions), then copy the -Webhook node's **Production URL**, for example: - -```text -https://n8n.example.org/webhook/message487/receive- -``` - -The `/webhook-test/` **Test URL** is for temporary listening with **Listen for test event**. -Production requests use a published workflow and appear under **Executions**. -Publish again after editing the workflow. - -If a reverse proxy causes n8n to display an internal URL, configure `WEBHOOK_URL`, -`N8N_PROXY_HOPS` and forwarded headers using the official -[reverse-proxy guide](https://docs.n8n.io/deploy/host-n8n/configure-n8n/basic-configuration/configuration-examples/configure-webhook-urls-with-reverse-proxy). -Use the final HTTPS URL with a trusted certificate: Message487 does not follow -HTTP redirects or disable TLS verification. - -## 3. Configure the app - -1. Open **Connection** and paste the complete Production URL. -2. Enter the same token in **Webhook token**, without `Bearer `. -3. Set a recognizable **Device code**, such as `personal-phone`. -4. Keep **n8n confirmation** enabled. -5. Save and send a test event. -6. Open the event in **Journal** and check its acknowledgement and HTTP 200. - -After the test succeeds, enable your desired **Sources**. Notifications require -Android notification access and selected apps; SMS requires receive-SMS permission. -Enabling SMS and selecting your SMS app can produce two events for one message. - -The bundled emulator endpoint is `http://10.0.2.2:5678/webhook/message487/receive`, -which requires a debug build. On a physical phone, `localhost` means the phone -itself, and `10.0.2.2` is not your computer's address. - -## 4. Inspect received data - -Open **Executions → execution → Webhook → Output → body** in n8n. Match its -`event_id` with the app journal. Enable saving successful execution data if needed; -DevServer already does this. Execution history contains complete messages, so -configure access and retention accordingly. Request headers may contain the token too. - -Example notification body: - -```json -{ - "schema_version": 1, - "event_id": "5d8ee1a5-9360-4b0e-8412-942b2e1c99ab", - "device_id": "43b55766-95b6-40b8-8f4f-c0240f547914", - "device_code": "personal-phone", - "message_type": "notification", - "occurred_at": "2026-09-09T09:00:00Z", - "source": "org.example.chat", - "source_name": "Example Chat", - "title": "Test notification", - "text": "Connection check" -} -``` - -| Field | Meaning | +| Your setup | Guide | | --- | --- | -| `event_id` | Event ID, preserved across delivery retries | -| `device_id` | Installation ID | -| `device_code` | Editable device label | -| `message_type` | `test`, `notification` or `sms` | -| `occurred_at` | Event timestamp in ISO 8601 format | -| `source` / `source_name` | Source package / app name; SMS uses source `android` | -| `title` | Notification title; absent for SMS and tests | -| `sender` | SMS sender; absent for notifications and tests | -| `text` | Event text | - -Directly after Webhook use `{{ $json.body.text }}` or `{{ $json.body.device_code }}`. -If intermediate nodes replace the data, reference the original node explicitly: -`{{ $('Webhook').first().json.body.text }}`. - -## 5. Add message processing +| I want to use a browser without running my own server | [n8n Cloud: step-by-step setup](n8n-cloud.md) | +| n8n runs on my server or my organization's server | [Self-hosted n8n: setup and troubleshooting](n8n-self-hosted.md) | +| I develop the app using an Android emulator | [Local DevServer](../../DevServer/README.md) | -For a complete example, see [forwarding to Telegram](n8n-telegram.md). +For beginners, we recommend **n8n Cloud**: n8n maintains the server and you configure +it through the website. Cloud offers a trial and paid plans; see the current terms +on the [n8n website](https://n8n.io/pricing/). -The bundled receiver only acknowledges requests; it does not send to Telegram, -store a separate durable queue or deduplicate. Put your actions before Respond to -Webhook, acknowledging only after the operation you consider acceptance succeeds. -For slow processing, persist the event to a durable queue/database first, ACK it, -and perform downstream work separately. - -The client uses 10-second connection and read timeouts. A lost response can cause -an already processed request to be retried. Use `event_id` as a unique storage key; -already accepted duplicates must receive the same successful ACK. A separate -“check then insert” without a unique constraint does not prevent concurrent duplicates. - -Acknowledging before processing removes the event body from the client's queue -once confirmed. A later n8n failure will not trigger a phone retry. Successful -n8n execution and successful client acknowledgement are different outcomes. - -## Test without a phone - -Use your actual Production URL and a new ID for each test. This request contains -synthetic data only: - -Set `WEBHOOK_TOKEN` in your shell to the same private token before running the command. - -```sh -curl --fail-with-body --max-time 10 \ - -X POST 'https://n8n.example.org/webhook/message487/YOUR-PATH' \ - -H 'Content-Type: application/json' \ - -H "Authorization: Bearer ${WEBHOOK_TOKEN:?Set WEBHOOK_TOKEN}" \ - --data '{"schema_version":1,"event_id":"manual-check-001","device_id":"manual-test","device_code":"test-phone","message_type":"test","occurred_at":"2026-09-09T09:00:00Z","source":"life.andre.message487","source_name":"Message487","text":"Synthetic connection test"}' -``` - -Expect HTTP 200 and `{"status":"accepted","event_id":"manual-check-001"}`. -This checks the server contract; also test the Android connection button and a new -notification or SMS to exercise actual app delivery. - -## Troubleshooting - -| Symptom | Check | -| --- | --- | -| HTTP 404 | Production URL, publication, POST method and path | -| HTTP 401/403 | Authentication and proxy/n8n access restrictions | -| HTTP 301/302 | Supply the final URL; redirects are not followed | -| `INVALID_ACK` with HTTP 200 | JSON object, `status: accepted`, matching ID and Webhook response mode | -| Timeout/network error | Phone connectivity, TLS, firewall and time until response | -| No execution in the editor | Executions tab and successful execution retention | -| Tests arrive, messages do not | Sources, Android permissions, selected apps and pause state | +Both setups let the app send messages to an authenticated endpoint and receive +confirmation. After a successful test, you can add [Telegram forwarding](n8n-telegram.md). -Network failures, timeouts, HTTP 408/425/429 and 5xx retry automatically. Invalid ACKs -and other HTTP errors require intervention and manual retry from the journal. -Changing the URL or token only affects new events; queued events retain both original values. -Old queued events created without authentication are blocked and cannot be sent anonymously. -After upgrading from 0.0.1, enter the token and send a new test; delete obsolete blocked events. -Send a new test after fixing configuration and delete old records separately if needed. -The top-bar bug icon opens [diagnostics](diagnostics.md), which records delivery -outcomes without message text. +If you haven't installed the app, start with [APK installation](apk-installation.md). +More help: [official n8n documentation](https://docs.n8n.io/) and +[Cloud versus self-hosting](https://docs.n8n.io/choose-how-to-use-n8n). diff --git a/docs/ru/n8n-cloud.md b/docs/ru/n8n-cloud.md new file mode 100644 index 0000000..697761d --- /dev/null +++ b/docs/ru/n8n-cloud.md @@ -0,0 +1,145 @@ +# Подключение Message487 к n8n Cloud + +[English](../en/n8n-cloud.md) | [Русский](../ru/n8n-cloud.md) + +Понадобятся браузер, аккаунт n8n Cloud и телефон с [установленным Message487](apk-installation.md). +Все шаги выполняются через интерфейс: устанавливать сервер, открывать консоль или +писать код не нужно. Удобнее открыть n8n на компьютере, а приложение — на телефоне. + +В результате тестовое сообщение из приложения появится в истории n8n. Пересылку в +Telegram можно добавить после проверки подключения. + +## 1. Откройте свой n8n + +Зарегистрируйтесь в [n8n Cloud](https://docs.n8n.io/deploy/use-n8n-cloud/start-your-free-trial) +и откройте редактор своего экземпляра n8n. Если аккаунт уже есть, войдите в него. +Облако предоставляет готовый адрес HTTPS. Условия пробного периода, стоимость и +лимиты запусков смотрите в [тарифах n8n](https://n8n.io/pricing/). + +В n8n сценарий обработки называется **workflow**, а отдельные действия внутри него — +**узлы**. Мы импортируем готовый сценарий с двумя узлами. + +## 2. Импортируйте готовый сценарий + +1. Создайте новый пустой workflow кнопкой **Create Workflow**. +2. В правом верхнем углу редактора откройте меню **⋯ → Import from URL**. +3. Вставьте следующий адрес и подтвердите импорт: + + ```text + https://raw.githubusercontent.com/andre487/AndroidMessage487/main/DevServer/workflows/receive.json + ``` + +4. На схеме должны появиться соединённые узлы **Webhook → Respond**. + Первый принимает сообщение, второй сообщает телефону об успешном приёме. +5. Назовите сценарий, например `Message487 — мой телефон`. + +Если импорт по URL недоступен, откройте [файл сценария](../../DevServer/workflows/receive.json) +на GitHub, скачайте его кнопкой **Download raw file**, затем выберите +**⋯ → Import from File** в n8n. Редактировать содержимое файла не нужно. +[Справка n8n по импорту](https://docs.n8n.io/build/manage-workflows/export-and-import). + +Предупреждение о ненастроенных credentials после импорта ожидаемо: на следующем +шаге вы зададите свой секрет. Узел **Respond** уже настроен — оставьте его как есть. + +## 3. Задайте секрет для подключения телефона + +Токен — это отдельный секретный пароль для связи приложения с этим workflow. +Это не пароль аккаунта n8n и не токен Telegram-бота. + +1. Откройте генератор паролей в своём менеджере паролей. Создайте случайный пароль + длиной не менее 32 символов из латинских букв и цифр, без пробелов. Сохраните его + под именем `Message487 webhook`, чтобы затем скопировать на телефон. +2. Дважды нажмите узел **Webhook**. Убедитесь, что **Authentication** стоит в + значении **Header Auth**. +3. В поле выбора **Credential for Header Auth** нажмите **Create new credential**. + Сохраните новую запись под понятным именем, например `Message487 phone`. + Внутри этой записи заполните два поля: + + | Поле n8n | Что ввести | + | --- | --- | + | **Name** | `Authorization` | + | **Value** | Слово `Bearer`, один обычный пробел и сгенерированный токен | + +4. Нажмите **Save** и убедитесь, что новая запись выбрана в узле Webhook. +5. Остальные настройки Webhook оставьте из шаблона: **HTTP Method → POST**, + **Respond → Using 'Respond to Webhook' Node**. Если у вас уже есть опубликованный + workflow с таким же **Path**, задайте новому другой путь, например `message487/second-phone`. + +Пишите именно **`Bearer`**, не `Bearier`. Кавычки и угловые скобки не нужны. +В n8n префикс `Bearer ` нужен, а в поле токена приложения — **не нужен**: приложение +добавит его само. Не выбирайте публичный тестовый credential `Message487 local webhook`. +[Справка n8n по Header Auth](https://docs.n8n.io/integrations/builtin/credentials/webhook/). + +## 4. Опубликуйте сценарий и скопируйте адрес + +1. Вернитесь на схему и нажмите **Publish**. Подтвердите публикацию, если появится диалог. + В старых версиях n8n вместо этой кнопки используется переключатель **Active**. +2. Снова откройте **Webhook**, выберите вкладку **Production URL** и скопируйте адрес целиком. +3. Перенесите адрес на телефон, например через синхронизированную заметку. + +Адрес берётся именно из узла Webhook, а не из адресной строки браузера. +**Test URL** и кнопка **Listen for test event** для этого способа настройки не нужны. +После изменения узлов публикуйте workflow повторно. +[Справка n8n об адресах веб-хука](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/). + +## 5. Подключите приложение и отправьте тест + +В Message487 откройте нижнюю вкладку **Связь** и заполните: + +| Поле приложения | Что указать | +| --- | --- | +| **Адрес webhook** | Полный **Production URL**, скопированный из n8n | +| **Токен веб-хука** | Сгенерированный токен **без `Bearer `** | +| **Код устройства** | Понятное имя телефона, например `my-phone` | +| **Подтверждение n8n** | Оставить включённым | + +Нажмите **Сохранить и отправить тест**. Откройте **Журнал**, затем новое тестовое +событие: успешный результат — **Принято webhook** и **HTTP 200**. +Для этого теста пока не требуется доступ к уведомлениям или SMS. + +## 6. Найдите сообщение в n8n + +1. В браузере откройте свой workflow и вкладку **Executions** — это история запусков. +2. Выберите последний запуск после нажатия тестовой кнопки. +3. Нажмите **Webhook**, справа откройте **Output**, при необходимости переключитесь + на **JSON** и раскройте **body**. Внутри находятся текст сообщения (`text`) и имя + телефона (`device_code`). Поле `event_id` совпадает с ID события в журнале приложения. + +У импортированного сценария сохранение успешных запусков уже включено. Если история +пуста, откройте **⋯ → Settings** и проверьте **Save successful production executions**: +сохранение должно быть включено. Затем отправьте **новый** тест с телефона. +[Справка по настройкам workflow](https://docs.n8n.io/build/manage-workflows/configure-workflow-settings). + +Содержимое сообщений и заголовки с токеном могут сохраняться в истории облака. +Учитывайте это, выбирая приложения для пересылки и предоставляя доступ к своему n8n. + +## 7. Включите нужные источники + +В приложении откройте **Источники**. Для уведомлений выдайте запрошенный Android +доступ и выберите приложения; для SMS включите приём SMS и выдайте разрешение. +Проверьте доставку новым уведомлением или SMS: старые сообщения из истории телефона +не пересылаются задним числом. Если выбраны SMS и уведомления SMS-приложения, +одно SMS может прийти дважды. + +Готовый workflow пока только принимает сообщения и подтверждает их телефону. +Для следующего шага откройте [инструкцию по пересылке в Telegram](n8n-telegram.md). +Статус «Принято webhook» сам по себе не означает доставку в Telegram. + +## Если что-то не получилось + +| Что видно | Что сделать | +| --- | --- | +| **401/403** в журнале | Проверьте `Authorization`, написание `Bearer` и один пробел перед токеном в n8n. В приложении должен быть тот же токен без префикса. Убедитесь, что Webhook использует созданный вами credential. | +| **404** | Опубликуйте workflow и заново скопируйте **Production URL**. Не используйте адрес страницы редактора или **Test URL**. | +| **HTTP 200**, но подтверждение неверно | Проверьте соединение **Webhook → Respond** и режим ответа Webhook из шага 3. Не меняйте готовые настройки Respond. | +| В редакторе не видно сообщения | Откройте **Executions**, а не только схему workflow; проверьте сохранение истории по шагу 6. | +| Сетевая ошибка или ожидание | Проверьте интернет на телефоне и доступность своего n8n Cloud. Убедитесь, что экземпляр работает и не исчерпан лимит тарифа. | +| Тест приходит, уведомления — нет | Проверьте **Источники**, выбор приложений, разрешения Android и паузу пересылки. Затем создайте новое уведомление. | + +После исправления адреса или токена снова нажмите **Сохранить и отправить тест**. +Уже созданные события сохраняют прежние настройки подключения; их повтор не проверяет +новый адрес или токен. Ненужные старые записи можно удалить из журнала. + +Для дальнейшего разбора ошибок в приложении есть [диагностический лог](diagnostics.md). +Подробности формата сообщений и подтверждений приведены в +[техническом руководстве](n8n-self-hosted.md). diff --git a/docs/ru/n8n-self-hosted.md b/docs/ru/n8n-self-hosted.md new file mode 100644 index 0000000..ac619af --- /dev/null +++ b/docs/ru/n8n-self-hosted.md @@ -0,0 +1,226 @@ +# Подключение Message487 к собственному серверу n8n + +[English](../en/n8n-self-hosted.md) | [Русский](../ru/n8n-self-hosted.md) + +Для установки на телефон см. [инструкцию по APK и ограничениям Android](apk-installation.md). + +Инструкция для Message487 0.0.2 и новее, с Bearer-авторизацией. Нужен доступ к редактору n8n и HTTPS-адрес, +доступный с телефона. Для локального Android-эмулятора используйте debug-сборку и +[готовый DevServer](../../DevServer/README.md). Релизный APK не принимает HTTP-адреса. + +## Подготовьте сервер + +Для облачного сервиса без администрирования используйте [инструкцию n8n Cloud](n8n-cloud.md). +Это руководство предназначено для владельца собственного сервера или его администратора. + +Установите n8n по [официальной инструкции Docker Compose](https://docs.n8n.io/deploy/host-n8n/install-options/install-using-docker-compose) +или выберите другой [способ установки](https://docs.n8n.io/deploy/host-n8n/install-options). +Настройте постоянное хранение данных, резервные копии и внешний HTTPS-адрес с доверенным +сертификатом. Он должен быть доступен с телефона, в том числе через мобильный интернет, +если пересылка нужна вне домашней сети. + +Если сервер обслуживает другой человек, попросите у него доступ к редактору и внешний +адрес n8n. Пароль входа в редактор и токен веб-хука — разные настройки. +[DevServer](../../DevServer/README.md) предназначен для локальной разработки; +не публикуйте его в интернете с тестовыми учётными данными. + +## 1. Создайте принимающий workflow + +Быстрее всего импортировать [receive.json](../../DevServer/workflows/receive.json) +через **Import from File** в меню редактора n8n. Это готовый пример приёмника с +проверкой базовых полей и подтверждением `event_id`. Импортируйте его как отдельный +workflow; не заменяйте им рабочий сценарий с вашими действиями. + +В импортированном workflow уже соединены два узла: + +```mermaid +flowchart LR + W[Webhook: POST] --> R[Respond to Webhook: JSON ACK] +``` + +Для ручной настройки создайте те же узлы. В узле **Webhook** установите: + +| Поле | Значение | +| --- | --- | +| HTTP Method | `POST` | +| Path | Уникальный путь, например `message487/receive-<случайная-строка>` | +| Authentication | `Header Auth` | +| Respond | `Using 'Respond to Webhook' Node` | + +Создайте credential **Header Auth**: **Name** = `Authorization`, **Value** = `Bearer <токен>`. +Сгенерируйте собственный токен командой `openssl rand -hex 32`, замените `<токен>` +и выберите credential в Webhook, в том числе после импорта файла. Публичный тестовый +credential DevServer нельзя использовать на рабочем сервере. Пароль редактора n8n +не заменяет авторизацию веб-хука. См. [официальную документацию](https://docs.n8n.io/integrations/builtin/credentials/webhook/). + +В узле **Respond to Webhook** выберите **Respond With → JSON**, добавьте +**Response Code → 200**, а **Response Body** переключите в режим **Expression**: + +```javascript +{{ { status: 'accepted', event_id: $('Webhook').first().json.body.event_id } }} +``` + +Здесь `Webhook` — имя первого узла; при переименовании исправьте ссылку в выражении. +Этот минимальный ручной пример подтверждает запрос без валидации. Импортированный +`receive.json` дополнительно проверяет `schema_version`, `event_id`, `message_type` +и `text` и возвращает HTTP 400 для некорректного тела. + +Клиент ждёт JSON-объект следующего вида, а не массив, строку с JSON или HTML: + +```json +{"status":"accepted","event_id":"тот-же-event_id-что-в-запросе"} +``` + +`status` должен быть ровно `accepted`, а `event_id` — совпадать с запросом. +Обычный ответ n8n «Workflow got started» не подходит для режима подтверждения. +Настройки узлов описаны в документации [Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/) +и [Respond to Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.respondtowebhook/). + +## 2. Опубликуйте workflow и скопируйте URL + +Нажмите **Publish** (в более старых версиях n8n — включите **Active**). В узле +Webhook скопируйте **Production URL**, например: + +```text +https://n8n.example.org/webhook/message487/receive-<случайная-строка> +``` + +Не используйте постоянным адресом **Test URL** с `/webhook-test/`: он предназначен +для временного прослушивания через **Listen for test event**. Production URL +работает для опубликованного workflow, а его вызовы смотрят во вкладке **Executions**. +После изменения workflow опубликуйте изменения повторно. + +Если n8n стоит за reverse proxy и показывает внутренний адрес, настройте внешний +`WEBHOOK_URL`, число доверенных proxy в `N8N_PROXY_HOPS` и forwarded-заголовки по +[инструкции n8n для reverse proxy](https://docs.n8n.io/deploy/host-n8n/configure-n8n/basic-configuration/configuration-examples/configure-webhook-urls-with-reverse-proxy). +Телефон должен обращаться сразу к конечному HTTPS URL с доверенным сертификатом: +Message487 не следует HTTP-перенаправлениям и не отключает проверку TLS. + +## 3. Настройте приложение + +1. Откройте вкладку **Связь / Connection**. +2. Вставьте полный Production URL в поле веб-хука. +3. Введите тот же токен в **Токен веб-хука**, без `Bearer `. +4. Задайте понятный **Код устройства / Device code**, например `personal-phone`. +5. Оставьте включённым **Подтверждение n8n / n8n confirmation**. +6. Нажмите кнопку сохранения и отправки тестового события. +7. В **Журнале / Journal** откройте событие и проверьте подтверждение и HTTP 200. + +После успешного теста включите нужные источники в **Источниках / Sources**: +для уведомлений выдайте системный доступ и выберите приложения; для SMS выдайте +разрешение на получение SMS. Если выбраны и SMS, и уведомления SMS-приложения, +одно входящее SMS может породить два разных события. + +Для эмулятора готовый DevServer использует +`http://10.0.2.2:5678/webhook/message487/receive`. Такой URL допустим только в +debug-сборке. На физическом телефоне `localhost` обозначает сам телефон, а +`10.0.2.2` не является адресом вашего компьютера. + +## 4. Посмотрите полученные данные + +В n8n откройте **Executions → нужный запуск → Webhook → Output → body**. Найдите +`event_id` из журнала приложения. Для сохранения успешных запусков включите +соответствующую настройку сохранения execution data; в DevServer она уже включена. +История n8n содержит полные сообщения, поэтому настройте её срок хранения и доступ. + +Пример тела уведомления: + +```json +{ + "schema_version": 1, + "event_id": "5d8ee1a5-9360-4b0e-8412-942b2e1c99ab", + "device_id": "43b55766-95b6-40b8-8f4f-c0240f547914", + "device_code": "personal-phone", + "message_type": "notification", + "occurred_at": "2026-09-09T09:00:00Z", + "source": "org.example.chat", + "source_name": "Example Chat", + "title": "Тестовое уведомление", + "text": "Проверка подключения" +} +``` + +| Поле | Значение | +| --- | --- | +| `event_id` | ID события; сохраняется при повторах доставки | +| `device_id` | ID установки приложения | +| `device_code` | Редактируемая метка устройства | +| `message_type` | `test`, `notification` или `sms` | +| `occurred_at` | Время события в формате ISO 8601 | +| `source` / `source_name` | Пакет источника / имя приложения; для SMS источник `android` | +| `title` | Заголовок уведомления; отсутствует у SMS и теста | +| `sender` | Отправитель SMS; отсутствует у уведомления и теста | +| `text` | Текст события | + +В узле сразу после Webhook доступны выражения `{{ $json.body.text }}` и +`{{ $json.body.device_code }}`. Если промежуточный узел меняет данные, обращайтесь +к исходному событию явно: `{{ $('Webhook').first().json.body.text }}`. + +## 5. Добавьте обработку сообщения + +Готовый пошаговый сценарий: [пересылка уведомлений в Telegram](n8n-telegram.md). + + +Готовый приёмник только подтверждает входящий запрос: он не отправляет сообщение +в Telegram, не сохраняет его в отдельную очередь и не удаляет дубли. + +Добавьте нужные действия перед Respond to Webhook и отправляйте ACK после +успешного завершения того действия, которое хотите считать приёмом сообщения. +Для долгой обработки сначала надёжно сохраните событие в собственной очереди или +БД, затем верните ACK, а последующие действия выполняйте отдельно. + +Клиент использует 10-секундные таймауты подключения и чтения. Если ответ потерян, +он может повторить уже обработанный запрос. Используйте `event_id` как уникальный +ключ в хранилище; уже принятый дубль должен получить тот же успешный ACK. +Отдельные операции «проверить наличие → добавить» без уникального ограничения не +защищают от двух одновременных запросов. + +Если отправить ACK **до** обработки, приложение удалит тело события из своей +очереди после подтверждения. Последующая ошибка в n8n не вызовет повтор на телефоне. +Статус успешного execution в n8n и успешное подтверждение клиенту — разные вещи. + +## Проверка без телефона + +Следующий запрос содержит только синтетические данные. Подставьте свой Production +URL и при каждом новом тесте используйте новый `event_id`: + +Перед запуском задайте в оболочке переменную `WEBHOOK_TOKEN` с тем же секретным токеном. + +```sh +curl --fail-with-body --max-time 10 \ + -X POST 'https://n8n.example.org/webhook/message487/ВАШ-ПУТЬ' \ + -H 'Content-Type: application/json' \ + -H "Authorization: Bearer ${WEBHOOK_TOKEN:?Set WEBHOOK_TOKEN}" \ + --data '{"schema_version":1,"event_id":"manual-check-001","device_id":"manual-test","device_code":"test-phone","message_type":"test","occurred_at":"2026-09-09T09:00:00Z","source":"life.andre.message487","source_name":"Message487","text":"Synthetic connection test"}' +``` + +Ожидаемый ответ: `{"status":"accepted","event_id":"manual-check-001"}` с HTTP 200. +Это проверяет серверный контракт; реальную доставку из Android проверьте кнопкой +тестового события и затем новым уведомлением или SMS. + +## Если доставка не работает + +| Симптом | Что проверить | +| --- | --- | +| HTTP 404 | Production URL, публикацию workflow, метод POST и путь | +| HTTP 401/403 | Настройки авторизации и ограничения доступа на proxy/n8n | +| HTTP 301/302 | Укажите конечный URL: клиент не следует redirect | +| `INVALID_ACK` при HTTP 200 | JSON-объект, `status: accepted`, точное совпадение `event_id`, режим ответа Webhook | +| Таймаут / сетевая ошибка | Доступность адреса с телефона, TLS, firewall, время до ответа | +| Нет execution в редакторе | Откройте вкладку Executions, проверьте сохранение успешных запусков | +| Тест проходит, а сообщений нет | Источники, разрешения Android, выбор приложений и паузу пересылки | + +Сетевые ошибки, таймауты, HTTP 408/425/429 и 5xx приводят к автоматическим повторам. +Неверный ACK и прочие HTTP-ошибки требуют вмешательства и ручного повтора из журнала. +Изменение URL в настройках влияет только на **новые** события: уже поставленные +в очередь сохраняют прежний адрес. После исправления подключения отправьте новый +тест; старые записи при необходимости удалите отдельно. + +Для разбора ошибок откройте значок диагностики в верхней панели приложения. +[Диагностический лог](diagnostics.md) показывает исход доставки без текста сообщений. + +Токен хранится на устройстве зашифрованным. Смена URL или токена применяется только +к новым событиям: очередь сохраняет исходные значения. Старые события без токена +блокируются. После обновления с 0.0.1 введите токен, отправьте новый тест и удалите +ненужные заблокированные события. История n8n может сохранять заголовки с токеном; +ограничьте доступ и срок хранения. diff --git a/docs/ru/n8n-telegram.md b/docs/ru/n8n-telegram.md index 4db02b3..77c4392 100644 --- a/docs/ru/n8n-telegram.md +++ b/docs/ru/n8n-telegram.md @@ -2,8 +2,9 @@ [English](../en/n8n-telegram.md) | [Русский](../ru/n8n-telegram.md) -Сначала настройте [приём webhook в n8n](n8n-webhook.md) и проверьте тестовое событие. -Там же есть ссылки на официальную документацию, n8n Cloud и самостоятельную установку. +Сначала подключите приложение по инструкции для [n8n Cloud](n8n-cloud.md) +или [собственного сервера](n8n-self-hosted.md) и проверьте тестовое событие. +Дальнейшие шаги одинаковы для обоих вариантов. Telegram-токен хранится в **Credentials n8n**; в Android-приложение его вводить не нужно. Сообщения будут доступны выбранному Telegram-чату и могут сохраняться в истории n8n. diff --git a/docs/ru/n8n-webhook.md b/docs/ru/n8n-webhook.md index 6745eaa..e20fb62 100644 --- a/docs/ru/n8n-webhook.md +++ b/docs/ru/n8n-webhook.md @@ -1,223 +1,23 @@ -# Как подключить Message487 к n8n +# Подключение Message487 к n8n [English](../en/n8n-webhook.md) | [Русский](../ru/n8n-webhook.md) -Для установки на телефон см. [инструкцию по APK и ограничениям Android](apk-installation.md). +Выберите инструкцию по тому, где работает ваш n8n: -Инструкция для Message487 0.0.2 и новее, с Bearer-авторизацией. Нужен доступ к редактору n8n и HTTPS-адрес, -доступный с телефона. Для локального Android-эмулятора используйте debug-сборку и -[готовый DevServer](../../DevServer/README.md). Релизный APK не принимает HTTP-адреса. - -## Где запустить n8n - -- [Официальная документация n8n](https://docs.n8n.io/) — узлы, выражения и работа с workflow. -- [n8n Cloud: начало работы](https://docs.n8n.io/deploy/use-n8n-cloud/start-your-free-trial) — облачная версия без установки сервера. -- [Облако или собственный сервер](https://docs.n8n.io/choose-how-to-use-n8n) — сравнение вариантов запуска. -- [Самостоятельная установка](https://docs.n8n.io/deploy/host-n8n/install-options) — варианты развёртывания. -- [Установка с Docker Compose](https://docs.n8n.io/deploy/host-n8n/install-options/install-using-docker-compose) — официальная инструкция. - -Для n8n Cloud используйте HTTPS Production URL своего workspace. Для собственного -сервера настройте доступ по HTTPS, хранение данных и резервные копии. -[DevServer](../../DevServer/README.md) предназначен для локальной разработки, -а не для публикации в интернете с его тестовыми учётными данными. - -## 1. Создайте принимающий workflow - -Быстрее всего импортировать [receive.json](../../DevServer/workflows/receive.json) -через **Import from File** в меню редактора n8n. Это готовый пример приёмника с -проверкой базовых полей и подтверждением `event_id`. Импортируйте его как отдельный -workflow; не заменяйте им рабочий сценарий с вашими действиями. - -В импортированном workflow уже соединены два узла: - -```mermaid -flowchart LR - W[Webhook: POST] --> R[Respond to Webhook: JSON ACK] -``` - -Для ручной настройки создайте те же узлы. В узле **Webhook** установите: - -| Поле | Значение | -| --- | --- | -| HTTP Method | `POST` | -| Path | Уникальный путь, например `message487/receive-<случайная-строка>` | -| Authentication | `Header Auth` | -| Respond | `Using 'Respond to Webhook' Node` | - -Создайте credential **Header Auth**: **Name** = `Authorization`, **Value** = `Bearer <токен>`. -Сгенерируйте собственный токен командой `openssl rand -hex 32`, замените `<токен>` -и выберите credential в Webhook, в том числе после импорта файла. Публичный тестовый -credential DevServer нельзя использовать на рабочем сервере. Пароль редактора n8n -не заменяет авторизацию веб-хука. См. [официальную документацию](https://docs.n8n.io/integrations/builtin/credentials/webhook/). - -В узле **Respond to Webhook** выберите **Respond With → JSON**, добавьте -**Response Code → 200**, а **Response Body** переключите в режим **Expression**: - -```javascript -{{ { status: 'accepted', event_id: $('Webhook').first().json.body.event_id } }} -``` - -Здесь `Webhook` — имя первого узла; при переименовании исправьте ссылку в выражении. -Этот минимальный ручной пример подтверждает запрос без валидации. Импортированный -`receive.json` дополнительно проверяет `schema_version`, `event_id`, `message_type` -и `text` и возвращает HTTP 400 для некорректного тела. - -Клиент ждёт JSON-объект следующего вида, а не массив, строку с JSON или HTML: - -```json -{"status":"accepted","event_id":"тот-же-event_id-что-в-запросе"} -``` - -`status` должен быть ровно `accepted`, а `event_id` — совпадать с запросом. -Обычный ответ n8n «Workflow got started» не подходит для режима подтверждения. -Настройки узлов описаны в документации [Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/) -и [Respond to Webhook](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.respondtowebhook/). - -## 2. Опубликуйте workflow и скопируйте URL - -Нажмите **Publish** (в более старых версиях n8n — включите **Active**). В узле -Webhook скопируйте **Production URL**, например: - -```text -https://n8n.example.org/webhook/message487/receive-<случайная-строка> -``` - -Не используйте постоянным адресом **Test URL** с `/webhook-test/`: он предназначен -для временного прослушивания через **Listen for test event**. Production URL -работает для опубликованного workflow, а его вызовы смотрят во вкладке **Executions**. -После изменения workflow опубликуйте изменения повторно. - -Если n8n стоит за reverse proxy и показывает внутренний адрес, настройте внешний -`WEBHOOK_URL`, число доверенных proxy в `N8N_PROXY_HOPS` и forwarded-заголовки по -[инструкции n8n для reverse proxy](https://docs.n8n.io/deploy/host-n8n/configure-n8n/basic-configuration/configuration-examples/configure-webhook-urls-with-reverse-proxy). -Телефон должен обращаться сразу к конечному HTTPS URL с доверенным сертификатом: -Message487 не следует HTTP-перенаправлениям и не отключает проверку TLS. - -## 3. Настройте приложение - -1. Откройте **Подключение / Connection**. -2. Вставьте полный Production URL в поле веб-хука. -3. Введите тот же токен в **Токен веб-хука**, без `Bearer `. -4. Задайте понятный **Код устройства / Device code**, например `personal-phone`. -5. Оставьте включённым **Подтверждение n8n / n8n confirmation**. -6. Нажмите кнопку сохранения и отправки тестового события. -7. В **Журнале / Journal** откройте событие и проверьте подтверждение и HTTP 200. - -После успешного теста включите нужные источники в **Источниках / Sources**: -для уведомлений выдайте системный доступ и выберите приложения; для SMS выдайте -разрешение на получение SMS. Если выбраны и SMS, и уведомления SMS-приложения, -одно входящее SMS может породить два разных события. - -Для эмулятора готовый DevServer использует -`http://10.0.2.2:5678/webhook/message487/receive`. Такой URL допустим только в -debug-сборке. На физическом телефоне `localhost` обозначает сам телефон, а -`10.0.2.2` не является адресом вашего компьютера. - -## 4. Посмотрите полученные данные - -В n8n откройте **Executions → нужный запуск → Webhook → Output → body**. Найдите -`event_id` из журнала приложения. Для сохранения успешных запусков включите -соответствующую настройку сохранения execution data; в DevServer она уже включена. -История n8n содержит полные сообщения, поэтому настройте её срок хранения и доступ. - -Пример тела уведомления: - -```json -{ - "schema_version": 1, - "event_id": "5d8ee1a5-9360-4b0e-8412-942b2e1c99ab", - "device_id": "43b55766-95b6-40b8-8f4f-c0240f547914", - "device_code": "personal-phone", - "message_type": "notification", - "occurred_at": "2026-09-09T09:00:00Z", - "source": "org.example.chat", - "source_name": "Example Chat", - "title": "Тестовое уведомление", - "text": "Проверка подключения" -} -``` - -| Поле | Значение | -| --- | --- | -| `event_id` | ID события; сохраняется при повторах доставки | -| `device_id` | ID установки приложения | -| `device_code` | Редактируемая метка устройства | -| `message_type` | `test`, `notification` или `sms` | -| `occurred_at` | Время события в формате ISO 8601 | -| `source` / `source_name` | Пакет источника / имя приложения; для SMS источник `android` | -| `title` | Заголовок уведомления; отсутствует у SMS и теста | -| `sender` | Отправитель SMS; отсутствует у уведомления и теста | -| `text` | Текст события | - -В узле сразу после Webhook доступны выражения `{{ $json.body.text }}` и -`{{ $json.body.device_code }}`. Если промежуточный узел меняет данные, обращайтесь -к исходному событию явно: `{{ $('Webhook').first().json.body.text }}`. - -## 5. Добавьте обработку сообщения - -Готовый пошаговый сценарий: [пересылка уведомлений в Telegram](n8n-telegram.md). - - -Готовый приёмник только подтверждает входящий запрос: он не отправляет сообщение -в Telegram, не сохраняет его в отдельную очередь и не удаляет дубли. - -Добавьте нужные действия перед Respond to Webhook и отправляйте ACK после -успешного завершения того действия, которое хотите считать приёмом сообщения. -Для долгой обработки сначала надёжно сохраните событие в собственной очереди или -БД, затем верните ACK, а последующие действия выполняйте отдельно. - -Клиент использует 10-секундные таймауты подключения и чтения. Если ответ потерян, -он может повторить уже обработанный запрос. Используйте `event_id` как уникальный -ключ в хранилище; уже принятый дубль должен получить тот же успешный ACK. -Отдельные операции «проверить наличие → добавить» без уникального ограничения не -защищают от двух одновременных запросов. - -Если отправить ACK **до** обработки, приложение удалит тело события из своей -очереди после подтверждения. Последующая ошибка в n8n не вызовет повтор на телефоне. -Статус успешного execution в n8n и успешное подтверждение клиенту — разные вещи. - -## Проверка без телефона - -Следующий запрос содержит только синтетические данные. Подставьте свой Production -URL и при каждом новом тесте используйте новый `event_id`: - -Перед запуском задайте в оболочке переменную `WEBHOOK_TOKEN` с тем же секретным токеном. - -```sh -curl --fail-with-body --max-time 10 \ - -X POST 'https://n8n.example.org/webhook/message487/ВАШ-ПУТЬ' \ - -H 'Content-Type: application/json' \ - -H "Authorization: Bearer ${WEBHOOK_TOKEN:?Set WEBHOOK_TOKEN}" \ - --data '{"schema_version":1,"event_id":"manual-check-001","device_id":"manual-test","device_code":"test-phone","message_type":"test","occurred_at":"2026-09-09T09:00:00Z","source":"life.andre.message487","source_name":"Message487","text":"Synthetic connection test"}' -``` - -Ожидаемый ответ: `{"status":"accepted","event_id":"manual-check-001"}` с HTTP 200. -Это проверяет серверный контракт; реальную доставку из Android проверьте кнопкой -тестового события и затем новым уведомлением или SMS. - -## Если доставка не работает - -| Симптом | Что проверить | +| Вариант | Инструкция | | --- | --- | -| HTTP 404 | Production URL, публикацию workflow, метод POST и путь | -| HTTP 401/403 | Настройки авторизации и ограничения доступа на proxy/n8n | -| HTTP 301/302 | Укажите конечный URL: клиент не следует redirect | -| `INVALID_ACK` при HTTP 200 | JSON-объект, `status: accepted`, точное совпадение `event_id`, режим ответа Webhook | -| Таймаут / сетевая ошибка | Доступность адреса с телефона, TLS, firewall, время до ответа | -| Нет execution в редакторе | Откройте вкладку Executions, проверьте сохранение успешных запусков | -| Тест проходит, а сообщений нет | Источники, разрешения Android, выбор приложений и паузу пересылки | +| Хочу настроить всё в браузере, без собственного сервера | [n8n Cloud: пошаговое подключение](n8n-cloud.md) | +| n8n установлен на моём сервере или сервере организации | [Собственный сервер: подключение и диагностика](n8n-self-hosted.md) | +| Разрабатываю приложение и использую Android-эмулятор | [Локальный DevServer](../../DevServer/README.md) | -Сетевые ошибки, таймауты, HTTP 408/425/429 и 5xx приводят к автоматическим повторам. -Неверный ACK и прочие HTTP-ошибки требуют вмешательства и ручного повтора из журнала. -Изменение URL в настройках влияет только на **новые** события: уже поставленные -в очередь сохраняют прежний адрес. После исправления подключения отправьте новый -тест; старые записи при необходимости удалите отдельно. +Начинающим рекомендуем **n8n Cloud**: сервер обслуживает n8n, а настройка выполняется +через сайт. У облака есть пробный период и платные тарифы; актуальные условия указаны +на [сайте n8n](https://n8n.io/pricing/). -Для разбора ошибок откройте значок диагностики в верхней панели приложения. -[Диагностический лог](diagnostics.md) показывает исход доставки без текста сообщений. +В обоих вариантах приложение отправляет сообщения на защищённый адрес и получает +подтверждение приёма. После успешного теста можно настроить +[пересылку в Telegram](n8n-telegram.md). -Токен хранится на устройстве зашифрованным. Смена URL или токена применяется только -к новым событиям: очередь сохраняет исходные значения. Старые события без токена -блокируются. После обновления с 0.0.1 введите токен, отправьте новый тест и удалите -ненужные заблокированные события. История n8n может сохранять заголовки с токеном; -ограничьте доступ и срок хранения. +Если приложение ещё не установлено, начните с [установки APK](apk-installation.md). +Дополнительная справка: [документация n8n](https://docs.n8n.io/), +[сравнение облака и собственного сервера](https://docs.n8n.io/choose-how-to-use-n8n).