@sockethub/platform-messenger 0.0.0-stage → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md CHANGED
@@ -1,3 +1,107 @@
1
- # Temporary Holding Version
1
+ # `@sockethub/platform-messenger`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Outgoing text messages through Meta's Messenger API. This is a stateless,
4
+ authenticated platform: set credentials, then send. No connect action or webhook
5
+ endpoint is needed. Incoming messages and recipient discovery are external.
6
+
7
+ ## Setup
8
+
9
+ The Sockethub CLI bundles this platform. For a custom server installation, install
10
+ `@sockethub/platform-messenger` and include it in your config's `platforms` list
11
+ alongside the other platforms you use. Node.js >= 20.19 and Redis >= 6 are required.
12
+
13
+ Use a Page access token with `pages_messaging`. The actor ID is your
14
+ Facebook Page ID; the target ID is the recipient's Page-scoped ID (PSID),
15
+ obtained through your external incoming-message integration. A username, phone
16
+ number, or ID scoped to a different app/account is not a substitute.
17
+
18
+ This implementation sends as a Facebook Page, not a personal Facebook profile.
19
+
20
+ Create a Meta developer app, add the messaging use case, connect your account,
21
+ and use app-role/tester accounts for a private development-mode proof of concept.
22
+ Public use and Human Agent access depend on Meta permissions and review; owning
23
+ the account does not remove those requirements. Obtain tokens outside Sockethub.
24
+
25
+ ## Examples app
26
+
27
+ Run `bun run dev` and open `/examples/messenger` on the Sockethub server.
28
+ Enter your account ID, access token, Graph API version, and scoped recipient ID
29
+ to send a text reply. Human Agent tagging is optional and off by default.
30
+
31
+ ## Usage
32
+
33
+ This server-side JavaScript example uses runtime environment variables. In a
34
+ browser, obtain credentials through your application's secure runtime flow.
35
+ Choose a supported Graph API version enabled for your Meta app explicitly.
36
+
37
+ ```javascript
38
+ import SockethubClient from '@sockethub/client';
39
+
40
+ const sc = await SockethubClient.connect('http://localhost:10550');
41
+ await sc.ready();
42
+ const actor = { id: process.env.META_ACCOUNT_ID, type: 'person' };
43
+
44
+ sc.socket.emit('credentials', {
45
+ '@context': sc.contextFor('messenger'),
46
+ type: 'credentials',
47
+ actor,
48
+ object: {
49
+ type: 'credentials',
50
+ token: process.env.META_ACCESS_TOKEN,
51
+ apiVersion: process.env.META_API_VERSION
52
+ }
53
+ }, (ack) => {
54
+ if (ack?.error) {
55
+ console.error(ack.error);
56
+ return;
57
+ }
58
+ sc.socket.emit('message', {
59
+ '@context': sc.contextFor('messenger'),
60
+ type: 'send',
61
+ actor,
62
+ target: { id: process.env.META_RECIPIENT_ID, type: 'person' },
63
+ object: { type: 'message', content: 'Hello from Sockethub!' }
64
+ }, (result) => {
65
+ if (result?.error) {
66
+ console.error(result.error);
67
+ return;
68
+ }
69
+ // A successful send returns the original activity with object.id set to
70
+ // Meta's message ID. This confirms API acceptance, not delivery or reading.
71
+ console.log(result.object?.id);
72
+ });
73
+ });
74
+
75
+ // On explicit logout or when switching users, clear the client-side replay
76
+ // state and disconnect. Credentials already stored for this server session
77
+ // stay usable until the socket disconnects; a new connection starts a fresh
78
+ // session that cannot reach them.
79
+ // sc.clearCredentials();
80
+ // sc.socket.disconnect();
81
+ ```
82
+
83
+ ## Limits and failures
84
+
85
+ - Text only, up to 2000 characters per message.
86
+ - Standard replies use Meta's normal messaging window. Sockethub does not track
87
+ incoming messages or calculate eligibility; Meta enforces its policies.
88
+ - Set `object.humanAgent: true` only for an eligible manual support reply when
89
+ your Meta app has Human Agent access. This explicitly adds `HUMAN_AGENT`;
90
+ Messenger also sets `messaging_type: MESSAGE_TAG`.
91
+ It does not grant access, verify human authorship, or restart the window.
92
+ - Meta error code `10` with subcode `2018278` or `2534022` returns the stable
93
+ marker `meta:messaging-window-closed` followed by the original diagnostic details.
94
+ Clients can recognise this marker in the acknowledgement's `error` string;
95
+ permission failures are not classified as window failures.
96
+ - Meta failures return the HTTP status, error code/subcode, and error message.
97
+ Requests time out after 15 seconds. There are no platform-level retries:
98
+ after a network timeout, delivery is unknown, so retrying may duplicate a send.
99
+ - No inbound messages, delivery/read receipts, OAuth onboarding, attachments,
100
+ conversation history, or webhook hosting.
101
+
102
+ See [Meta's Messenger API collection](https://www.postman.com/meta/messenger-platform-api/documentation/iyp204x/messenger-platform-api)
103
+ for access requirements and the underlying API.
104
+
105
+ API contract references:
106
+
107
+ - [Meta error codes](https://developers.facebook.com/docs/messenger-platform/error-codes/)
@@ -0,0 +1,168 @@
1
+ import type { ActivityStream, CredentialsObject, PlatformCallback, PlatformInterface, PlatformSession, StatelessPlatformConfig } from "@sockethub/schemas";
2
+ export interface MessengerCredentials extends CredentialsObject {
3
+ object: {
4
+ type: "credentials";
5
+ token: string;
6
+ apiVersion: string;
7
+ };
8
+ }
9
+ export default class Messenger implements PlatformInterface {
10
+ private readonly log;
11
+ config: StatelessPlatformConfig;
12
+ constructor(session: PlatformSession);
13
+ get schema(): {
14
+ name: string;
15
+ version: string;
16
+ contextUrl: string;
17
+ contextVersion: string;
18
+ schemaVersion: string;
19
+ messages: {
20
+ required: string[];
21
+ properties: {
22
+ type: {
23
+ enum: string[];
24
+ };
25
+ actor: {
26
+ type: string;
27
+ required: string[];
28
+ additionalProperties: boolean;
29
+ properties: {
30
+ id: {
31
+ type: string;
32
+ pattern: string;
33
+ maxLength: number;
34
+ };
35
+ type: {
36
+ const: string;
37
+ };
38
+ };
39
+ };
40
+ target: {
41
+ type: string;
42
+ required: string[];
43
+ additionalProperties: boolean;
44
+ properties: {
45
+ id: {
46
+ type: string;
47
+ pattern: string;
48
+ maxLength: number;
49
+ };
50
+ type: {
51
+ const: string;
52
+ };
53
+ };
54
+ };
55
+ object: {
56
+ type: string;
57
+ required: string[];
58
+ additionalProperties: boolean;
59
+ properties: {
60
+ type: {
61
+ const: string;
62
+ };
63
+ content: {
64
+ type: string;
65
+ minLength: number;
66
+ maxLength: number;
67
+ };
68
+ humanAgent: {
69
+ type: string;
70
+ };
71
+ };
72
+ };
73
+ };
74
+ };
75
+ credentials: {
76
+ required: string[];
77
+ properties: {
78
+ object: {
79
+ type: string;
80
+ required: string[];
81
+ additionalProperties: boolean;
82
+ properties: {
83
+ type: {
84
+ const: string;
85
+ };
86
+ token: {
87
+ type: string;
88
+ minLength: number;
89
+ maxLength: number;
90
+ pattern: string;
91
+ };
92
+ apiVersion: {
93
+ type: string;
94
+ pattern: string;
95
+ };
96
+ };
97
+ };
98
+ };
99
+ };
100
+ responses: {
101
+ type: string;
102
+ required: string[];
103
+ properties: {
104
+ "@context": {
105
+ type: string;
106
+ items: {
107
+ type: string;
108
+ };
109
+ };
110
+ type: {
111
+ const: string;
112
+ };
113
+ actor: {
114
+ type: string;
115
+ required: string[];
116
+ additionalProperties: boolean;
117
+ properties: {
118
+ id: {
119
+ type: string;
120
+ pattern: string;
121
+ maxLength: number;
122
+ };
123
+ type: {
124
+ const: string;
125
+ };
126
+ };
127
+ };
128
+ target: {
129
+ type: string;
130
+ required: string[];
131
+ additionalProperties: boolean;
132
+ properties: {
133
+ id: {
134
+ type: string;
135
+ pattern: string;
136
+ maxLength: number;
137
+ };
138
+ type: {
139
+ const: string;
140
+ };
141
+ };
142
+ };
143
+ object: {
144
+ type: string;
145
+ required: string[];
146
+ properties: {
147
+ type: {
148
+ const: string;
149
+ };
150
+ id: {
151
+ type: string;
152
+ minLength: number;
153
+ };
154
+ content: {
155
+ type: string;
156
+ };
157
+ humanAgent: {
158
+ type: string;
159
+ };
160
+ };
161
+ };
162
+ };
163
+ };
164
+ };
165
+ isInitialized(): boolean;
166
+ cleanup(done: PlatformCallback): void;
167
+ send(job: ActivityStream, credentials: MessengerCredentials, done: PlatformCallback): Promise<void>;
168
+ }
package/dist/index.js ADDED
@@ -0,0 +1,210 @@
1
+ // package.json
2
+ var package_default = {
3
+ name: "@sockethub/platform-messenger",
4
+ description: "Outgoing text messages through the Meta Messenger API",
5
+ version: "1.0.0-beta.2",
6
+ type: "module",
7
+ private: false,
8
+ license: "LGPL-3.0+",
9
+ publishConfig: {
10
+ access: "public"
11
+ },
12
+ main: "./dist/index.js",
13
+ types: "./dist/index.d.ts",
14
+ exports: {
15
+ ".": {
16
+ types: "./dist/index.d.ts",
17
+ import: "./dist/index.js",
18
+ default: "./dist/index.js"
19
+ }
20
+ },
21
+ files: [
22
+ "dist/"
23
+ ],
24
+ engines: {
25
+ node: ">=20.19"
26
+ },
27
+ scripts: {
28
+ build: "bun build src/index.ts --outdir dist --target node --format esm --sourcemap=external",
29
+ clean: "rm -rf dist",
30
+ "clean:deps": "rm -rf node_modules",
31
+ test: "bun test src/"
32
+ },
33
+ dependencies: {
34
+ "@sockethub/schemas": "^3.0.0-beta.2"
35
+ },
36
+ devDependencies: {
37
+ "@types/bun": "latest"
38
+ },
39
+ peerDependencies: {
40
+ "@sockethub/server": "^5.0.0-beta.2"
41
+ },
42
+ peerDependenciesMeta: {
43
+ "@sockethub/server": {
44
+ optional: true
45
+ }
46
+ },
47
+ gitHead: "1f74d4e07311496f0acc021855137bc197d79eab"
48
+ };
49
+
50
+ // src/schema.ts
51
+ var identity = {
52
+ type: "object",
53
+ required: ["id", "type"],
54
+ additionalProperties: false,
55
+ properties: {
56
+ id: { type: "string", pattern: "^[0-9]+$", maxLength: 128 },
57
+ type: { const: "person" }
58
+ }
59
+ };
60
+ var PlatformMessengerSchema = {
61
+ name: "messenger",
62
+ version: package_default.version,
63
+ contextUrl: "https://sockethub.org/ns/context/platform/messenger/v1.jsonld",
64
+ contextVersion: "1",
65
+ schemaVersion: "1",
66
+ messages: {
67
+ required: ["type", "actor", "target", "object"],
68
+ properties: {
69
+ type: { enum: ["send"] },
70
+ actor: identity,
71
+ target: identity,
72
+ object: {
73
+ type: "object",
74
+ required: ["type", "content"],
75
+ additionalProperties: false,
76
+ properties: {
77
+ type: { const: "message" },
78
+ content: { type: "string", minLength: 1, maxLength: 2000 },
79
+ humanAgent: { type: "boolean" }
80
+ }
81
+ }
82
+ }
83
+ },
84
+ credentials: {
85
+ required: ["object"],
86
+ properties: {
87
+ object: {
88
+ type: "object",
89
+ required: ["type", "token", "apiVersion"],
90
+ additionalProperties: false,
91
+ properties: {
92
+ type: { const: "credentials" },
93
+ token: {
94
+ type: "string",
95
+ minLength: 1,
96
+ maxLength: 8192,
97
+ pattern: "^[^\\r\\n]+$"
98
+ },
99
+ apiVersion: {
100
+ type: "string",
101
+ pattern: "^v[0-9]{1,3}\\.[0-9]{1,2}$"
102
+ }
103
+ }
104
+ }
105
+ }
106
+ },
107
+ responses: {
108
+ type: "object",
109
+ required: ["@context", "type", "actor", "target", "object"],
110
+ properties: {
111
+ "@context": { type: "array", items: { type: "string" } },
112
+ type: { const: "send" },
113
+ actor: identity,
114
+ target: identity,
115
+ object: {
116
+ type: "object",
117
+ required: ["type", "id", "content"],
118
+ properties: {
119
+ type: { const: "message" },
120
+ id: { type: "string", minLength: 1 },
121
+ content: { type: "string" },
122
+ humanAgent: { type: "boolean" }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ };
128
+
129
+ // src/index.ts
130
+ class Messenger {
131
+ log;
132
+ config = {
133
+ persist: false,
134
+ requireCredentials: ["send"]
135
+ };
136
+ constructor(session) {
137
+ this.log = session.log;
138
+ }
139
+ get schema() {
140
+ return PlatformMessengerSchema;
141
+ }
142
+ isInitialized() {
143
+ return true;
144
+ }
145
+ cleanup(done) {
146
+ done();
147
+ }
148
+ async send(job, credentials, done) {
149
+ const { token, apiVersion } = credentials.object;
150
+ const humanAgent = job.object.humanAgent === true;
151
+ let result;
152
+ try {
153
+ const response = await fetch(`https://graph.facebook.com/${apiVersion}/${encodeURIComponent(job.actor.id)}/messages`, {
154
+ method: "POST",
155
+ redirect: "error",
156
+ headers: {
157
+ authorization: `Bearer ${token}`,
158
+ "content-type": "application/json"
159
+ },
160
+ body: JSON.stringify({
161
+ recipient: { id: job.target.id },
162
+ message: { text: job.object.content },
163
+ messaging_type: humanAgent ? "MESSAGE_TAG" : "RESPONSE",
164
+ ...humanAgent ? { tag: "HUMAN_AGENT" } : {}
165
+ }),
166
+ signal: AbortSignal.timeout(15000)
167
+ });
168
+ const data = await response.json();
169
+ if (!data || typeof data !== "object") {
170
+ throw new Error("messenger: invalid API response");
171
+ }
172
+ if ("error" in data || !response.ok) {
173
+ const error = "error" in data ? data.error : undefined;
174
+ let detail = `HTTP ${response.status}`;
175
+ if (error && typeof error === "object") {
176
+ if ("code" in error && typeof error.code === "number") {
177
+ detail += `, code ${error.code}`;
178
+ }
179
+ if ("error_subcode" in error && typeof error.error_subcode === "number") {
180
+ detail += `, subcode ${error.error_subcode}`;
181
+ }
182
+ if ("message" in error && typeof error.message === "string") {
183
+ detail += `: ${error.message.split(token).join("[redacted]")}`;
184
+ }
185
+ }
186
+ const windowClosed = error && typeof error === "object" && "code" in error && error.code === 10 && "error_subcode" in error && (error.error_subcode === 2018278 || error.error_subcode === 2534022);
187
+ const reason = windowClosed ? "meta:messaging-window-closed" : "messenger: send rejected";
188
+ throw new Error(`${reason} (${detail})`);
189
+ }
190
+ if (!("message_id" in data) || typeof data.message_id !== "string" || !data.message_id) {
191
+ throw new Error("messenger: API response missing message_id");
192
+ }
193
+ result = {
194
+ ...job,
195
+ object: { ...job.object, id: data.message_id }
196
+ };
197
+ } catch (error) {
198
+ const failure = error instanceof Error && (error.message.startsWith("messenger:") || error.message.startsWith("meta:messaging-window-closed")) ? new Error(error.message.split(token).join("[redacted]")) : new Error("messenger: send failed (network error, timeout, or invalid JSON); delivery is unknown");
199
+ this.log.warn(`send failed for actor ${job.actor.id} on messenger`);
200
+ done(failure);
201
+ return;
202
+ }
203
+ done(null, result);
204
+ }
205
+ }
206
+ export {
207
+ Messenger as default
208
+ };
209
+
210
+ //# debugId=EA77EFFFBD66931764756E2164756E21
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/schema.ts", "../src/index.ts"],
4
+ "sourcesContent": [
5
+ "import packageJson from \"../package.json\" with { type: \"json\" };\n\nconst identity = {\n type: \"object\",\n required: [\"id\", \"type\"],\n additionalProperties: false,\n properties: {\n id: { type: \"string\", pattern: \"^[0-9]+$\", maxLength: 128 },\n type: { const: \"person\" },\n },\n};\n\nexport const PlatformMessengerSchema = {\n name: \"messenger\",\n version: packageJson.version,\n contextUrl: \"https://sockethub.org/ns/context/platform/messenger/v1.jsonld\",\n contextVersion: \"1\",\n schemaVersion: \"1\",\n messages: {\n required: [\"type\", \"actor\", \"target\", \"object\"],\n properties: {\n type: { enum: [\"send\"] },\n actor: identity,\n target: identity,\n object: {\n type: \"object\",\n required: [\"type\", \"content\"],\n additionalProperties: false,\n properties: {\n type: { const: \"message\" },\n content: { type: \"string\", minLength: 1, maxLength: 2000 },\n humanAgent: { type: \"boolean\" },\n },\n },\n },\n },\n credentials: {\n required: [\"object\"],\n properties: {\n object: {\n type: \"object\",\n required: [\"type\", \"token\", \"apiVersion\"],\n additionalProperties: false,\n properties: {\n type: { const: \"credentials\" },\n token: {\n type: \"string\",\n minLength: 1,\n maxLength: 8192,\n pattern: \"^[^\\\\r\\\\n]+$\",\n },\n apiVersion: {\n type: \"string\",\n pattern: \"^v[0-9]{1,3}\\\\.[0-9]{1,2}$\",\n },\n },\n },\n },\n },\n responses: {\n type: \"object\",\n required: [\"@context\", \"type\", \"actor\", \"target\", \"object\"],\n properties: {\n \"@context\": { type: \"array\", items: { type: \"string\" } },\n type: { const: \"send\" },\n actor: identity,\n target: identity,\n object: {\n type: \"object\",\n required: [\"type\", \"id\", \"content\"],\n properties: {\n type: { const: \"message\" },\n id: { type: \"string\", minLength: 1 },\n content: { type: \"string\" },\n humanAgent: { type: \"boolean\" },\n },\n },\n },\n },\n};\n",
6
+ "import type {\n ActivityStream,\n CredentialsObject,\n Logger,\n PlatformCallback,\n PlatformInterface,\n PlatformSession,\n StatelessPlatformConfig,\n} from \"@sockethub/schemas\";\nimport { PlatformMessengerSchema } from \"./schema.js\";\n\nexport interface MessengerCredentials extends CredentialsObject {\n object: { type: \"credentials\"; token: string; apiVersion: string };\n}\n\nexport default class Messenger implements PlatformInterface {\n private readonly log: Logger;\n config: StatelessPlatformConfig = {\n persist: false,\n requireCredentials: [\"send\"],\n };\n\n constructor(session: PlatformSession) {\n this.log = session.log;\n }\n\n get schema() {\n return PlatformMessengerSchema;\n }\n\n isInitialized(): boolean {\n return true;\n }\n\n cleanup(done: PlatformCallback): void {\n done();\n }\n\n async send(\n job: ActivityStream,\n credentials: MessengerCredentials,\n done: PlatformCallback,\n ): Promise<void> {\n const { token, apiVersion } = credentials.object;\n const humanAgent = job.object.humanAgent === true;\n let result: ActivityStream;\n try {\n const response = await fetch(\n `https://graph.facebook.com/${apiVersion}/${encodeURIComponent(job.actor.id)}/messages`,\n {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n authorization: `Bearer ${token}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n recipient: { id: job.target.id },\n message: { text: job.object.content },\n messaging_type: humanAgent ? \"MESSAGE_TAG\" : \"RESPONSE\",\n ...(humanAgent ? { tag: \"HUMAN_AGENT\" } : {}),\n }),\n signal: AbortSignal.timeout(15_000),\n },\n );\n const data: unknown = await response.json();\n if (!data || typeof data !== \"object\") {\n throw new Error(\"messenger: invalid API response\");\n }\n if (\"error\" in data || !response.ok) {\n const error = \"error\" in data ? data.error : undefined;\n let detail = `HTTP ${response.status}`;\n if (error && typeof error === \"object\") {\n if (\"code\" in error && typeof error.code === \"number\") {\n detail += `, code ${error.code}`;\n }\n if (\n \"error_subcode\" in error &&\n typeof error.error_subcode === \"number\"\n ) {\n detail += `, subcode ${error.error_subcode}`;\n }\n if (\n \"message\" in error &&\n typeof error.message === \"string\"\n ) {\n detail += `: ${error.message.split(token).join(\"[redacted]\")}`;\n }\n }\n const windowClosed =\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === 10 &&\n \"error_subcode\" in error &&\n (error.error_subcode === 2018278 ||\n error.error_subcode === 2534022);\n const reason = windowClosed\n ? \"meta:messaging-window-closed\"\n : \"messenger: send rejected\";\n throw new Error(`${reason} (${detail})`);\n }\n if (\n !(\"message_id\" in data) ||\n typeof data.message_id !== \"string\" ||\n !data.message_id\n ) {\n throw new Error(\"messenger: API response missing message_id\");\n }\n result = {\n ...job,\n object: { ...job.object, id: data.message_id },\n };\n } catch (error) {\n // Network errors may contain request details; never expose tokens.\n const failure =\n error instanceof Error &&\n (error.message.startsWith(\"messenger:\") ||\n error.message.startsWith(\"meta:messaging-window-closed\"))\n ? new Error(error.message.split(token).join(\"[redacted]\"))\n : new Error(\n \"messenger: send failed (network error, timeout, or invalid JSON); delivery is unknown\",\n );\n this.log.warn(`send failed for actor ${job.actor.id} on messenger`);\n done(failure);\n return;\n }\n done(null, result);\n }\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,WAAW;AAAA,EACb,MAAM;AAAA,EACN,UAAU,CAAC,MAAM,MAAM;AAAA,EACvB,sBAAsB;AAAA,EACtB,YAAY;AAAA,IACR,IAAI,EAAE,MAAM,UAAU,SAAS,YAAY,WAAW,IAAI;AAAA,IAC1D,MAAM,EAAE,OAAO,SAAS;AAAA,EAC5B;AACJ;AAEO,IAAM,0BAA0B;AAAA,EACnC,MAAM;AAAA,EACN,SAAS,gBAAY;AAAA,EACrB,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,UAAU;AAAA,IACN,UAAU,CAAC,QAAQ,SAAS,UAAU,QAAQ;AAAA,IAC9C,YAAY;AAAA,MACR,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;AAAA,MACvB,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,QAAQ;AAAA,QACJ,MAAM;AAAA,QACN,UAAU,CAAC,QAAQ,SAAS;AAAA,QAC5B,sBAAsB;AAAA,QACtB,YAAY;AAAA,UACR,MAAM,EAAE,OAAO,UAAU;AAAA,UACzB,SAAS,EAAE,MAAM,UAAU,WAAW,GAAG,WAAW,KAAK;AAAA,UACzD,YAAY,EAAE,MAAM,UAAU;AAAA,QAClC;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAAA,EACA,aAAa;AAAA,IACT,UAAU,CAAC,QAAQ;AAAA,IACnB,YAAY;AAAA,MACR,QAAQ;AAAA,QACJ,MAAM;AAAA,QACN,UAAU,CAAC,QAAQ,SAAS,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;AAAA,QACA,MAAM,eACF,SACA,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,MACf,mBAAmB,UAClB,MAAM,kBAAkB,WACrB,MAAM,kBAAkB;AAAA,QAChC,MAAM,SAAS,eACT,iCACA;AAAA,QACN,MAAM,IAAI,MAAM,GAAG,WAAW,SAAS;AAAA,MAC3C;AAAA,MACA,IACI,EAAE,gBAAgB,SAClB,OAAO,KAAK,eAAe,YAC3B,CAAC,KAAK,YACR;AAAA,QACE,MAAM,IAAI,MAAM,4CAA4C;AAAA,MAChE;AAAA,MACA,SAAS;AAAA,WACF;AAAA,QACH,QAAQ,KAAK,IAAI,QAAQ,IAAI,KAAK,WAAW;AAAA,MACjD;AAAA,MACF,OAAO,OAAO;AAAA,MAEZ,MAAM,UACF,iBAAiB,UAChB,MAAM,QAAQ,WAAW,YAAY,KAClC,MAAM,QAAQ,WAAW,8BAA8B,KACrD,IAAI,MAAM,MAAM,QAAQ,MAAM,KAAK,EAAE,KAAK,YAAY,CAAC,IACvD,IAAI,MACA,uFACJ;AAAA,MACV,KAAK,IAAI,KAAK,yBAAyB,IAAI,MAAM,iBAAiB;AAAA,MAClE,KAAK,OAAO;AAAA,MACZ;AAAA;AAAA,IAEJ,KAAK,MAAM,MAAM;AAAA;AAEzB;",
9
+ "debugId": "EA77EFFFBD66931764756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,152 @@
1
+ export declare const PlatformMessengerSchema: {
2
+ name: string;
3
+ version: string;
4
+ contextUrl: string;
5
+ contextVersion: string;
6
+ schemaVersion: string;
7
+ messages: {
8
+ required: string[];
9
+ properties: {
10
+ type: {
11
+ enum: string[];
12
+ };
13
+ actor: {
14
+ type: string;
15
+ required: string[];
16
+ additionalProperties: boolean;
17
+ properties: {
18
+ id: {
19
+ type: string;
20
+ pattern: string;
21
+ maxLength: number;
22
+ };
23
+ type: {
24
+ const: string;
25
+ };
26
+ };
27
+ };
28
+ target: {
29
+ type: string;
30
+ required: string[];
31
+ additionalProperties: boolean;
32
+ properties: {
33
+ id: {
34
+ type: string;
35
+ pattern: string;
36
+ maxLength: number;
37
+ };
38
+ type: {
39
+ const: string;
40
+ };
41
+ };
42
+ };
43
+ object: {
44
+ type: string;
45
+ required: string[];
46
+ additionalProperties: boolean;
47
+ properties: {
48
+ type: {
49
+ const: string;
50
+ };
51
+ content: {
52
+ type: string;
53
+ minLength: number;
54
+ maxLength: number;
55
+ };
56
+ humanAgent: {
57
+ type: string;
58
+ };
59
+ };
60
+ };
61
+ };
62
+ };
63
+ credentials: {
64
+ required: string[];
65
+ properties: {
66
+ object: {
67
+ type: string;
68
+ required: string[];
69
+ additionalProperties: boolean;
70
+ properties: {
71
+ type: {
72
+ const: string;
73
+ };
74
+ token: {
75
+ type: string;
76
+ minLength: number;
77
+ maxLength: number;
78
+ pattern: string;
79
+ };
80
+ apiVersion: {
81
+ type: string;
82
+ pattern: string;
83
+ };
84
+ };
85
+ };
86
+ };
87
+ };
88
+ responses: {
89
+ type: string;
90
+ required: string[];
91
+ properties: {
92
+ "@context": {
93
+ type: string;
94
+ items: {
95
+ type: string;
96
+ };
97
+ };
98
+ type: {
99
+ const: string;
100
+ };
101
+ actor: {
102
+ type: string;
103
+ required: string[];
104
+ additionalProperties: boolean;
105
+ properties: {
106
+ id: {
107
+ type: string;
108
+ pattern: string;
109
+ maxLength: number;
110
+ };
111
+ type: {
112
+ const: string;
113
+ };
114
+ };
115
+ };
116
+ target: {
117
+ type: string;
118
+ required: string[];
119
+ additionalProperties: boolean;
120
+ properties: {
121
+ id: {
122
+ type: string;
123
+ pattern: string;
124
+ maxLength: number;
125
+ };
126
+ type: {
127
+ const: string;
128
+ };
129
+ };
130
+ };
131
+ object: {
132
+ type: string;
133
+ required: string[];
134
+ properties: {
135
+ type: {
136
+ const: string;
137
+ };
138
+ id: {
139
+ type: string;
140
+ minLength: number;
141
+ };
142
+ content: {
143
+ type: string;
144
+ };
145
+ humanAgent: {
146
+ type: string;
147
+ };
148
+ };
149
+ };
150
+ };
151
+ };
152
+ };
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@sockethub/platform-messenger",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Outgoing text messages through the Meta Messenger API",
4
+ "version": "1.0.0-beta.2",
5
+ "type": "module",
6
+ "private": false,
7
+ "license": "LGPL-3.0+",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist/"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20.19"
25
+ },
26
+ "scripts": {
27
+ "build": "bun build src/index.ts --outdir dist --target node --format esm --sourcemap=external",
28
+ "clean": "rm -rf dist",
29
+ "clean:deps": "rm -rf node_modules",
30
+ "test": "bun test src/"
31
+ },
32
+ "dependencies": {
33
+ "@sockethub/schemas": "^3.0.0-beta.2"
34
+ },
35
+ "devDependencies": {
36
+ "@types/bun": "latest"
37
+ },
38
+ "peerDependencies": {
39
+ "@sockethub/server": "^5.0.0-beta.2"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@sockethub/server": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "gitHead": "d241420f9743f66a15ed083a1390595b331a96ac"
47
+ }