telegram-ask 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +143 -0
  3. package/dist/approval/constants.js +10 -0
  4. package/dist/approval/formatter.js +27 -0
  5. package/dist/approval/index.js +5 -0
  6. package/dist/approval/parser.js +43 -0
  7. package/dist/approval/pending.js +47 -0
  8. package/dist/approval/service.js +65 -0
  9. package/dist/approval/types.js +1 -0
  10. package/dist/cli.js +161 -0
  11. package/dist/commands/constants.js +14 -0
  12. package/dist/commands/index.js +8 -0
  13. package/dist/commands/init.js +159 -0
  14. package/dist/commands/owner.js +18 -0
  15. package/dist/commands/pairing-wait.js +65 -0
  16. package/dist/commands/prompts.js +55 -0
  17. package/dist/commands/reset-owner.js +58 -0
  18. package/dist/commands/status.js +42 -0
  19. package/dist/commands/test.js +22 -0
  20. package/dist/commands/types.js +1 -0
  21. package/dist/commands/uninstall.js +30 -0
  22. package/dist/config/constants.js +13 -0
  23. package/dist/config/index.js +2 -0
  24. package/dist/config/schema.js +7 -0
  25. package/dist/config/store.js +104 -0
  26. package/dist/config/types.js +1 -0
  27. package/dist/daemon/index.js +1 -0
  28. package/dist/daemon/service.js +82 -0
  29. package/dist/install/compose.js +123 -0
  30. package/dist/install/constants.js +28 -0
  31. package/dist/install/envfile.js +50 -0
  32. package/dist/install/index.js +9 -0
  33. package/dist/install/paths.js +23 -0
  34. package/dist/install/quadlet.js +167 -0
  35. package/dist/install/registry.js +98 -0
  36. package/dist/install/schema.js +10 -0
  37. package/dist/install/state.js +24 -0
  38. package/dist/install/systemd.js +151 -0
  39. package/dist/install/templates.js +87 -0
  40. package/dist/install/types.js +1 -0
  41. package/dist/server/constants.js +2 -0
  42. package/dist/server/index.js +2 -0
  43. package/dist/server/schema.js +6 -0
  44. package/dist/server/server.js +74 -0
  45. package/dist/server/types.js +1 -0
  46. package/dist/system/constants.js +6 -0
  47. package/dist/system/exec.js +30 -0
  48. package/dist/system/files.js +50 -0
  49. package/dist/system/host.js +48 -0
  50. package/dist/system/index.js +3 -0
  51. package/dist/system/types.js +1 -0
  52. package/dist/telegram/adapter.js +99 -0
  53. package/dist/telegram/constants.js +12 -0
  54. package/dist/telegram/index.js +3 -0
  55. package/dist/telegram/pairing.js +60 -0
  56. package/dist/telegram/types.js +1 -0
  57. package/package.json +43 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # telegram-ask
