opscms-meta-plugin 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +13 -13
- package/dist/{chunk-HCQSD757.mjs → chunk-VPSQ2E3Q.mjs} +1 -1
- package/dist/components/MetaCatalogSync/index.mjs +1 -1
- package/dist/components/MetaConnectPanel/index.js +1 -1
- package/dist/components/MetaConnectPanel/index.mjs +1 -1
- package/dist/components/MetaPixelSelect/index.mjs +1 -1
- package/dist/components/ThreadsConnectPanel/index.js +1 -1
- package/dist/components/ThreadsConnectPanel/index.mjs +1 -1
- package/dist/index.d.mts +27 -14
- package/dist/index.d.ts +27 -14
- package/dist/index.js +47 -30
- package/dist/index.mjs +47 -30
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.1
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- **An organization admin (and an editor) could not create a Meta connection, so no site could be connected.** The create rule refused unless the request already named a
|
|
8
|
+
site, but the admin screen asks "may this person create one?" before there is a document, so the answer was always no and "Create New" never appeared (only a
|
|
9
|
+
super-admin saw it). An admin or editor may now start one. Nothing else is looser: the site is still a required field, an editor is still pinned to their own site,
|
|
10
|
+
and a site that is submitted is still checked against the admin's organization.
|
|
11
|
+
|
|
12
|
+
## 0.6.0
|
|
13
|
+
|
|
14
|
+
### Changed (breaking)
|
|
15
|
+
|
|
16
|
+
- **The platform's Meta app comes from the host, and only from the host.** `metaPlugin({ app: () => ({ appId, appSecret, webhookVerifyToken }) })`: the
|
|
17
|
+
plugin asks for it when it needs it, so a host that keeps the app in its own settings needs nothing on the server, and a change is used at once.
|
|
18
|
+
`META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN` are **no longer read**: one place to set the app, no second value that can disagree.
|
|
19
|
+
A host that passes no `app` has Meta Connect, Facebook login and the webhook switched off. (`META_ENCRYPTION_KEY` and `META_OAUTH_STATE_SECRET` are
|
|
20
|
+
not part of this: they protect what is stored and signed, so they stay on the server.)
|
|
21
|
+
|
|
3
22
|
## 0.4.2
|
|
4
23
|
|
|
5
24
|
### Fixed
|
package/README.md
CHANGED
|
@@ -87,18 +87,18 @@ export default buildConfig({
|
|
|
87
87
|
```bash
|
|
88
88
|
# .env
|
|
89
89
|
META_ENCRYPTION_KEY=$(openssl rand -hex 32)
|
|
90
|
-
META_APP_ID=your-meta-app-id
|
|
91
|
-
META_APP_SECRET=your-meta-app-secret
|
|
92
90
|
```
|
|
93
91
|
|
|
92
|
+
The Meta App itself is **not** set in the environment: the host CMS passes it in (`metaPlugin({ app: () => ({ appId, appSecret, webhookVerifyToken }) })`), from wherever it keeps its own settings (OpsCMS: Platform Settings → Meta app). A host that passes no `app` has Meta Connect, Facebook login and the webhook switched off.
|
|
93
|
+
|
|
94
94
|
Without `META_ENCRYPTION_KEY`, credentials are stored in plain text (allowed in development; the plugin **fails fast at startup in production** unless you explicitly set `ALLOW_PLAINTEXT_META_CREDS=true`, which you should not do).
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
The App ID and secret the host passes are the **one Meta App for the whole deployment** — same pattern as Buffer/Hootsuite/Zapier: every tenant site connects through this single App, they never create their own. There's no API to create a Meta App programmatically (unlike, say, ERPNext's OAuth Client doctype), so this is a one-time manual step:
|
|
97
97
|
|
|
98
98
|
1. Create an App at [developers.facebook.com](https://developers.facebook.com), add the **Facebook Login for Business** product (and **Threads API** if you'll connect Threads).
|
|
99
99
|
2. Add `{PAYLOAD_PUBLIC_SERVER_URL}/api/meta-oauth/callback` and `{PAYLOAD_PUBLIC_SERVER_URL}/api/threads-oauth/callback` as **Valid OAuth Redirect URIs**.
|
|
100
100
|
3. Switch the App to **Live** mode and request **Advanced Access** (via App Review) for whichever scopes you need — `pages_show_list`, `pages_read_engagement`, `instagram_basic`, `business_management`, `ads_management`, etc. In Development mode, OAuth only works for users added as Testers/Admins/Developers on the App itself — real tenant site owners won't be able to connect until this is done. Meta may also require **Business Verification** for the ads/marketing-adjacent scopes.
|
|
101
|
-
4.
|
|
101
|
+
4. Give the host the App ID and App secret from that App's Settings → Basic page (OpsCMS: Platform Settings → Meta app). It is used at once; no restart.
|
|
102
102
|
|
|
103
103
|
Site owners never see or enter these — the admin UI shows only a masked, read-only App ID (`GET /api/meta-oauth/app-info`) so they can confirm a platform App is configured before clicking Connect.
|
|
104
104
|
|
|
@@ -136,7 +136,7 @@ Paste a long-lived Page or System User access token directly into `accessToken`
|
|
|
136
136
|
|
|
137
137
|
### Option B — Connect to Meta Business (OAuth)
|
|
138
138
|
|
|
139
|
-
Uses the one platform-level Meta App
|
|
139
|
+
Uses the one platform-level Meta App the host passes in (see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app) — that's a one-time deployment setup step, not something each site does). Once that's configured:
|
|
140
140
|
|
|
141
141
|
1. On the `meta-config` document's 🔑 Connection tab, the panel shows a masked, read-only **Platform Meta App** ID confirming it's configured.
|
|
142
142
|
2. Click **Connect to Meta Business** — you'll be redirected to Meta's OAuth consent screen requesting `business_management`, `pages_show_list`, `pages_read_engagement`, `pages_manage_metadata`, `instagram_basic`, `ads_management`, `catalog_management`, and `whatsapp_business_management` (trim the scope list in `metaOAuth.ts` if your App's review doesn't cover all of them — Meta simply omits ungranted permissions from the resulting token rather than failing the whole flow).
|
|
@@ -145,7 +145,7 @@ Uses the one platform-level Meta App set up via `META_APP_ID`/`META_APP_SECRET`
|
|
|
145
145
|
|
|
146
146
|
### Connecting Threads
|
|
147
147
|
|
|
148
|
-
Threads is a **separate product/API** from Facebook and Instagram — its own OAuth host (`threads.net`, not `facebook.com`), its own token host (`graph.threads.net`, not `graph.facebook.com`), and its own token/profile shape — even though it's added as a product on the *same* Meta App and reuses the same platform-level
|
|
148
|
+
Threads is a **separate product/API** from Facebook and Instagram — its own OAuth host (`threads.net`, not `facebook.com`), its own token host (`graph.threads.net`, not `graph.facebook.com`), and its own token/profile shape — even though it's added as a product on the *same* Meta App and reuses the same platform-level the app ID/the app secret.
|
|
149
149
|
|
|
150
150
|
1. Add the **Threads API** product to the same Meta App (see setup step above), and register `{PAYLOAD_PUBLIC_SERVER_URL}/api/threads-oauth/callback` as its redirect URI.
|
|
151
151
|
2. On the **🧵 Threads** tab, click **Connect Threads** — separate consent screen (`threads_basic`, `threads_content_publish`), separate callback, separate stored token (`threadsAccessToken`). Connecting Threads does not affect or require the Facebook/Instagram connection above, or vice versa.
|
|
@@ -167,7 +167,7 @@ export interface MetaPluginOptions {
|
|
|
167
167
|
|
|
168
168
|
| Variable | Required | Description |
|
|
169
169
|
|---|---|---|
|
|
170
|
-
|
|
|
170
|
+
| *(the host's `app` option)* | For OAuth Connect | The one Meta App for the whole deployment (developers.facebook.com) — every tenant site's Connect button uses this. Not required if every site only ever uses manual Access Token entry. Not an environment variable, and never entered by a site owner; see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app). |
|
|
171
171
|
| `META_ENCRYPTION_KEY` | Production: yes | 32-byte hex key (`openssl rand -hex 32`) for AES-256-GCM credential encryption. Separate from `opscms-erpnext-plugin`'s `ERPNEXT_ENCRYPTION_KEY` — rotating one doesn't affect the other. |
|
|
172
172
|
| `ALLOW_PLAINTEXT_META_CREDS` | No | Set to `true` to explicitly allow plain-text credential storage in production. Do not set this unless you understand the risk (a DB dump/backup leaks every tenant's Meta access token). |
|
|
173
173
|
| `PAYLOAD_PUBLIC_SERVER_URL` | For Catalog feed + OAuth | Used to build absolute image URLs in the Commerce Catalog feed, and the OAuth callback redirect URIs (`/api/meta-oauth/callback`, `/api/threads-oauth/callback`). Already set for the host CMS's other public-facing needs. |
|
|
@@ -177,7 +177,7 @@ export interface MetaPluginOptions {
|
|
|
177
177
|
|
|
178
178
|
## The `meta-config` Collection
|
|
179
179
|
|
|
180
|
-
One document per site. `appId`/`appSecret` are **not** fields here — they're the one platform-level Meta App
|
|
180
|
+
One document per site. `appId`/`appSecret` are **not** fields here — they're the one platform-level Meta App the host passes in, never per-site. Every other credential field is directly editable (manual entry) — the Connect buttons are a convenience layer on top, not a replacement:
|
|
181
181
|
|
|
182
182
|
| Tab | Fields | Notes |
|
|
183
183
|
|---|---|---|
|
|
@@ -187,7 +187,7 @@ One document per site. `appId`/`appSecret` are **not** fields here — they're t
|
|
|
187
187
|
| 💬 WhatsApp Business | `whatsappEnabled`, `whatsappPhoneNumberId`, `whatsappBusinessAccountId` | Populates the host CMS's existing `lib/whatsapp.ts` `metaCloud` provider — no plugin code needed for outbound sending. |
|
|
188
188
|
| 🧵 Threads | `threadsEnabled`, **Connect Threads** button, `threadsUserId`/`threadsUsername` (read-only, set by Connect), `threadsAccessToken` (hidden, encrypted) | Independent OAuth flow — see [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads). |
|
|
189
189
|
|
|
190
|
-
Credentials (`accessToken`, `oauthUserAccessToken`, `threadsAccessToken`) are AES-256-GCM encrypted at rest and masked in the admin UI (`••••1234`) for any authenticated non-internal request — the same pattern `ErpnextConfig` uses for `apiKey`/`apiSecret`.
|
|
190
|
+
Credentials (`accessToken`, `oauthUserAccessToken`, `threadsAccessToken`) are AES-256-GCM encrypted at rest and masked in the admin UI (`••••1234`) for any authenticated non-internal request — the same pattern `ErpnextConfig` uses for `apiKey`/`apiSecret`. the app secret never touches the database at all — it's read from the environment on each OAuth request.
|
|
191
191
|
|
|
192
192
|
---
|
|
193
193
|
|
|
@@ -270,7 +270,7 @@ The one real gap: Meta's WhatsApp Cloud API webhook subscription requires a `GET
|
|
|
270
270
|
|
|
271
271
|
## Security
|
|
272
272
|
|
|
273
|
-
- Credentials (`accessToken`) are AES-256-GCM encrypted at rest (`META_ENCRYPTION_KEY`), masked in the admin UI, and only decrypted server-side when actually needed (e.g. `getMetaCredentials()`, the connection-health check).
|
|
273
|
+
- Credentials (`accessToken`) are AES-256-GCM encrypted at rest (`META_ENCRYPTION_KEY`), masked in the admin UI, and only decrypted server-side when actually needed (e.g. `getMetaCredentials()`, the connection-health check). the app secret is never stored in the database at all — it's read from the environment only, on each OAuth request.
|
|
274
274
|
- `accessToken` is only writable by `admin`/`super-admin` roles (`adminOrAboveField` field-level access) — editors can see the masked config but can't rotate credentials or repoint a connection.
|
|
275
275
|
- `getMetaCredentials()` never falls back across sites — a lookup for one site's slug will never return another tenant's credentials, even on a partial/missing config.
|
|
276
276
|
- The Commerce Catalog feed is intentionally public (Meta's crawler needs unauthenticated access) but strictly site-scoped — it can never return another site's data, and only returns docs that already belong to the requested site.
|
|
@@ -298,8 +298,8 @@ MIT
|
|
|
298
298
|
|
|
299
299
|
Meta reports what happens on its side to one callback address per app. Register
|
|
300
300
|
`https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the
|
|
301
|
-
**WhatsApp Business Account** topic, with the verify token
|
|
302
|
-
The app secret
|
|
301
|
+
**WhatsApp Business Account** topic, with the verify token the host passes in (`webhookVerifyToken`).
|
|
302
|
+
The app secret must also be set: every delivery is signed with it, and a
|
|
303
303
|
delivery with a missing or wrong signature is refused with 401.
|
|
304
304
|
|
|
305
305
|
Each site's business account is subscribed to the app when the site chooses its WhatsApp
|
|
@@ -329,7 +329,7 @@ The plugin adds "Continue with Facebook" to the platform's login page, using the
|
|
|
329
329
|
|
|
330
330
|
- **Who gets in:** someone who already has a platform account. Their Facebook email must be the same as their platform email to join the
|
|
331
331
|
two; after that they sign in by Facebook id. Signing in never creates an account, and an account is never matched on a different email.
|
|
332
|
-
- **Setup:**
|
|
332
|
+
- **Setup:** the Meta app given to the plugin by the host, the Facebook Login product on the Meta app, and
|
|
333
333
|
`<PAYLOAD_PUBLIC_SERVER_URL>/api/meta-login/callback` listed as a valid OAuth redirect URI. Only `email` and `public_profile` are
|
|
334
334
|
requested, which need no App Review.
|
|
335
335
|
- **Database:** the plugin adds a unique `facebookId` field to the users collection; the platform needs a migration for the column.
|
|
@@ -70,7 +70,7 @@ function useMetaAppInfo() {
|
|
|
70
70
|
var MetaAppInfoBadge = ({ appInfo }) => {
|
|
71
71
|
if (appInfo.loading) return null;
|
|
72
72
|
if (!appInfo.configured) {
|
|
73
|
-
return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014
|
|
73
|
+
return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings." });
|
|
74
74
|
}
|
|
75
75
|
return /* @__PURE__ */ jsxs("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
|
|
76
76
|
/* @__PURE__ */ jsx("span", { children: "Platform Meta App" }),
|
|
@@ -110,7 +110,7 @@ function useMetaAppInfo() {
|
|
|
110
110
|
var MetaAppInfoBadge = ({ appInfo }) => {
|
|
111
111
|
if (appInfo.loading) return null;
|
|
112
112
|
if (!appInfo.configured) {
|
|
113
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014
|
|
113
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings." });
|
|
114
114
|
}
|
|
115
115
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
|
|
116
116
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
openMetaOAuthPopup,
|
|
16
16
|
useMetaAppInfo,
|
|
17
17
|
useOAuthRedirectMessage
|
|
18
|
-
} from "../../chunk-
|
|
18
|
+
} from "../../chunk-VPSQ2E3Q.mjs";
|
|
19
19
|
|
|
20
20
|
// src/components/MetaConnectPanel/index.tsx
|
|
21
21
|
import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState } from "react";
|
|
@@ -89,7 +89,7 @@ function useMetaAppInfo() {
|
|
|
89
89
|
var MetaAppInfoBadge = ({ appInfo }) => {
|
|
90
90
|
if (appInfo.loading) return null;
|
|
91
91
|
if (!appInfo.configured) {
|
|
92
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014
|
|
92
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings." });
|
|
93
93
|
}
|
|
94
94
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
|
|
95
95
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
|
package/dist/index.d.mts
CHANGED
|
@@ -40,6 +40,23 @@ interface MetaHost {
|
|
|
40
40
|
};
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Encrypt a plain-text credential. Returns a string prefixed with "enc:".
|
|
45
|
+
* If encryption key is not configured, returns the value as-is.
|
|
46
|
+
*/
|
|
47
|
+
declare function encryptCredential(plaintext: string): string;
|
|
48
|
+
/**
|
|
49
|
+
* Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
|
|
50
|
+
* it's assumed to be plain text (backward compatible).
|
|
51
|
+
*/
|
|
52
|
+
declare function decryptCredential(stored: string): string;
|
|
53
|
+
/** What a host CMS says the platform's Meta app is (typed into its own settings, not set on the server). Any part may be missing. */
|
|
54
|
+
interface MetaAppSettings {
|
|
55
|
+
appId?: string | null;
|
|
56
|
+
appSecret?: string | null;
|
|
57
|
+
webhookVerifyToken?: string | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
43
60
|
/**
|
|
44
61
|
* Cloud API send failures that are about the template a message names.
|
|
45
62
|
*
|
|
@@ -52,18 +69,7 @@ declare function explainTemplateSendError(body: string): {
|
|
|
52
69
|
error: string;
|
|
53
70
|
} | null;
|
|
54
71
|
|
|
55
|
-
/**
|
|
56
|
-
* Encrypt a plain-text credential. Returns a string prefixed with "enc:".
|
|
57
|
-
* If encryption key is not configured, returns the value as-is.
|
|
58
|
-
*/
|
|
59
|
-
declare function encryptCredential(plaintext: string): string;
|
|
60
|
-
/**
|
|
61
|
-
* Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
|
|
62
|
-
* it's assumed to be plain text (backward compatible).
|
|
63
|
-
*/
|
|
64
|
-
declare function decryptCredential(stored: string): string;
|
|
65
|
-
|
|
66
|
-
/** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (META_APP_ID/META_APP_SECRET, see utils/metaCrypto.ts), not part of a site's credentials. */
|
|
72
|
+
/** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (given by the host, see utils/metaCrypto.ts), not part of a site's credentials. */
|
|
67
73
|
interface MetaCredentials {
|
|
68
74
|
accessToken: string;
|
|
69
75
|
businessManagerId?: string;
|
|
@@ -223,7 +229,7 @@ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>
|
|
|
223
229
|
* The plugin's webhook: the address Meta calls to report what happens on its side.
|
|
224
230
|
*
|
|
225
231
|
* Register `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the WhatsApp business account
|
|
226
|
-
* topic, with the verify token set in
|
|
232
|
+
* topic, with the verify token set in the host's Meta app settings. Each site's business account is subscribed to the app when
|
|
227
233
|
* the site connects (see utils/wabaSubscription.ts), so its events arrive here.
|
|
228
234
|
*
|
|
229
235
|
* - GET answers Meta's handshake.
|
|
@@ -342,6 +348,13 @@ interface MetaPluginOptions {
|
|
|
342
348
|
* accepts Meta's deliveries, but nobody is told.
|
|
343
349
|
*/
|
|
344
350
|
host?: MetaHost;
|
|
351
|
+
/**
|
|
352
|
+
* The platform's Meta app (App ID, secret, webhook verify token), as the host keeps it in its own settings. Called whenever the plugin needs it, so
|
|
353
|
+
* keep it quick (answer from memory). It is the ONLY source: the plugin does not read the app from the server's environment, so a host that does
|
|
354
|
+
* not pass this leaves Meta Connect, Facebook login and the webhook switched off. (`META_ENCRYPTION_KEY`, the key that protects what is stored,
|
|
355
|
+
* is still read from the environment.)
|
|
356
|
+
*/
|
|
357
|
+
app?: () => MetaAppSettings | null | undefined;
|
|
345
358
|
}
|
|
346
359
|
/**
|
|
347
360
|
* Meta Network Plugin for Payload CMS
|
|
@@ -373,4 +386,4 @@ interface MetaPluginOptions {
|
|
|
373
386
|
*/
|
|
374
387
|
declare function metaPlugin(options?: MetaPluginOptions): Plugin;
|
|
375
388
|
|
|
376
|
-
export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaConfigDoc, type MetaCredentials, type MetaHost, type MetaPluginOptions, type NotificationChannelProvider, attachFacebookLogin, createMetaLoginEndpoints, createMetaWebhookEndpoints, decryptCredential, encryptCredential, explainTemplateSendError, facebookIdField, getMetaCredentials, metaConversionEventHandler, metaPlugin, metaWhatsAppChannel, resolveLoginUser, sendConversionEvent, subscribeWabaToApp, unsubscribeWabaFromApp };
|
|
389
|
+
export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaAppSettings, type MetaConfigDoc, type MetaCredentials, type MetaHost, type MetaPluginOptions, type NotificationChannelProvider, attachFacebookLogin, createMetaLoginEndpoints, createMetaWebhookEndpoints, decryptCredential, encryptCredential, explainTemplateSendError, facebookIdField, getMetaCredentials, metaConversionEventHandler, metaPlugin, metaWhatsAppChannel, resolveLoginUser, sendConversionEvent, subscribeWabaToApp, unsubscribeWabaFromApp };
|
package/dist/index.d.ts
CHANGED
|
@@ -40,6 +40,23 @@ interface MetaHost {
|
|
|
40
40
|
};
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Encrypt a plain-text credential. Returns a string prefixed with "enc:".
|
|
45
|
+
* If encryption key is not configured, returns the value as-is.
|
|
46
|
+
*/
|
|
47
|
+
declare function encryptCredential(plaintext: string): string;
|
|
48
|
+
/**
|
|
49
|
+
* Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
|
|
50
|
+
* it's assumed to be plain text (backward compatible).
|
|
51
|
+
*/
|
|
52
|
+
declare function decryptCredential(stored: string): string;
|
|
53
|
+
/** What a host CMS says the platform's Meta app is (typed into its own settings, not set on the server). Any part may be missing. */
|
|
54
|
+
interface MetaAppSettings {
|
|
55
|
+
appId?: string | null;
|
|
56
|
+
appSecret?: string | null;
|
|
57
|
+
webhookVerifyToken?: string | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
43
60
|
/**
|
|
44
61
|
* Cloud API send failures that are about the template a message names.
|
|
45
62
|
*
|
|
@@ -52,18 +69,7 @@ declare function explainTemplateSendError(body: string): {
|
|
|
52
69
|
error: string;
|
|
53
70
|
} | null;
|
|
54
71
|
|
|
55
|
-
/**
|
|
56
|
-
* Encrypt a plain-text credential. Returns a string prefixed with "enc:".
|
|
57
|
-
* If encryption key is not configured, returns the value as-is.
|
|
58
|
-
*/
|
|
59
|
-
declare function encryptCredential(plaintext: string): string;
|
|
60
|
-
/**
|
|
61
|
-
* Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
|
|
62
|
-
* it's assumed to be plain text (backward compatible).
|
|
63
|
-
*/
|
|
64
|
-
declare function decryptCredential(stored: string): string;
|
|
65
|
-
|
|
66
|
-
/** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (META_APP_ID/META_APP_SECRET, see utils/metaCrypto.ts), not part of a site's credentials. */
|
|
72
|
+
/** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (given by the host, see utils/metaCrypto.ts), not part of a site's credentials. */
|
|
67
73
|
interface MetaCredentials {
|
|
68
74
|
accessToken: string;
|
|
69
75
|
businessManagerId?: string;
|
|
@@ -223,7 +229,7 @@ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>
|
|
|
223
229
|
* The plugin's webhook: the address Meta calls to report what happens on its side.
|
|
224
230
|
*
|
|
225
231
|
* Register `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the WhatsApp business account
|
|
226
|
-
* topic, with the verify token set in
|
|
232
|
+
* topic, with the verify token set in the host's Meta app settings. Each site's business account is subscribed to the app when
|
|
227
233
|
* the site connects (see utils/wabaSubscription.ts), so its events arrive here.
|
|
228
234
|
*
|
|
229
235
|
* - GET answers Meta's handshake.
|
|
@@ -342,6 +348,13 @@ interface MetaPluginOptions {
|
|
|
342
348
|
* accepts Meta's deliveries, but nobody is told.
|
|
343
349
|
*/
|
|
344
350
|
host?: MetaHost;
|
|
351
|
+
/**
|
|
352
|
+
* The platform's Meta app (App ID, secret, webhook verify token), as the host keeps it in its own settings. Called whenever the plugin needs it, so
|
|
353
|
+
* keep it quick (answer from memory). It is the ONLY source: the plugin does not read the app from the server's environment, so a host that does
|
|
354
|
+
* not pass this leaves Meta Connect, Facebook login and the webhook switched off. (`META_ENCRYPTION_KEY`, the key that protects what is stored,
|
|
355
|
+
* is still read from the environment.)
|
|
356
|
+
*/
|
|
357
|
+
app?: () => MetaAppSettings | null | undefined;
|
|
345
358
|
}
|
|
346
359
|
/**
|
|
347
360
|
* Meta Network Plugin for Payload CMS
|
|
@@ -373,4 +386,4 @@ interface MetaPluginOptions {
|
|
|
373
386
|
*/
|
|
374
387
|
declare function metaPlugin(options?: MetaPluginOptions): Plugin;
|
|
375
388
|
|
|
376
|
-
export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaConfigDoc, type MetaCredentials, type MetaHost, type MetaPluginOptions, type NotificationChannelProvider, attachFacebookLogin, createMetaLoginEndpoints, createMetaWebhookEndpoints, decryptCredential, encryptCredential, explainTemplateSendError, facebookIdField, getMetaCredentials, metaConversionEventHandler, metaPlugin, metaWhatsAppChannel, resolveLoginUser, sendConversionEvent, subscribeWabaToApp, unsubscribeWabaFromApp };
|
|
389
|
+
export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaAppSettings, type MetaConfigDoc, type MetaCredentials, type MetaHost, type MetaPluginOptions, type NotificationChannelProvider, attachFacebookLogin, createMetaLoginEndpoints, createMetaWebhookEndpoints, decryptCredential, encryptCredential, explainTemplateSendError, facebookIdField, getMetaCredentials, metaConversionEventHandler, metaPlugin, metaWhatsAppChannel, resolveLoginUser, sendConversionEvent, subscribeWabaToApp, unsubscribeWabaFromApp };
|
package/dist/index.js
CHANGED
|
@@ -155,7 +155,7 @@ var siteScopedCreate = (siteField = "site") => {
|
|
|
155
155
|
if (u.role === "super-admin") return true;
|
|
156
156
|
if (!["admin", "editor"].includes(u.role)) return false;
|
|
157
157
|
const rawDocSite = submittedSiteId(data, siteField);
|
|
158
|
-
if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return
|
|
158
|
+
if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return true;
|
|
159
159
|
const siteId = getUserSiteId(u);
|
|
160
160
|
if (siteId) return String(rawDocSite) === String(siteId);
|
|
161
161
|
if (u.role !== "admin") return false;
|
|
@@ -296,12 +296,28 @@ function decryptCredential(stored) {
|
|
|
296
296
|
return stored;
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
|
+
var appProvider = null;
|
|
300
|
+
function setMetaAppProvider(provider) {
|
|
301
|
+
appProvider = provider ?? null;
|
|
302
|
+
}
|
|
303
|
+
var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
304
|
+
function metaAppSettings() {
|
|
305
|
+
let given;
|
|
306
|
+
try {
|
|
307
|
+
given = appProvider?.();
|
|
308
|
+
} catch {
|
|
309
|
+
given = null;
|
|
310
|
+
}
|
|
311
|
+
return { appId: text(given?.appId), appSecret: text(given?.appSecret), webhookVerifyToken: text(given?.webhookVerifyToken) };
|
|
312
|
+
}
|
|
299
313
|
function getMetaAppCredentials() {
|
|
300
|
-
const appId =
|
|
301
|
-
const appSecret = process.env.META_APP_SECRET;
|
|
314
|
+
const { appId, appSecret } = metaAppSettings();
|
|
302
315
|
if (!appId || !appSecret) return null;
|
|
303
316
|
return { appId, appSecret };
|
|
304
317
|
}
|
|
318
|
+
function getMetaWebhookVerifyToken() {
|
|
319
|
+
return metaAppSettings().webhookVerifyToken;
|
|
320
|
+
}
|
|
305
321
|
function getMaskedMetaAppId() {
|
|
306
322
|
const creds = getMetaAppCredentials();
|
|
307
323
|
if (!creds) return null;
|
|
@@ -545,7 +561,7 @@ var MetaConfig = {
|
|
|
545
561
|
// ── Tab 1: Connection ────────────────────────────────
|
|
546
562
|
{
|
|
547
563
|
label: "\u{1F511} Connection",
|
|
548
|
-
description: "
|
|
564
|
+
description: "The Meta app is set once for the whole platform (by the platform owner, in its settings). Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
|
|
549
565
|
fields: [
|
|
550
566
|
{
|
|
551
567
|
name: "accessToken",
|
|
@@ -1246,9 +1262,9 @@ async function graphPostJson(path, body, accessToken) {
|
|
|
1246
1262
|
return { ok: true, status: res.status, data: await readGraphJson(res) };
|
|
1247
1263
|
}
|
|
1248
1264
|
async function readGraphJson(res) {
|
|
1249
|
-
const
|
|
1250
|
-
if (!
|
|
1251
|
-
return JSON.parse(
|
|
1265
|
+
const text3 = await res.text();
|
|
1266
|
+
if (!text3) return {};
|
|
1267
|
+
return JSON.parse(text3);
|
|
1252
1268
|
}
|
|
1253
1269
|
async function graphDelete(path, accessToken) {
|
|
1254
1270
|
const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
|
|
@@ -1611,7 +1627,7 @@ var metaOAuthStartEndpoint = {
|
|
|
1611
1627
|
}
|
|
1612
1628
|
const appCreds = getMetaAppCredentials();
|
|
1613
1629
|
if (!appCreds) {
|
|
1614
|
-
return Response.json({ error: "Meta App not configured on this deployment \u2014
|
|
1630
|
+
return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
|
|
1615
1631
|
}
|
|
1616
1632
|
const state = signOAuthState(configId);
|
|
1617
1633
|
const params = new URLSearchParams({
|
|
@@ -1649,7 +1665,7 @@ var metaOAuthCallbackEndpoint = {
|
|
|
1649
1665
|
}
|
|
1650
1666
|
const appCreds = getMetaAppCredentials();
|
|
1651
1667
|
if (!appCreds) {
|
|
1652
|
-
return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014
|
|
1668
|
+
return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." });
|
|
1653
1669
|
}
|
|
1654
1670
|
const shortLived = await graphGet("/oauth/access_token", {
|
|
1655
1671
|
client_id: appCreds.appId,
|
|
@@ -1932,7 +1948,7 @@ var threadsOAuthStartEndpoint = {
|
|
|
1932
1948
|
}
|
|
1933
1949
|
const appCreds = getMetaAppCredentials();
|
|
1934
1950
|
if (!appCreds) {
|
|
1935
|
-
return Response.json({ error: "Meta App not configured on this deployment \u2014
|
|
1951
|
+
return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
|
|
1936
1952
|
}
|
|
1937
1953
|
const state = signOAuthState(configId);
|
|
1938
1954
|
const params = new URLSearchParams({
|
|
@@ -1970,7 +1986,7 @@ var threadsOAuthCallbackEndpoint = {
|
|
|
1970
1986
|
}
|
|
1971
1987
|
const appCreds = getMetaAppCredentials();
|
|
1972
1988
|
if (!appCreds) {
|
|
1973
|
-
return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014
|
|
1989
|
+
return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings.")}`, 302);
|
|
1974
1990
|
}
|
|
1975
1991
|
const shortLived = await threadsPost("/oauth/access_token", {
|
|
1976
1992
|
client_id: appCreds.appId,
|
|
@@ -2199,7 +2215,7 @@ function toMetaBody(message) {
|
|
|
2199
2215
|
if (!normalised) return { ok: false, problems: ["The message is empty."] };
|
|
2200
2216
|
const taken = /* @__PURE__ */ new Set();
|
|
2201
2217
|
const byPath = /* @__PURE__ */ new Map();
|
|
2202
|
-
const
|
|
2218
|
+
const text3 = normalised.replace(PLACEHOLDER, (_whole, path) => {
|
|
2203
2219
|
let parameter = byPath.get(path);
|
|
2204
2220
|
if (!parameter) {
|
|
2205
2221
|
parameter = { name: nameFor(path, taken), path, example: sampleFor(path) };
|
|
@@ -2208,16 +2224,16 @@ function toMetaBody(message) {
|
|
|
2208
2224
|
return `{{${parameter.name}}}`;
|
|
2209
2225
|
});
|
|
2210
2226
|
const problems = [];
|
|
2211
|
-
if (
|
|
2212
|
-
if (/^\s*\{\{[^}]+\}\}/.test(
|
|
2213
|
-
if (/\{\{[^}]+\}\}\s*$/.test(
|
|
2214
|
-
if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(
|
|
2215
|
-
const withoutVariables =
|
|
2227
|
+
if (text3.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
|
|
2228
|
+
if (/^\s*\{\{[^}]+\}\}/.test(text3)) problems.push("The message cannot start with a variable. Put some words before it.");
|
|
2229
|
+
if (/\{\{[^}]+\}\}\s*$/.test(text3)) problems.push("The message cannot end with a variable. Put some words after it.");
|
|
2230
|
+
if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text3)) problems.push("Two variables cannot sit next to each other. Put words between them.");
|
|
2231
|
+
const withoutVariables = text3.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
|
|
2216
2232
|
if (byPath.size > 0 && withoutVariables.length === 0) problems.push("The message cannot be only variables.");
|
|
2217
|
-
const words =
|
|
2233
|
+
const words = text3.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
|
|
2218
2234
|
if (byPath.size > 0 && words < byPath.size * 3) problems.push("The message has too many variables for its length. Meta wants about three words for every variable.");
|
|
2219
|
-
if ((
|
|
2220
|
-
return problems.length ? { ok: false, problems } : { ok: true, body: { text:
|
|
2235
|
+
if ((text3.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
|
|
2236
|
+
return problems.length ? { ok: false, problems } : { ok: true, body: { text: text3, parameters: [...byPath.values()] } };
|
|
2221
2237
|
}
|
|
2222
2238
|
function contentHash(message) {
|
|
2223
2239
|
return (0, import_node_crypto3.createHash)("sha256").update(message.replace(/\r\n/g, "\n").trim()).digest("hex").slice(0, 12);
|
|
@@ -2683,7 +2699,7 @@ function toE164Digits(phone, defaultCountryCode) {
|
|
|
2683
2699
|
|
|
2684
2700
|
// src/channels/whatsapp.ts
|
|
2685
2701
|
var WHATSAPP_TIMEOUT_MS = 1e4;
|
|
2686
|
-
async function sendViaMetaCloud(to,
|
|
2702
|
+
async function sendViaMetaCloud(to, text3, cfg, log, template) {
|
|
2687
2703
|
const payload = template ? {
|
|
2688
2704
|
messaging_product: "whatsapp",
|
|
2689
2705
|
to,
|
|
@@ -2702,7 +2718,7 @@ async function sendViaMetaCloud(to, text2, cfg, log, template) {
|
|
|
2702
2718
|
messaging_product: "whatsapp",
|
|
2703
2719
|
to,
|
|
2704
2720
|
type: "text",
|
|
2705
|
-
text: { body:
|
|
2721
|
+
text: { body: text3 }
|
|
2706
2722
|
};
|
|
2707
2723
|
try {
|
|
2708
2724
|
const res = await fetch(
|
|
@@ -2867,22 +2883,22 @@ var TEMPLATE_EVENT_BY_FIELD = {
|
|
|
2867
2883
|
message_template_quality_update: "meta.template.quality_changed",
|
|
2868
2884
|
message_template_components_update: "meta.template.components_changed"
|
|
2869
2885
|
};
|
|
2870
|
-
var
|
|
2886
|
+
var text2 = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
|
|
2871
2887
|
function templateEventsFrom(body) {
|
|
2872
2888
|
const delivery = body;
|
|
2873
2889
|
if (!delivery || delivery.object !== "whatsapp_business_account" || !Array.isArray(delivery.entry)) return [];
|
|
2874
2890
|
const events = [];
|
|
2875
2891
|
for (const entry of delivery.entry) {
|
|
2876
|
-
const wabaId =
|
|
2892
|
+
const wabaId = text2(entry?.id);
|
|
2877
2893
|
if (!wabaId || !Array.isArray(entry.changes)) continue;
|
|
2878
2894
|
for (const change of entry.changes) {
|
|
2879
2895
|
const field = typeof change?.field === "string" ? change.field : "";
|
|
2880
2896
|
const eventName = TEMPLATE_EVENT_BY_FIELD[field];
|
|
2881
2897
|
if (!eventName) continue;
|
|
2882
2898
|
const value = change.value ?? {};
|
|
2883
|
-
const templateId =
|
|
2884
|
-
const status =
|
|
2885
|
-
const reason =
|
|
2899
|
+
const templateId = text2(value.message_template_id);
|
|
2900
|
+
const status = text2(value.event) ?? text2(value.new_category) ?? text2(value.new_quality_score) ?? text2(value.correct_category);
|
|
2901
|
+
const reason = text2(value.reason) ?? text2(value.disable_info?.disable_date);
|
|
2886
2902
|
const eventId = (0, import_node_crypto5.createHash)("sha256").update(JSON.stringify([wabaId, field, entry.time ?? null, templateId, status, reason])).digest("hex").slice(0, 32);
|
|
2887
2903
|
events.push({
|
|
2888
2904
|
eventName,
|
|
@@ -2892,8 +2908,8 @@ function templateEventsFrom(body) {
|
|
|
2892
2908
|
eventId,
|
|
2893
2909
|
wabaId,
|
|
2894
2910
|
templateId,
|
|
2895
|
-
templateName:
|
|
2896
|
-
language:
|
|
2911
|
+
templateName: text2(value.message_template_name),
|
|
2912
|
+
language: text2(value.message_template_language),
|
|
2897
2913
|
status,
|
|
2898
2914
|
reason
|
|
2899
2915
|
}
|
|
@@ -2909,7 +2925,7 @@ function createMetaWebhookEndpoints(host) {
|
|
|
2909
2925
|
path: "/meta-webhook",
|
|
2910
2926
|
method: "get",
|
|
2911
2927
|
handler: async (req) => {
|
|
2912
|
-
const challenge = handshakeChallenge(req.query,
|
|
2928
|
+
const challenge = handshakeChallenge(req.query, getMetaWebhookVerifyToken());
|
|
2913
2929
|
if (challenge === null) return Response.json({ error: "Verification failed" }, { status: 403 });
|
|
2914
2930
|
return new Response(challenge, { status: 200, headers: { "content-type": "text/plain" } });
|
|
2915
2931
|
}
|
|
@@ -3415,6 +3431,7 @@ function registerNotificationChannel(provider) {
|
|
|
3415
3431
|
|
|
3416
3432
|
// src/index.ts
|
|
3417
3433
|
function metaPlugin(options = {}) {
|
|
3434
|
+
setMetaAppProvider(options.app);
|
|
3418
3435
|
if (options.registry) {
|
|
3419
3436
|
options.registry.register("meta-conversion-event", metaConversionEventHandler);
|
|
3420
3437
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -119,7 +119,7 @@ var siteScopedCreate = (siteField = "site") => {
|
|
|
119
119
|
if (u.role === "super-admin") return true;
|
|
120
120
|
if (!["admin", "editor"].includes(u.role)) return false;
|
|
121
121
|
const rawDocSite = submittedSiteId(data, siteField);
|
|
122
|
-
if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return
|
|
122
|
+
if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return true;
|
|
123
123
|
const siteId = getUserSiteId(u);
|
|
124
124
|
if (siteId) return String(rawDocSite) === String(siteId);
|
|
125
125
|
if (u.role !== "admin") return false;
|
|
@@ -260,12 +260,28 @@ function decryptCredential(stored) {
|
|
|
260
260
|
return stored;
|
|
261
261
|
}
|
|
262
262
|
}
|
|
263
|
+
var appProvider = null;
|
|
264
|
+
function setMetaAppProvider(provider) {
|
|
265
|
+
appProvider = provider ?? null;
|
|
266
|
+
}
|
|
267
|
+
var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
268
|
+
function metaAppSettings() {
|
|
269
|
+
let given;
|
|
270
|
+
try {
|
|
271
|
+
given = appProvider?.();
|
|
272
|
+
} catch {
|
|
273
|
+
given = null;
|
|
274
|
+
}
|
|
275
|
+
return { appId: text(given?.appId), appSecret: text(given?.appSecret), webhookVerifyToken: text(given?.webhookVerifyToken) };
|
|
276
|
+
}
|
|
263
277
|
function getMetaAppCredentials() {
|
|
264
|
-
const appId =
|
|
265
|
-
const appSecret = process.env.META_APP_SECRET;
|
|
278
|
+
const { appId, appSecret } = metaAppSettings();
|
|
266
279
|
if (!appId || !appSecret) return null;
|
|
267
280
|
return { appId, appSecret };
|
|
268
281
|
}
|
|
282
|
+
function getMetaWebhookVerifyToken() {
|
|
283
|
+
return metaAppSettings().webhookVerifyToken;
|
|
284
|
+
}
|
|
269
285
|
function getMaskedMetaAppId() {
|
|
270
286
|
const creds = getMetaAppCredentials();
|
|
271
287
|
if (!creds) return null;
|
|
@@ -509,7 +525,7 @@ var MetaConfig = {
|
|
|
509
525
|
// ── Tab 1: Connection ────────────────────────────────
|
|
510
526
|
{
|
|
511
527
|
label: "\u{1F511} Connection",
|
|
512
|
-
description: "
|
|
528
|
+
description: "The Meta app is set once for the whole platform (by the platform owner, in its settings). Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
|
|
513
529
|
fields: [
|
|
514
530
|
{
|
|
515
531
|
name: "accessToken",
|
|
@@ -1210,9 +1226,9 @@ async function graphPostJson(path, body, accessToken) {
|
|
|
1210
1226
|
return { ok: true, status: res.status, data: await readGraphJson(res) };
|
|
1211
1227
|
}
|
|
1212
1228
|
async function readGraphJson(res) {
|
|
1213
|
-
const
|
|
1214
|
-
if (!
|
|
1215
|
-
return JSON.parse(
|
|
1229
|
+
const text3 = await res.text();
|
|
1230
|
+
if (!text3) return {};
|
|
1231
|
+
return JSON.parse(text3);
|
|
1216
1232
|
}
|
|
1217
1233
|
async function graphDelete(path, accessToken) {
|
|
1218
1234
|
const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
|
|
@@ -1552,7 +1568,7 @@ var metaOAuthStartEndpoint = {
|
|
|
1552
1568
|
}
|
|
1553
1569
|
const appCreds = getMetaAppCredentials();
|
|
1554
1570
|
if (!appCreds) {
|
|
1555
|
-
return Response.json({ error: "Meta App not configured on this deployment \u2014
|
|
1571
|
+
return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
|
|
1556
1572
|
}
|
|
1557
1573
|
const state = signOAuthState(configId);
|
|
1558
1574
|
const params = new URLSearchParams({
|
|
@@ -1590,7 +1606,7 @@ var metaOAuthCallbackEndpoint = {
|
|
|
1590
1606
|
}
|
|
1591
1607
|
const appCreds = getMetaAppCredentials();
|
|
1592
1608
|
if (!appCreds) {
|
|
1593
|
-
return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014
|
|
1609
|
+
return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." });
|
|
1594
1610
|
}
|
|
1595
1611
|
const shortLived = await graphGet("/oauth/access_token", {
|
|
1596
1612
|
client_id: appCreds.appId,
|
|
@@ -1873,7 +1889,7 @@ var threadsOAuthStartEndpoint = {
|
|
|
1873
1889
|
}
|
|
1874
1890
|
const appCreds = getMetaAppCredentials();
|
|
1875
1891
|
if (!appCreds) {
|
|
1876
|
-
return Response.json({ error: "Meta App not configured on this deployment \u2014
|
|
1892
|
+
return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
|
|
1877
1893
|
}
|
|
1878
1894
|
const state = signOAuthState(configId);
|
|
1879
1895
|
const params = new URLSearchParams({
|
|
@@ -1911,7 +1927,7 @@ var threadsOAuthCallbackEndpoint = {
|
|
|
1911
1927
|
}
|
|
1912
1928
|
const appCreds = getMetaAppCredentials();
|
|
1913
1929
|
if (!appCreds) {
|
|
1914
|
-
return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014
|
|
1930
|
+
return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings.")}`, 302);
|
|
1915
1931
|
}
|
|
1916
1932
|
const shortLived = await threadsPost("/oauth/access_token", {
|
|
1917
1933
|
client_id: appCreds.appId,
|
|
@@ -2140,7 +2156,7 @@ function toMetaBody(message) {
|
|
|
2140
2156
|
if (!normalised) return { ok: false, problems: ["The message is empty."] };
|
|
2141
2157
|
const taken = /* @__PURE__ */ new Set();
|
|
2142
2158
|
const byPath = /* @__PURE__ */ new Map();
|
|
2143
|
-
const
|
|
2159
|
+
const text3 = normalised.replace(PLACEHOLDER, (_whole, path) => {
|
|
2144
2160
|
let parameter = byPath.get(path);
|
|
2145
2161
|
if (!parameter) {
|
|
2146
2162
|
parameter = { name: nameFor(path, taken), path, example: sampleFor(path) };
|
|
@@ -2149,16 +2165,16 @@ function toMetaBody(message) {
|
|
|
2149
2165
|
return `{{${parameter.name}}}`;
|
|
2150
2166
|
});
|
|
2151
2167
|
const problems = [];
|
|
2152
|
-
if (
|
|
2153
|
-
if (/^\s*\{\{[^}]+\}\}/.test(
|
|
2154
|
-
if (/\{\{[^}]+\}\}\s*$/.test(
|
|
2155
|
-
if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(
|
|
2156
|
-
const withoutVariables =
|
|
2168
|
+
if (text3.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
|
|
2169
|
+
if (/^\s*\{\{[^}]+\}\}/.test(text3)) problems.push("The message cannot start with a variable. Put some words before it.");
|
|
2170
|
+
if (/\{\{[^}]+\}\}\s*$/.test(text3)) problems.push("The message cannot end with a variable. Put some words after it.");
|
|
2171
|
+
if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text3)) problems.push("Two variables cannot sit next to each other. Put words between them.");
|
|
2172
|
+
const withoutVariables = text3.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
|
|
2157
2173
|
if (byPath.size > 0 && withoutVariables.length === 0) problems.push("The message cannot be only variables.");
|
|
2158
|
-
const words =
|
|
2174
|
+
const words = text3.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
|
|
2159
2175
|
if (byPath.size > 0 && words < byPath.size * 3) problems.push("The message has too many variables for its length. Meta wants about three words for every variable.");
|
|
2160
|
-
if ((
|
|
2161
|
-
return problems.length ? { ok: false, problems } : { ok: true, body: { text:
|
|
2176
|
+
if ((text3.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
|
|
2177
|
+
return problems.length ? { ok: false, problems } : { ok: true, body: { text: text3, parameters: [...byPath.values()] } };
|
|
2162
2178
|
}
|
|
2163
2179
|
function contentHash(message) {
|
|
2164
2180
|
return createHash2("sha256").update(message.replace(/\r\n/g, "\n").trim()).digest("hex").slice(0, 12);
|
|
@@ -2624,7 +2640,7 @@ function toE164Digits(phone, defaultCountryCode) {
|
|
|
2624
2640
|
|
|
2625
2641
|
// src/channels/whatsapp.ts
|
|
2626
2642
|
var WHATSAPP_TIMEOUT_MS = 1e4;
|
|
2627
|
-
async function sendViaMetaCloud(to,
|
|
2643
|
+
async function sendViaMetaCloud(to, text3, cfg, log, template) {
|
|
2628
2644
|
const payload = template ? {
|
|
2629
2645
|
messaging_product: "whatsapp",
|
|
2630
2646
|
to,
|
|
@@ -2643,7 +2659,7 @@ async function sendViaMetaCloud(to, text2, cfg, log, template) {
|
|
|
2643
2659
|
messaging_product: "whatsapp",
|
|
2644
2660
|
to,
|
|
2645
2661
|
type: "text",
|
|
2646
|
-
text: { body:
|
|
2662
|
+
text: { body: text3 }
|
|
2647
2663
|
};
|
|
2648
2664
|
try {
|
|
2649
2665
|
const res = await fetch(
|
|
@@ -2808,22 +2824,22 @@ var TEMPLATE_EVENT_BY_FIELD = {
|
|
|
2808
2824
|
message_template_quality_update: "meta.template.quality_changed",
|
|
2809
2825
|
message_template_components_update: "meta.template.components_changed"
|
|
2810
2826
|
};
|
|
2811
|
-
var
|
|
2827
|
+
var text2 = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
|
|
2812
2828
|
function templateEventsFrom(body) {
|
|
2813
2829
|
const delivery = body;
|
|
2814
2830
|
if (!delivery || delivery.object !== "whatsapp_business_account" || !Array.isArray(delivery.entry)) return [];
|
|
2815
2831
|
const events = [];
|
|
2816
2832
|
for (const entry of delivery.entry) {
|
|
2817
|
-
const wabaId =
|
|
2833
|
+
const wabaId = text2(entry?.id);
|
|
2818
2834
|
if (!wabaId || !Array.isArray(entry.changes)) continue;
|
|
2819
2835
|
for (const change of entry.changes) {
|
|
2820
2836
|
const field = typeof change?.field === "string" ? change.field : "";
|
|
2821
2837
|
const eventName = TEMPLATE_EVENT_BY_FIELD[field];
|
|
2822
2838
|
if (!eventName) continue;
|
|
2823
2839
|
const value = change.value ?? {};
|
|
2824
|
-
const templateId =
|
|
2825
|
-
const status =
|
|
2826
|
-
const reason =
|
|
2840
|
+
const templateId = text2(value.message_template_id);
|
|
2841
|
+
const status = text2(value.event) ?? text2(value.new_category) ?? text2(value.new_quality_score) ?? text2(value.correct_category);
|
|
2842
|
+
const reason = text2(value.reason) ?? text2(value.disable_info?.disable_date);
|
|
2827
2843
|
const eventId = createHash3("sha256").update(JSON.stringify([wabaId, field, entry.time ?? null, templateId, status, reason])).digest("hex").slice(0, 32);
|
|
2828
2844
|
events.push({
|
|
2829
2845
|
eventName,
|
|
@@ -2833,8 +2849,8 @@ function templateEventsFrom(body) {
|
|
|
2833
2849
|
eventId,
|
|
2834
2850
|
wabaId,
|
|
2835
2851
|
templateId,
|
|
2836
|
-
templateName:
|
|
2837
|
-
language:
|
|
2852
|
+
templateName: text2(value.message_template_name),
|
|
2853
|
+
language: text2(value.message_template_language),
|
|
2838
2854
|
status,
|
|
2839
2855
|
reason
|
|
2840
2856
|
}
|
|
@@ -2850,7 +2866,7 @@ function createMetaWebhookEndpoints(host) {
|
|
|
2850
2866
|
path: "/meta-webhook",
|
|
2851
2867
|
method: "get",
|
|
2852
2868
|
handler: async (req) => {
|
|
2853
|
-
const challenge = handshakeChallenge(req.query,
|
|
2869
|
+
const challenge = handshakeChallenge(req.query, getMetaWebhookVerifyToken());
|
|
2854
2870
|
if (challenge === null) return Response.json({ error: "Verification failed" }, { status: 403 });
|
|
2855
2871
|
return new Response(challenge, { status: 200, headers: { "content-type": "text/plain" } });
|
|
2856
2872
|
}
|
|
@@ -3356,6 +3372,7 @@ function registerNotificationChannel(provider) {
|
|
|
3356
3372
|
|
|
3357
3373
|
// src/index.ts
|
|
3358
3374
|
function metaPlugin(options = {}) {
|
|
3375
|
+
setMetaAppProvider(options.app);
|
|
3359
3376
|
if (options.registry) {
|
|
3360
3377
|
options.registry.register("meta-conversion-event", metaConversionEventHandler);
|
|
3361
3378
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opscms-meta-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Payload CMS plugin for connecting multi-tenant sites to Meta's network (Facebook Pixel + Conversions API, Facebook/Instagram Commerce Catalog, WhatsApp Business Cloud API). Modular per-channel, per-site — nothing hardcoded to one product line.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|