2
+
3
+ Small local service that asks you a question on Telegram and hands the answer back to the caller. A script POSTs a question with button options to a local HTTP API; the bot sends it to you with inline buttons, and the request returns when you tap one or the timeout fires.
4
+
5
+ Single owner, one Telegram user. Needs Node 24+ for `npx` and the systemd target; the container targets bring their own Node.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ npx telegram-ask init
11
+ ```
12
+
13
+ Create a bot with @BotFather first and have the token ready. `init`:
14
+
15
+ 1. Detects which targets work here (Podman Quadlet, Docker Compose, systemd) and asks where the bot should run. The first usable one in that order is the default. Or pass it: `init quadlet`, `init compose`, `init systemd`.
16
+ 2. Asks for the bot token (input hidden) and checks it with Telegram. Port is 8787; use `--port N` to change it. It refuses a port that's already in use.
17
+ 3. Installs and starts the service, then waits for pairing.
18
+
19
+ If it finds an existing install it offers to replace it, reusing the saved token and owner (no re-pairing). If there's no install but a token was kept by `uninstall`, it reuses that (and the owner) too. If `init` fails partway, run it again; the old install record and saved token are kept until the new install succeeds.
20
+
21
+ ## Pairing
22
+
23
+ The first time (and after `reset-owner`), the bot only answers whoever proves they own it. `init` prints a code like `ABCD-EFGH` and a link. Either send `/start ABCD-EFGH` to your bot, or open `https://t.me/<bot>?start=ABCDEFGH`. Case and the dash don't matter. After 5 wrong codes from one Telegram user that user is blocked until the service restarts.
24
+
25
+ If you lose the code: `telegram-ask status` prints it again while unpaired.
26
+
27
+ To move to another Telegram account:
28
+
29
+ ```
30
+ telegram-ask reset-owner
31
+ ```
32
+
33
+ It asks first, clears the owner, restarts the service and waits for a new pairing.
34
+
35
+ ## Targets
36
+
37
+ All targets keep their files under `~/.config/telegram-ask/` (or `$XDG_CONFIG_HOME/telegram-ask/`). `install.json` there records which target is installed, its port and version. It's what `status`, `reset-owner` and `uninstall` read.
38
+
39
+ ### Podman Quadlet
40
+
41
+ Needs Podman 4.4 or newer and a systemd user session. Written:
42
+
43
+ - `~/.config/telegram-ask/quadlet/` with a `Dockerfile`, `.env` (token, port, owner) and a `.dockerignore` that keeps `.env` out of the image build
44
+ - `~/.config/containers/systemd/telegram-ask.container`
45
+ - image `localhost/telegram-ask:<version>`, volume `telegram-ask-data` (holds the pairing state)
46
+
47
+ Runs as a user service named `telegram-ask`. `init` enables linger (`loginctl enable-linger`) if needed so it survives logout; it tells you if that needs a password. Logs:
48
+
49
+ ```
50
+ journalctl --user -u telegram-ask -f
51
+ ```
52
+
53
+ ### Docker Compose
54
+
55
+ Needs Docker with the compose v2 plugin, and your user in the `docker` group (otherwise `init` reports it can't talk to docker and skips this target). Written:
56
+
57
+ - `~/.config/telegram-ask/compose/` with `Dockerfile`, `compose.yaml`, `.env` and `.dockerignore`
58
+ - a named volume `data` in the `telegram-ask` compose project
59
+
60
+ Logs:
61
+
62
+ ```
63
+ docker compose -f ~/.config/telegram-ask/compose/compose.yaml logs -f
64
+ ```
65
+
66
+ This target is untested on real Docker so far.
67
+
68
+ ### systemd (npm)
69
+
70
+ No container. `init` installs the package globally with npm (`npm i -g`), or into `~/.local/share/telegram-ask/npm` if the global prefix isn't writable. If you ran `init` from an already-installed copy, it uses that. Written:
71
+
72
+ - `~/.config/telegram-ask/config.json` (token, port, owner)
73
+ - `~/.config/systemd/user/telegram-ask.service` with absolute paths to `node`, the CLI and the config file (`TELEGRAM_ASK_CONFIG` is always set in the unit, and `install.json` records the same path)
74
+
75
+ Logs: `journalctl --user -u telegram-ask -f`. Linger is handled as for Quadlet.
76
+
77
+ Config is read from `$TELEGRAM_ASK_CONFIG`, else `$XDG_CONFIG_HOME/telegram-ask/config.json`, else `~/.config/telegram-ask/config.json`. The env vars `BOT_TOKEN`, `OWNER_ID`, `PORT` and `HOST` override the file. `HOST` defaults to `127.0.0.1` (the container targets set `0.0.0.0` inside the container and publish only on `127.0.0.1`).
78
+
79
+ ## Commands
80
+
81
+ ```
82
+ telegram-ask init [systemd|compose|quadlet] [--port N]
83
+ telegram-ask status
84
+ telegram-ask test
85
+ telegram-ask reset-owner
86
+ telegram-ask uninstall
87
+ telegram-ask start
88
+ ```
89
+
90
+ - `status`: target, version, port, whether it's running, and pairing state (with the code if unpaired).
91
+ - `test`: sends "This is a test" with Approve/Decline buttons (Decline on timeout) and prints the response.
92
+ - `uninstall`: stops and removes the service, then asks whether to also delete the bot token and paired owner. Answer no to keep them: `config.json` (systemd) or the target's `.env` and volume stay on disk, and a later `init` finds them and reuses the token and owner without asking. Yes also removes the target's image, volume and files. For systemd the npm package stays; `uninstall` prints the command to remove it, `npm rm -g telegram-ask`, or `npm rm -g --prefix ~/.local/share/telegram-ask/npm telegram-ask` if `init` installed it into that prefix.
93
+ - `start`: runs the service in the foreground. The installed services use this.
94
+
95
+ ## One instance per token
96
+
97
+ Only one instance can run per bot token; two would fight over Telegram's updates. `init` replaces an existing install rather than adding a second. Stop anything you started by hand, including a `docker run` container, before running `init`.
98
+
99
+ ## Upgrading from the old setup
100
+
101
+ Earlier versions used `npm run onboard` and `deploy/install-service.sh`. `init` recognizes that systemd unit as a legacy install, offers to replace it, and reuses the token and owner from the existing config. Stop any hand-run Docker container using the same token first. The old config file is kept and reused if you pick the systemd target.
102
+
103
+ ## API
104
+
105
+ `POST /request` on `127.0.0.1:<port>`, JSON body:
106
+
107
+ | Field | Type | Required | Notes |
108
+ | --------------- | -------- | -------- | ------------------------------------------------------ |
109
+ | `text` | string | yes | Question shown in Telegram. Non-empty, max 3900 chars. |
110
+ | `options` | string[] | yes | Button labels. Non-empty, unique, non-empty strings. |
111
+ | `timeoutOption` | string | yes | Answer returned on timeout. Must be one of `options`. |
112
+ | `timeout` | number | no | Seconds. Default and max 300. Must be positive. |
113
+
114
+ The request stays open until you tap a button or the timeout fires, then returns `200`:
115
+
116
+ ```json
117
+ { "answer": "Approve", "timedOut": false }
118
+ ```
119
+
120
+ On timeout, `answer` is `timeoutOption` and `timedOut` is `true`. Many requests can be pending at once.
121
+
122
+ ```
123
+ curl -s -X POST http://127.0.0.1:8787/request \
124
+ -H 'content-type: application/json' \
125
+ -d '{"text":"Deploy?","options":["Approve","Decline"],"timeoutOption":"Decline","timeout":60}'
126
+ ```
127
+
128
+ Errors are JSON `{ "error": "..." }`:
129
+
130
+ | Status | Meaning |
131
+ | ------ | ----------------------------------------------------------------------- |
132
+ | 400 | Body isn't valid JSON or fails validation. Nothing is sent to Telegram. |
133
+ | 413 | Body over 64 KiB. |
134
+ | 502 | Telegram message couldn't be sent. |
135
+ | 500 | Internal error, or the request was cancelled. |
136
+ | 404 | Path isn't `/request`. |
137
+ | 405 | Method isn't POST. |
138
+
139
+ If the caller disconnects early, the request is dropped and the Telegram message is edited to a "cancelled" line. Pending requests live in memory, so a restart drops them (callers see a connection error).
140
+
141
+ ## Security
142
+
143
+ There's no auth. The API is meant for localhost only; don't expose it. The container targets publish the port on `127.0.0.1` only; keep it that way.
@@ -0,0 +1,10 @@
1
+ /** Hard cap on a request's timeout; also the timeout when the client sends none. */
2
+ export const MAX_TIMEOUT_SECONDS = 300;
3
+ /** Longest allowed option label, in characters. */
4
+ export const MAX_OPTION_LENGTH = 64;
5
+ /** Leaves room for the appended result line under Telegram's 4096 message limit. */
6
+ export const MAX_TEXT_LENGTH = 3900;
7
+ /** Shared settlement for a request cancelled before an answer. */
8
+ export const CANCELLED_SETTLEMENT = { kind: 'cancelled' };
9
+ /** Shared result for `ApprovalService.request` when its signal aborted. */
10
+ export const CANCELLED_RESULT = { kind: 'cancelled' };
@@ -0,0 +1,27 @@
1
+ function formatTime(at) {
2
+ const hours = String(at.getHours()).padStart(2, '0');
3
+ const minutes = String(at.getMinutes()).padStart(2, '0');
4
+ return `${hours}:${minutes}`;
5
+ }
6
+ /**
7
+ * One-line outcome shown under the request: answer, timeout or cancellation, with the local time as
8
+ * HH:MM.
9
+ */
10
+ export function formatResultLine(settlement, at) {
11
+ const time = formatTime(at);
12
+ switch (settlement.kind) {
13
+ case 'answered':
14
+ return `✅ ${settlement.answer}, ${time}`;
15
+ case 'timedOut':
16
+ return `⏱ Timed out, ${settlement.answer}, ${time}`;
17
+ case 'cancelled':
18
+ return `🚫 Cancelled, ${time}`;
19
+ }
20
+ }
21
+ /**
22
+ * The original request text, a blank line, then the result line; this replaces the message once
23
+ * settled.
24
+ */
25
+ export function formatFinalText(original, settlement, at) {
26
+ return `${original}\n\n${formatResultLine(settlement, at)}`;
27
+ }
@@ -0,0 +1,5 @@
1
+ export { MAX_OPTION_LENGTH, MAX_TEXT_LENGTH, MAX_TIMEOUT_SECONDS } from './constants.js';
2
+ export { formatFinalText, formatResultLine } from './formatter.js';
3
+ export { parseApprovalRequest } from './parser.js';
4
+ export { PendingRequests } from './pending.js';
5
+ export { ApprovalService, SendError } from './service.js';
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import { MAX_OPTION_LENGTH, MAX_TEXT_LENGTH, MAX_TIMEOUT_SECONDS } from './constants.js';
3
+ const TEXT_ERROR = 'text must be a non-empty string';
4
+ const OPTIONS_ERROR = 'options must be a non-empty array';
5
+ const OPTION_ERROR = `options must contain only non-empty strings of at most ${MAX_OPTION_LENGTH} characters`;
6
+ const TIMEOUT_ERROR = 'timeout must be a finite positive number';
7
+ // Messages are part of the API (README error table); only the first issue is reported.
8
+ const approvalRequestSchema = z
9
+ .object({
10
+ text: z
11
+ .string({ error: TEXT_ERROR })
12
+ .refine((text) => text.trim().length > 0, TEXT_ERROR)
13
+ .refine((text) => text.length <= MAX_TEXT_LENGTH, `text must be at most ${MAX_TEXT_LENGTH} characters`),
14
+ options: z
15
+ .array(z
16
+ .string({ error: OPTION_ERROR })
17
+ .min(1, OPTION_ERROR)
18
+ .max(MAX_OPTION_LENGTH, OPTION_ERROR), {
19
+ error: OPTIONS_ERROR,
20
+ })
21
+ .min(1, OPTIONS_ERROR)
22
+ .refine((options) => new Set(options).size === options.length, 'options must be unique'),
23
+ timeoutOption: z.string({ error: 'timeoutOption must be a string' }),
24
+ timeout: z.number({ error: TIMEOUT_ERROR }).positive(TIMEOUT_ERROR).optional(),
25
+ }, { error: 'body must be a JSON object' })
26
+ .refine((body) => body.options.includes(body.timeoutOption), 'timeoutOption must be one of options')
27
+ .transform(({ text, options, timeoutOption, timeout }) => ({
28
+ text,
29
+ options,
30
+ timeoutOption,
31
+ timeoutSeconds: Math.min(timeout ?? MAX_TIMEOUT_SECONDS, MAX_TIMEOUT_SECONDS),
32
+ }));
33
+ /**
34
+ * Validates a request body; never throws. Returns the first problem as `error`, and clamps
35
+ * `timeout` to the cap (the cap is also the default).
36
+ */
37
+ export function parseApprovalRequest(body) {
38
+ const result = approvalRequestSchema.safeParse(body);
39
+ if (result.success) {
40
+ return { ok: true, value: result.data };
41
+ }
42
+ return { ok: false, error: result.error.issues[0]?.message ?? 'invalid request' };
43
+ }
@@ -0,0 +1,47 @@
1
+ import { CANCELLED_SETTLEMENT } from './constants.js';
2
+ /**
3
+ * Open requests by id, each settling exactly once (answer, timeout or cancel); settling clears its
4
+ * timer.
5
+ */
6
+ export class PendingRequests {
7
+ #entries = new Map();
8
+ get size() {
9
+ return this.#entries.size;
10
+ }
11
+ /**
12
+ * Registers `request` and resolves with how it settled. The timeout settles it with the request's
13
+ * timeout option.
14
+ */
15
+ open(id, request) {
16
+ return new Promise((resolve) => {
17
+ const timer = setTimeout(() => this.#settle(id, { kind: 'timedOut', answer: request.timeoutOption }), request.timeoutSeconds * 1000);
18
+ this.#entries.set(id, { request, timer, resolve });
19
+ });
20
+ }
21
+ /**
22
+ * Settles with the option at `optionIndex`; false when the id is unknown or already settled, or
23
+ * the index is out of range.
24
+ */
25
+ answer(id, optionIndex) {
26
+ const entry = this.#entries.get(id);
27
+ const answer = entry?.request.options[optionIndex];
28
+ if (answer === undefined) {
29
+ return false;
30
+ }
31
+ return this.#settle(id, { kind: 'answered', answer });
32
+ }
33
+ /** Settles as cancelled; false when the id is unknown or already settled. */
34
+ cancel(id) {
35
+ return this.#settle(id, CANCELLED_SETTLEMENT);
36
+ }
37
+ #settle(id, settlement) {
38
+ const entry = this.#entries.get(id);
39
+ if (!entry) {
40
+ return false;
41
+ }
42
+ clearTimeout(entry.timer);
43
+ this.#entries.delete(id);
44
+ entry.resolve(settlement);
45
+ return true;
46
+ }
47
+ }
@@ -0,0 +1,65 @@
1
+ import { CANCELLED_RESULT } from './constants.js';
2
+ import { formatFinalText } from './formatter.js';
3
+ import { PendingRequests } from './pending.js';
4
+ /** The messenger failed to send the request; the original error is in `cause`. */
5
+ export class SendError extends Error {
6
+ }
7
+ /** Sends each request to the owner and waits for a tap, the timeout or an abort. */
8
+ export class ApprovalService {
9
+ #messenger;
10
+ #now;
11
+ #newId;
12
+ #pending = new PendingRequests();
13
+ constructor(messenger, now = () => new Date(), newId = () => crypto.randomUUID()) {
14
+ this.#messenger = messenger;
15
+ this.#now = now;
16
+ this.#newId = newId;
17
+ }
18
+ /**
19
+ * Resolves once settled. Throws `SendError` if the message can't be sent; a failed final edit is
20
+ * only logged. An aborted `signal` settles as cancelled.
21
+ */
22
+ async request(request, signal) {
23
+ const id = this.#newId();
24
+ let reference;
25
+ try {
26
+ reference = await this.#messenger.sendRequest(id, request.text, request.options);
27
+ }
28
+ catch (cause) {
29
+ throw new SendError('failed to send approval request', { cause });
30
+ }
31
+ const settled = this.#pending.open(id, request);
32
+ const onAbort = () => {
33
+ this.#pending.cancel(id);
34
+ };
35
+ // Checked after open() so an abort during sendRequest is not missed.
36
+ if (signal?.aborted) {
37
+ onAbort();
38
+ }
39
+ else {
40
+ signal?.addEventListener('abort', onAbort, { once: true });
41
+ }
42
+ const settlement = await settled;
43
+ signal?.removeEventListener('abort', onAbort);
44
+ try {
45
+ await this.#messenger.finalize(reference, formatFinalText(request.text, settlement, this.#now()));
46
+ }
47
+ catch (error) {
48
+ console.error('failed to finalize approval message', error);
49
+ }
50
+ if (settlement.kind === 'cancelled') {
51
+ return CANCELLED_RESULT;
52
+ }
53
+ return {
54
+ kind: 'completed',
55
+ outcome: { answer: settlement.answer, timedOut: settlement.kind === 'timedOut' },
56
+ };
57
+ }
58
+ /**
59
+ * Records a button tap; 'expired' when the request is unknown, already settled or the index is
60
+ * invalid.
61
+ */
62
+ tap(id, optionIndex) {
63
+ return this.#pending.answer(id, optionIndex) ? 'accepted' : 'expired';
64
+ }
65
+ }
@@ -0,0 +1 @@
1
+ export {};