opscms-meta-plugin 0.0.0-stage → 0.4.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/CHANGELOG.md +189 -0
- package/LICENSE +21 -0
- package/README.md +338 -2
- package/dist/chunk-HCQSD757.mjs +142 -0
- package/dist/chunk-QEVRQKSQ.mjs +26 -0
- package/dist/components/MetaCatalogSync/index.d.mts +10 -0
- package/dist/components/MetaCatalogSync/index.d.ts +10 -0
- package/dist/components/MetaCatalogSync/index.js +195 -0
- package/dist/components/MetaCatalogSync/index.mjs +108 -0
- package/dist/components/MetaConnectPanel/index.d.mts +20 -0
- package/dist/components/MetaConnectPanel/index.d.ts +20 -0
- package/dist/components/MetaConnectPanel/index.js +723 -0
- package/dist/components/MetaConnectPanel/index.mjs +554 -0
- package/dist/components/MetaLoginButton/index.d.mts +5 -0
- package/dist/components/MetaLoginButton/index.d.ts +5 -0
- package/dist/components/MetaLoginButton/index.js +82 -0
- package/dist/components/MetaLoginButton/index.mjs +58 -0
- package/dist/components/MetaPixelSelect/index.d.mts +11 -0
- package/dist/components/MetaPixelSelect/index.d.ts +11 -0
- package/dist/components/MetaPixelSelect/index.js +202 -0
- package/dist/components/MetaPixelSelect/index.mjs +115 -0
- package/dist/components/ThreadsConnectPanel/index.d.mts +10 -0
- package/dist/components/ThreadsConnectPanel/index.d.ts +10 -0
- package/dist/components/ThreadsConnectPanel/index.js +163 -0
- package/dist/components/ThreadsConnectPanel/index.mjs +56 -0
- package/dist/index.d.mts +376 -0
- package/dist/index.d.ts +376 -0
- package/dist/index.js +3563 -0
- package/dist/index.mjs +3503 -0
- package/icon.svg +1 -0
- package/package.json +109 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3503 @@
|
|
|
1
|
+
import {
|
|
2
|
+
clearedMetaUserConnection
|
|
3
|
+
} from "./chunk-QEVRQKSQ.mjs";
|
|
4
|
+
|
|
5
|
+
// src/types.ts
|
|
6
|
+
import { timingSafeEqual } from "crypto";
|
|
7
|
+
function isInternalAuth(req) {
|
|
8
|
+
const secret = process.env.INTERNAL_API_SECRET;
|
|
9
|
+
if (!secret) return false;
|
|
10
|
+
const authSecret = req.headers?.get("x-internal-auth");
|
|
11
|
+
if (!authSecret) return false;
|
|
12
|
+
const a = Buffer.from(authSecret);
|
|
13
|
+
const b = Buffer.from(secret);
|
|
14
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
15
|
+
return timingSafeEqual(a, b);
|
|
16
|
+
}
|
|
17
|
+
var getUserOrgId = (user) => {
|
|
18
|
+
if (!user.organization) return null;
|
|
19
|
+
if (typeof user.organization === "object") return user.organization.id;
|
|
20
|
+
return user.organization;
|
|
21
|
+
};
|
|
22
|
+
var getUserSiteId = (user) => {
|
|
23
|
+
if (!user.site) return null;
|
|
24
|
+
if (typeof user.site === "object") return user.site.id;
|
|
25
|
+
return user.site;
|
|
26
|
+
};
|
|
27
|
+
function callerOwnsConfigSite(req, config) {
|
|
28
|
+
const user = getUserWithRole(req.user);
|
|
29
|
+
if (!user) return false;
|
|
30
|
+
if (user.role === "super-admin") return true;
|
|
31
|
+
const configSite = typeof config.site === "object" && config.site !== null ? config.site.id : config.site;
|
|
32
|
+
const configOrg = typeof config.organization === "object" && config.organization !== null ? config.organization.id : config.organization;
|
|
33
|
+
const callerSiteId = getUserSiteId(user);
|
|
34
|
+
const callerOrgId = getUserOrgId(user);
|
|
35
|
+
const siteMatches = callerSiteId != null && configSite != null && String(configSite) === String(callerSiteId);
|
|
36
|
+
const orgMatches = callerOrgId != null && configOrg != null && String(configOrg) === String(callerOrgId);
|
|
37
|
+
return siteMatches || orgMatches;
|
|
38
|
+
}
|
|
39
|
+
function getUserWithRole(user) {
|
|
40
|
+
if (!user || typeof user !== "object") return void 0;
|
|
41
|
+
const obj = user;
|
|
42
|
+
if (typeof obj.role !== "string") return void 0;
|
|
43
|
+
return {
|
|
44
|
+
id: obj.id,
|
|
45
|
+
role: obj.role,
|
|
46
|
+
email: typeof obj.email === "string" ? obj.email : void 0,
|
|
47
|
+
organization: obj.organization,
|
|
48
|
+
site: obj.site
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function asCollectionSlug(slug) {
|
|
52
|
+
return slug;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/access/roles.ts
|
|
56
|
+
var orgSiteIdsCache = /* @__PURE__ */ new WeakMap();
|
|
57
|
+
async function getOrgSiteIds(req, orgId) {
|
|
58
|
+
let byOrg = orgSiteIdsCache.get(req);
|
|
59
|
+
if (!byOrg) {
|
|
60
|
+
byOrg = /* @__PURE__ */ new Map();
|
|
61
|
+
orgSiteIdsCache.set(req, byOrg);
|
|
62
|
+
}
|
|
63
|
+
const key = String(orgId);
|
|
64
|
+
const cached = byOrg.get(key);
|
|
65
|
+
if (cached) return cached;
|
|
66
|
+
const payload = req.payload;
|
|
67
|
+
if (!payload) return [];
|
|
68
|
+
const pending = payload.find({
|
|
69
|
+
collection: asCollectionSlug("sites"),
|
|
70
|
+
where: { organization: { equals: orgId } },
|
|
71
|
+
limit: 0,
|
|
72
|
+
pagination: false,
|
|
73
|
+
depth: 0,
|
|
74
|
+
select: { id: true },
|
|
75
|
+
overrideAccess: true
|
|
76
|
+
}).then((res) => res.docs.map((doc) => doc.id));
|
|
77
|
+
byOrg.set(key, pending);
|
|
78
|
+
pending.catch(() => byOrg.delete(key));
|
|
79
|
+
return pending;
|
|
80
|
+
}
|
|
81
|
+
async function orgScopeFor(req, orgId, siteField) {
|
|
82
|
+
const siteIds = await getOrgSiteIds(req, orgId);
|
|
83
|
+
if (siteIds.length === 0) return false;
|
|
84
|
+
return { [siteField]: { in: siteIds } };
|
|
85
|
+
}
|
|
86
|
+
function submittedSiteId(data, siteField) {
|
|
87
|
+
if (!data) return void 0;
|
|
88
|
+
const raw = data[siteField];
|
|
89
|
+
if (raw && typeof raw === "object") return raw.id;
|
|
90
|
+
return raw;
|
|
91
|
+
}
|
|
92
|
+
function ownerScope(req, siteField) {
|
|
93
|
+
const u = getUserWithRole(req.user);
|
|
94
|
+
if (!u) return false;
|
|
95
|
+
const siteId = getUserSiteId(u);
|
|
96
|
+
if (siteId) return { [siteField]: { equals: siteId } };
|
|
97
|
+
if (u.role === "admin") {
|
|
98
|
+
const orgId = getUserOrgId(u);
|
|
99
|
+
if (orgId) return orgScopeFor(req, orgId, siteField);
|
|
100
|
+
}
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
var siteScopedRead = (siteField = "site") => {
|
|
104
|
+
return ({ req }) => {
|
|
105
|
+
if (isInternalAuth(req)) return true;
|
|
106
|
+
if (!req.user) return false;
|
|
107
|
+
const u = getUserWithRole(req.user);
|
|
108
|
+
if (!u) return false;
|
|
109
|
+
if (u.role === "super-admin") return true;
|
|
110
|
+
return ownerScope(req, siteField);
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
var siteScopedCreate = (siteField = "site") => {
|
|
114
|
+
return ({ req, data }) => {
|
|
115
|
+
if (isInternalAuth(req)) return true;
|
|
116
|
+
if (!req.user) return false;
|
|
117
|
+
const u = getUserWithRole(req.user);
|
|
118
|
+
if (!u) return false;
|
|
119
|
+
if (u.role === "super-admin") return true;
|
|
120
|
+
if (!["admin", "editor"].includes(u.role)) return false;
|
|
121
|
+
const rawDocSite = submittedSiteId(data, siteField);
|
|
122
|
+
if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return false;
|
|
123
|
+
const siteId = getUserSiteId(u);
|
|
124
|
+
if (siteId) return String(rawDocSite) === String(siteId);
|
|
125
|
+
if (u.role !== "admin") return false;
|
|
126
|
+
const orgId = getUserOrgId(u);
|
|
127
|
+
if (orgId == null) return false;
|
|
128
|
+
return getOrgSiteIds(req, orgId).then((ids) => ids.some((id) => String(id) === String(rawDocSite)));
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
var siteScopedUpdate = (siteField = "site") => {
|
|
132
|
+
return ({ req }) => {
|
|
133
|
+
if (isInternalAuth(req)) return true;
|
|
134
|
+
if (!req.user) return false;
|
|
135
|
+
const u = getUserWithRole(req.user);
|
|
136
|
+
if (!u) return false;
|
|
137
|
+
if (u.role === "super-admin") return true;
|
|
138
|
+
return ownerScope(req, siteField);
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
var siteScopedDelete = (siteField = "site") => {
|
|
142
|
+
return ({ req }) => {
|
|
143
|
+
if (isInternalAuth(req)) return true;
|
|
144
|
+
if (!req.user) return false;
|
|
145
|
+
const u = getUserWithRole(req.user);
|
|
146
|
+
if (!u) return false;
|
|
147
|
+
if (u.role === "super-admin") return true;
|
|
148
|
+
if (u.role === "admin") return ownerScope(req, siteField);
|
|
149
|
+
return false;
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// src/fields/organizationField.ts
|
|
154
|
+
var organizationField = (overrides) => ({
|
|
155
|
+
name: "organization",
|
|
156
|
+
type: "relationship",
|
|
157
|
+
relationTo: "organizations",
|
|
158
|
+
required: true,
|
|
159
|
+
admin: {
|
|
160
|
+
description: "The organization this belongs to"
|
|
161
|
+
},
|
|
162
|
+
...overrides
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// src/fields/tenantDefaults.ts
|
|
166
|
+
function relationId(value) {
|
|
167
|
+
if (value == null || value === "") return null;
|
|
168
|
+
if (typeof value === "object") {
|
|
169
|
+
const id = value.id;
|
|
170
|
+
if (typeof id === "string" || typeof id === "number") return id;
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
if (typeof value === "string" || typeof value === "number") return value;
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
function defaultSiteId(user) {
|
|
177
|
+
const account = getUserWithRole(user);
|
|
178
|
+
if (!account || account.role === "super-admin") return null;
|
|
179
|
+
return getUserSiteId(account);
|
|
180
|
+
}
|
|
181
|
+
function defaultOrganizationId(user) {
|
|
182
|
+
const account = getUserWithRole(user);
|
|
183
|
+
if (!account || account.role === "super-admin") return null;
|
|
184
|
+
return getUserOrgId(account);
|
|
185
|
+
}
|
|
186
|
+
function pinnedSiteValue(user, submitted) {
|
|
187
|
+
const account = getUserWithRole(user);
|
|
188
|
+
if (!account || account.role === "super-admin") return submitted;
|
|
189
|
+
const ownSite = getUserSiteId(account);
|
|
190
|
+
if (ownSite != null) return ownSite;
|
|
191
|
+
return relationId(submitted) ?? submitted;
|
|
192
|
+
}
|
|
193
|
+
function pinnedOrganizationValue(user, submitted, siteOrganizationId) {
|
|
194
|
+
const account = getUserWithRole(user);
|
|
195
|
+
if (account && account.role !== "super-admin") {
|
|
196
|
+
const ownOrg = getUserOrgId(account);
|
|
197
|
+
if (ownOrg != null) return ownOrg;
|
|
198
|
+
}
|
|
199
|
+
return siteOrganizationId ?? relationId(submitted) ?? submitted;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/utils/metaCrypto.ts
|
|
203
|
+
import { createCipheriv, createDecipheriv, randomBytes, createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
204
|
+
var ALGORITHM = "aes-256-gcm";
|
|
205
|
+
var IV_LENGTH = 12;
|
|
206
|
+
var PREFIX = "enc:";
|
|
207
|
+
var cachedKey = null;
|
|
208
|
+
var initialized = false;
|
|
209
|
+
function getEncryptionKey() {
|
|
210
|
+
if (initialized) return cachedKey;
|
|
211
|
+
const hex = process.env.META_ENCRYPTION_KEY;
|
|
212
|
+
if (!hex) {
|
|
213
|
+
if (process.env.NODE_ENV === "production" && process.env.ALLOW_PLAINTEXT_META_CREDS !== "true") {
|
|
214
|
+
throw new Error(
|
|
215
|
+
"[meta-crypto] FATAL: META_ENCRYPTION_KEY is required in production (generate with `openssl rand -hex 32`). Set ALLOW_PLAINTEXT_META_CREDS=true to knowingly store credentials in plain text."
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
if (process.env.NODE_ENV === "production") {
|
|
219
|
+
console.warn("[meta-crypto] META_ENCRYPTION_KEY not set \u2014 Meta credentials will be stored in plain text (ALLOW_PLAINTEXT_META_CREDS=true).");
|
|
220
|
+
}
|
|
221
|
+
initialized = true;
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
const buf = Buffer.from(hex, "hex");
|
|
225
|
+
if (buf.length !== 32) {
|
|
226
|
+
throw new Error("[meta-crypto] FATAL: META_ENCRYPTION_KEY must be exactly 32 bytes (64 hex chars).");
|
|
227
|
+
}
|
|
228
|
+
cachedKey = buf;
|
|
229
|
+
initialized = true;
|
|
230
|
+
return cachedKey;
|
|
231
|
+
}
|
|
232
|
+
getEncryptionKey();
|
|
233
|
+
function encryptCredential(plaintext) {
|
|
234
|
+
const key = getEncryptionKey();
|
|
235
|
+
if (!key) return plaintext;
|
|
236
|
+
if (plaintext.startsWith(PREFIX)) return plaintext;
|
|
237
|
+
const iv = randomBytes(IV_LENGTH);
|
|
238
|
+
const cipher = createCipheriv(ALGORITHM, key, iv);
|
|
239
|
+
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
240
|
+
const tag = cipher.getAuthTag();
|
|
241
|
+
return `${PREFIX}${iv.toString("hex")}:${tag.toString("hex")}:${encrypted.toString("hex")}`;
|
|
242
|
+
}
|
|
243
|
+
function decryptCredential(stored) {
|
|
244
|
+
const key = getEncryptionKey();
|
|
245
|
+
if (!key) return stored;
|
|
246
|
+
if (!stored.startsWith(PREFIX)) return stored;
|
|
247
|
+
try {
|
|
248
|
+
const payload = stored.slice(PREFIX.length);
|
|
249
|
+
const [ivHex, tagHex, ciphertextHex] = payload.split(":");
|
|
250
|
+
if (!ivHex || !tagHex || !ciphertextHex) return stored;
|
|
251
|
+
const iv = Buffer.from(ivHex, "hex");
|
|
252
|
+
const tag = Buffer.from(tagHex, "hex");
|
|
253
|
+
const ciphertext = Buffer.from(ciphertextHex, "hex");
|
|
254
|
+
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
|
255
|
+
decipher.setAuthTag(tag);
|
|
256
|
+
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
257
|
+
return decrypted.toString("utf8");
|
|
258
|
+
} catch (err) {
|
|
259
|
+
console.error("[meta-crypto] Failed to decrypt credential:", err);
|
|
260
|
+
return stored;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function getMetaAppCredentials() {
|
|
264
|
+
const appId = process.env.META_APP_ID;
|
|
265
|
+
const appSecret = process.env.META_APP_SECRET;
|
|
266
|
+
if (!appId || !appSecret) return null;
|
|
267
|
+
return { appId, appSecret };
|
|
268
|
+
}
|
|
269
|
+
function getMaskedMetaAppId() {
|
|
270
|
+
const creds = getMetaAppCredentials();
|
|
271
|
+
if (!creds) return null;
|
|
272
|
+
return creds.appId.length > 4 ? `\u2022\u2022\u2022\u2022${creds.appId.slice(-4)}` : "\u2022\u2022\u2022\u2022";
|
|
273
|
+
}
|
|
274
|
+
var STATE_TTL_MS = 10 * 60 * 1e3;
|
|
275
|
+
var cachedStateSecret = null;
|
|
276
|
+
function getStateSecret() {
|
|
277
|
+
if (cachedStateSecret) return cachedStateSecret;
|
|
278
|
+
const fromEnv = process.env.META_OAUTH_STATE_SECRET || process.env.META_ENCRYPTION_KEY;
|
|
279
|
+
if (fromEnv) {
|
|
280
|
+
cachedStateSecret = fromEnv;
|
|
281
|
+
return cachedStateSecret;
|
|
282
|
+
}
|
|
283
|
+
if (process.env.NODE_ENV === "production") {
|
|
284
|
+
throw new Error(
|
|
285
|
+
"[meta-crypto] FATAL: META_OAUTH_STATE_SECRET or META_ENCRYPTION_KEY is required for OAuth state signing in production."
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
cachedStateSecret = randomBytes(32).toString("hex");
|
|
289
|
+
return cachedStateSecret;
|
|
290
|
+
}
|
|
291
|
+
function signOAuthState(configId) {
|
|
292
|
+
const payload = `${configId}:${Date.now()}`;
|
|
293
|
+
const sig = createHmac("sha256", getStateSecret()).update(payload).digest("hex");
|
|
294
|
+
return Buffer.from(`${payload}:${sig}`).toString("base64url");
|
|
295
|
+
}
|
|
296
|
+
function verifyOAuthState(state) {
|
|
297
|
+
try {
|
|
298
|
+
const decoded = Buffer.from(state, "base64url").toString("utf8");
|
|
299
|
+
const parts = decoded.split(":");
|
|
300
|
+
if (parts.length !== 3) return null;
|
|
301
|
+
const [configId, timestampStr, sig] = parts;
|
|
302
|
+
const payload = `${configId}:${timestampStr}`;
|
|
303
|
+
const expected = createHmac("sha256", getStateSecret()).update(payload).digest("hex");
|
|
304
|
+
const a = Buffer.from(sig);
|
|
305
|
+
const b = Buffer.from(expected);
|
|
306
|
+
if (a.length !== b.length || !timingSafeEqual2(a, b)) return null;
|
|
307
|
+
const timestamp = Number(timestampStr);
|
|
308
|
+
if (!Number.isFinite(timestamp) || Date.now() - timestamp > STATE_TTL_MS) return null;
|
|
309
|
+
return configId;
|
|
310
|
+
} catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// src/collections/MetaConfig.ts
|
|
316
|
+
var adminOrAboveField = ({ req }) => ["super-admin", "admin"].includes(getUserWithRole(req?.user)?.role ?? "");
|
|
317
|
+
async function encryptBeforeChange({ value, originalDoc, field, req }) {
|
|
318
|
+
if (typeof value === "string" && value && !value.startsWith("\u2022\u2022\u2022\u2022")) {
|
|
319
|
+
return encryptCredential(value);
|
|
320
|
+
}
|
|
321
|
+
if (typeof value === "string" && value.startsWith("\u2022\u2022\u2022\u2022")) {
|
|
322
|
+
if (!originalDoc?.id) {
|
|
323
|
+
throw new Error(`Cannot save masked credential for ${field.name}. Please re-enter it.`);
|
|
324
|
+
}
|
|
325
|
+
const rawConfig = await req.payload.findByID({
|
|
326
|
+
collection: asCollectionSlug("meta-config"),
|
|
327
|
+
id: originalDoc.id,
|
|
328
|
+
depth: 0,
|
|
329
|
+
overrideAccess: true,
|
|
330
|
+
context: { preventMasking: true, skipConnectionTest: true }
|
|
331
|
+
});
|
|
332
|
+
const decrypted = rawConfig[field.name];
|
|
333
|
+
return decrypted && typeof decrypted === "string" ? encryptCredential(decrypted) : value;
|
|
334
|
+
}
|
|
335
|
+
return value;
|
|
336
|
+
}
|
|
337
|
+
function decryptAfterRead({ value, req, context }) {
|
|
338
|
+
if (typeof value !== "string") return value;
|
|
339
|
+
const decrypted = decryptCredential(value);
|
|
340
|
+
const ctx = req?.context || context || {};
|
|
341
|
+
if (ctx.preventMasking) return decrypted;
|
|
342
|
+
if (req?.user && decrypted.length > 4) {
|
|
343
|
+
return "\u2022\u2022\u2022\u2022" + decrypted.slice(-4);
|
|
344
|
+
}
|
|
345
|
+
return decrypted;
|
|
346
|
+
}
|
|
347
|
+
var testMetaConnection = async ({ doc, previousDoc, operation, req }) => {
|
|
348
|
+
if (operation === "update" && previousDoc) {
|
|
349
|
+
const alreadyConnected = doc.connectionStatus === "connected";
|
|
350
|
+
if (alreadyConnected) return doc;
|
|
351
|
+
}
|
|
352
|
+
const rawConfig = await req.payload.findByID({
|
|
353
|
+
collection: asCollectionSlug("meta-config"),
|
|
354
|
+
id: doc.id,
|
|
355
|
+
depth: 0,
|
|
356
|
+
overrideAccess: true,
|
|
357
|
+
context: { preventMasking: true, skipConnectionTest: true }
|
|
358
|
+
});
|
|
359
|
+
const accessToken = rawConfig.accessToken;
|
|
360
|
+
if (!accessToken) return doc;
|
|
361
|
+
const decryptedToken = decryptCredential(accessToken);
|
|
362
|
+
if (!decryptedToken) return doc;
|
|
363
|
+
let connected = false;
|
|
364
|
+
try {
|
|
365
|
+
const res = await fetch(
|
|
366
|
+
`https://graph.facebook.com/v21.0/me?access_token=${encodeURIComponent(decryptedToken)}`,
|
|
367
|
+
{ method: "GET", signal: AbortSignal.timeout(15e3) }
|
|
368
|
+
);
|
|
369
|
+
connected = res.ok;
|
|
370
|
+
await req.payload.update({
|
|
371
|
+
collection: asCollectionSlug("meta-config"),
|
|
372
|
+
id: doc.id,
|
|
373
|
+
data: { connectionStatus: connected ? "connected" : "disconnected" },
|
|
374
|
+
overrideAccess: true,
|
|
375
|
+
context: { skipConnectionTest: true }
|
|
376
|
+
});
|
|
377
|
+
req.payload.logger.info(`[MetaConfig] Connection test ${connected ? "succeeded" : "failed"} for config ${doc.id}`);
|
|
378
|
+
} catch (err) {
|
|
379
|
+
req.payload.logger.warn(`[MetaConfig] Connection test failed: ${err}`);
|
|
380
|
+
try {
|
|
381
|
+
await req.payload.update({
|
|
382
|
+
collection: asCollectionSlug("meta-config"),
|
|
383
|
+
id: doc.id,
|
|
384
|
+
data: { connectionStatus: "disconnected" },
|
|
385
|
+
overrideAccess: true,
|
|
386
|
+
context: { skipConnectionTest: true }
|
|
387
|
+
});
|
|
388
|
+
} catch {
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return doc;
|
|
392
|
+
};
|
|
393
|
+
var MetaConfig = {
|
|
394
|
+
slug: "meta-config",
|
|
395
|
+
labels: { singular: "Meta Config", plural: "Meta Configs" },
|
|
396
|
+
admin: {
|
|
397
|
+
useAsTitle: "label",
|
|
398
|
+
defaultColumns: ["label", "site", "connectionStatus", "isActive", "updatedAt"],
|
|
399
|
+
group: "Integrations",
|
|
400
|
+
description: "Connect this site to Meta (Facebook/Instagram/WhatsApp). Enable only the channels this site needs."
|
|
401
|
+
},
|
|
402
|
+
access: {
|
|
403
|
+
read: siteScopedRead(),
|
|
404
|
+
create: siteScopedCreate(),
|
|
405
|
+
update: siteScopedUpdate(),
|
|
406
|
+
delete: siteScopedDelete()
|
|
407
|
+
},
|
|
408
|
+
hooks: {
|
|
409
|
+
afterChange: [
|
|
410
|
+
(args) => {
|
|
411
|
+
if (args.context?.skipConnectionTest) return args.doc;
|
|
412
|
+
const payload = args.req.payload;
|
|
413
|
+
const docRef = args.doc;
|
|
414
|
+
setTimeout(() => {
|
|
415
|
+
testMetaConnection({ ...args, doc: docRef }).catch((err) => {
|
|
416
|
+
payload.logger.error(`[MetaConfig] Background connection test failed: ${err}`);
|
|
417
|
+
});
|
|
418
|
+
}, 2e3);
|
|
419
|
+
return args.doc;
|
|
420
|
+
}
|
|
421
|
+
]
|
|
422
|
+
},
|
|
423
|
+
fields: [
|
|
424
|
+
{
|
|
425
|
+
name: "label",
|
|
426
|
+
type: "text",
|
|
427
|
+
required: true,
|
|
428
|
+
admin: { description: 'Friendly name, e.g. "That Ofada Girl \u2014 Meta"' }
|
|
429
|
+
},
|
|
430
|
+
organizationField({
|
|
431
|
+
defaultValue: ({ user }) => defaultOrganizationId(user) ?? void 0,
|
|
432
|
+
admin: {
|
|
433
|
+
description: "Choose the organization first. The site list below only includes sites that belong to it."
|
|
434
|
+
},
|
|
435
|
+
hooks: {
|
|
436
|
+
beforeValidate: [async ({ req, value, siblingData }) => {
|
|
437
|
+
const account = getUserWithRole(req.user);
|
|
438
|
+
if (account && account.role !== "super-admin" && getUserOrgId(account) != null) {
|
|
439
|
+
return pinnedOrganizationValue(req.user, value, null);
|
|
440
|
+
}
|
|
441
|
+
const siteRef = siblingData?.site;
|
|
442
|
+
const siteId = siteRef && typeof siteRef === "object" ? siteRef.id : siteRef;
|
|
443
|
+
if (typeof siteId !== "string" && typeof siteId !== "number") {
|
|
444
|
+
return pinnedOrganizationValue(req.user, value, null);
|
|
445
|
+
}
|
|
446
|
+
try {
|
|
447
|
+
const site = await req.payload.findByID({
|
|
448
|
+
collection: asCollectionSlug("sites"),
|
|
449
|
+
id: siteId,
|
|
450
|
+
depth: 0,
|
|
451
|
+
overrideAccess: true
|
|
452
|
+
});
|
|
453
|
+
const orgRef = site?.organization;
|
|
454
|
+
const orgId = orgRef && typeof orgRef === "object" ? orgRef.id : orgRef;
|
|
455
|
+
const resolved = typeof orgId === "string" || typeof orgId === "number" ? orgId : null;
|
|
456
|
+
return pinnedOrganizationValue(req.user, value, resolved);
|
|
457
|
+
} catch {
|
|
458
|
+
return pinnedOrganizationValue(req.user, value, null);
|
|
459
|
+
}
|
|
460
|
+
}]
|
|
461
|
+
}
|
|
462
|
+
}),
|
|
463
|
+
{
|
|
464
|
+
type: "row",
|
|
465
|
+
fields: [
|
|
466
|
+
{
|
|
467
|
+
name: "site",
|
|
468
|
+
type: "relationship",
|
|
469
|
+
relationTo: "sites",
|
|
470
|
+
required: true,
|
|
471
|
+
defaultValue: ({ user }) => defaultSiteId(user) ?? void 0,
|
|
472
|
+
filterOptions: ({ data }) => {
|
|
473
|
+
const orgRef = data?.organization;
|
|
474
|
+
const orgId = orgRef && typeof orgRef === "object" ? orgRef.id : orgRef;
|
|
475
|
+
if (typeof orgId !== "string" && typeof orgId !== "number") return false;
|
|
476
|
+
return { organization: { equals: orgId } };
|
|
477
|
+
},
|
|
478
|
+
hooks: {
|
|
479
|
+
beforeValidate: [({ req, value }) => pinnedSiteValue(req.user, value)]
|
|
480
|
+
},
|
|
481
|
+
admin: {
|
|
482
|
+
description: "A site in the organization above. Filled from your account when you have one site.",
|
|
483
|
+
width: "70%"
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
{
|
|
487
|
+
name: "isActive",
|
|
488
|
+
type: "checkbox",
|
|
489
|
+
defaultValue: true,
|
|
490
|
+
admin: { width: "30%" }
|
|
491
|
+
}
|
|
492
|
+
]
|
|
493
|
+
},
|
|
494
|
+
{
|
|
495
|
+
name: "metaTenantDefaults",
|
|
496
|
+
type: "ui",
|
|
497
|
+
admin: {
|
|
498
|
+
components: {
|
|
499
|
+
Field: {
|
|
500
|
+
path: "opscms-meta-plugin/components/MetaConnectPanel",
|
|
501
|
+
exportName: "MetaTenantDefaults"
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
},
|
|
506
|
+
{
|
|
507
|
+
type: "tabs",
|
|
508
|
+
tabs: [
|
|
509
|
+
// ── Tab 1: Connection ────────────────────────────────
|
|
510
|
+
{
|
|
511
|
+
label: "\u{1F511} Connection",
|
|
512
|
+
description: "META_APP_ID and META_APP_SECRET are set for the whole deployment. Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
|
|
513
|
+
fields: [
|
|
514
|
+
{
|
|
515
|
+
name: "accessToken",
|
|
516
|
+
type: "text",
|
|
517
|
+
// Deliberately optional, not just conditionally required. authMethod
|
|
518
|
+
// is read-only and only ever flips to 'oauth' *after* a successful
|
|
519
|
+
// Connect to Meta Business flow — which itself requires this document
|
|
520
|
+
// to already have an id (the Connect button only renders once saved).
|
|
521
|
+
// Gating this field's requirement on authMethod === 'oauth' therefore
|
|
522
|
+
// made the very first save of a brand-new OAuth-only config impossible:
|
|
523
|
+
// authMethod could never be 'oauth' yet, so accessToken was always
|
|
524
|
+
// required, so the document could never be saved, so Connect could
|
|
525
|
+
// never appear. getMetaCredentials() (utils/metaCredentials.ts) already
|
|
526
|
+
// fails closed with a clear error at USE time if neither a manual token
|
|
527
|
+
// nor a completed OAuth connection exist, so nothing needs to be
|
|
528
|
+
// enforced here at save time.
|
|
529
|
+
access: { create: adminOrAboveField, update: adminOrAboveField },
|
|
530
|
+
admin: {
|
|
531
|
+
description: "Filled by Facebook login. Shown masked. Disconnect clears it.",
|
|
532
|
+
readOnly: true
|
|
533
|
+
},
|
|
534
|
+
hooks: {
|
|
535
|
+
beforeChange: [
|
|
536
|
+
async ({ value, originalDoc, req }) => await encryptBeforeChange({ value, originalDoc, field: { name: "accessToken" }, req })
|
|
537
|
+
],
|
|
538
|
+
afterRead: [
|
|
539
|
+
({ value, req, context }) => decryptAfterRead({ value, req, context })
|
|
540
|
+
]
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
{
|
|
544
|
+
name: "businessManagerId",
|
|
545
|
+
type: "text",
|
|
546
|
+
admin: {
|
|
547
|
+
description: "Filled by Facebook login.",
|
|
548
|
+
readOnly: true
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
{
|
|
552
|
+
name: "connectionStatus",
|
|
553
|
+
type: "select",
|
|
554
|
+
defaultValue: "untested",
|
|
555
|
+
options: [
|
|
556
|
+
{ label: "\u2705 Connected", value: "connected" },
|
|
557
|
+
{ label: "\u274C Disconnected", value: "disconnected" },
|
|
558
|
+
{ label: "\u23F3 Untested", value: "untested" }
|
|
559
|
+
],
|
|
560
|
+
admin: {
|
|
561
|
+
description: "Connection health \u2014 updated automatically when you save.",
|
|
562
|
+
readOnly: true
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
{
|
|
566
|
+
name: "authMethod",
|
|
567
|
+
type: "select",
|
|
568
|
+
defaultValue: "manual",
|
|
569
|
+
options: [
|
|
570
|
+
{ label: "Manual (paste Access Token)", value: "manual" },
|
|
571
|
+
{ label: "Connected via Meta Business Login", value: "oauth" }
|
|
572
|
+
],
|
|
573
|
+
admin: {
|
|
574
|
+
description: "Set automatically by the Connect flow below \u2014 informational only, does not change how credentials are used.",
|
|
575
|
+
readOnly: true
|
|
576
|
+
}
|
|
577
|
+
},
|
|
578
|
+
{
|
|
579
|
+
name: "metaConnectPanel",
|
|
580
|
+
type: "ui",
|
|
581
|
+
admin: {
|
|
582
|
+
components: {
|
|
583
|
+
Field: {
|
|
584
|
+
path: "opscms-meta-plugin/components/MetaConnectPanel",
|
|
585
|
+
exportName: "MetaConnectPanelField"
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
},
|
|
590
|
+
{
|
|
591
|
+
type: "row",
|
|
592
|
+
fields: [
|
|
593
|
+
{
|
|
594
|
+
name: "facebookPageId",
|
|
595
|
+
type: "text",
|
|
596
|
+
admin: { description: "Set by Connect. Facebook Page ID.", readOnly: true, width: "50%" }
|
|
597
|
+
},
|
|
598
|
+
{
|
|
599
|
+
name: "facebookPageName",
|
|
600
|
+
type: "text",
|
|
601
|
+
admin: { description: "Set by Connect.", readOnly: true, width: "50%" }
|
|
602
|
+
}
|
|
603
|
+
]
|
|
604
|
+
},
|
|
605
|
+
{
|
|
606
|
+
type: "row",
|
|
607
|
+
fields: [
|
|
608
|
+
{
|
|
609
|
+
name: "instagramBusinessAccountId",
|
|
610
|
+
type: "text",
|
|
611
|
+
admin: { description: "Set by Connect \u2014 auto-detected from the selected Page.", readOnly: true, width: "50%" }
|
|
612
|
+
},
|
|
613
|
+
{
|
|
614
|
+
name: "instagramUsername",
|
|
615
|
+
type: "text",
|
|
616
|
+
admin: { description: "Set by Connect.", readOnly: true, width: "50%" }
|
|
617
|
+
}
|
|
618
|
+
]
|
|
619
|
+
},
|
|
620
|
+
{
|
|
621
|
+
name: "oauthUserAccessToken",
|
|
622
|
+
type: "text",
|
|
623
|
+
admin: {
|
|
624
|
+
hidden: true,
|
|
625
|
+
description: "Internal \u2014 long-lived user token from Meta Business Login, used to re-fetch Pages/Pixels. Not the credential used for API calls (accessToken, set to the selected Page's token, is)."
|
|
626
|
+
},
|
|
627
|
+
hooks: {
|
|
628
|
+
beforeChange: [
|
|
629
|
+
async ({ value, originalDoc, req }) => await encryptBeforeChange({ value, originalDoc, field: { name: "oauthUserAccessToken" }, req })
|
|
630
|
+
],
|
|
631
|
+
afterRead: [
|
|
632
|
+
({ value, req, context }) => decryptAfterRead({ value, req, context })
|
|
633
|
+
]
|
|
634
|
+
}
|
|
635
|
+
},
|
|
636
|
+
{
|
|
637
|
+
name: "oauthExpiresAt",
|
|
638
|
+
type: "date",
|
|
639
|
+
admin: {
|
|
640
|
+
hidden: true,
|
|
641
|
+
description: "Internal \u2014 when the long-lived Page access token (accessToken) expires (~60 days from Connect). getMetaCredentials() fails closed and marks the connection disconnected past this point; Meta has no refresh_token grant, so re-connecting is currently a manual action."
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
]
|
|
645
|
+
},
|
|
646
|
+
// ── Tab 2: Pixel & Conversions API ───────────────────
|
|
647
|
+
{
|
|
648
|
+
label: "\u{1F4CA} Pixel & Conversions API",
|
|
649
|
+
description: "Client-side Pixel events plus a matching server-side Conversions API event (deduplicated by event_id) for accurate tracking despite iOS ad-tracking loss.",
|
|
650
|
+
fields: [
|
|
651
|
+
{
|
|
652
|
+
name: "pixelEnabled",
|
|
653
|
+
type: "checkbox",
|
|
654
|
+
defaultValue: false,
|
|
655
|
+
admin: {
|
|
656
|
+
description: "Turned on when Facebook login saves a Pixel. Disconnect turns it off.",
|
|
657
|
+
readOnly: true
|
|
658
|
+
}
|
|
659
|
+
},
|
|
660
|
+
{
|
|
661
|
+
name: "pixelId",
|
|
662
|
+
type: "text",
|
|
663
|
+
admin: {
|
|
664
|
+
description: "Filled by Facebook login.",
|
|
665
|
+
readOnly: true,
|
|
666
|
+
condition: (_data, siblingData) => Boolean(siblingData?.pixelEnabled)
|
|
667
|
+
}
|
|
668
|
+
},
|
|
669
|
+
{
|
|
670
|
+
name: "metaPixelSelectPanel",
|
|
671
|
+
type: "ui",
|
|
672
|
+
admin: {
|
|
673
|
+
condition: (data) => Boolean(data?.pixelEnabled) && data?.authMethod !== "oauth",
|
|
674
|
+
components: {
|
|
675
|
+
Field: {
|
|
676
|
+
path: "opscms-meta-plugin/components/MetaPixelSelect",
|
|
677
|
+
exportName: "MetaPixelSelectField"
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
]
|
|
683
|
+
},
|
|
684
|
+
// ── Tab 3: Commerce Catalog ──────────────────────────
|
|
685
|
+
{
|
|
686
|
+
label: "\u{1F6CD}\uFE0F Commerce Catalog",
|
|
687
|
+
description: "Sends this site's commerce catalogue to the Facebook catalog owned by the Facebook account that connected the site. Saving a catalogue item updates Meta. The public CSV feed stays available for Commerce Manager to fetch as well.",
|
|
688
|
+
fields: [
|
|
689
|
+
{
|
|
690
|
+
name: "catalogEnabled",
|
|
691
|
+
type: "checkbox",
|
|
692
|
+
defaultValue: false,
|
|
693
|
+
admin: {
|
|
694
|
+
description: "Turned on when Facebook login saves a catalog. Disconnect turns it off.",
|
|
695
|
+
readOnly: true
|
|
696
|
+
}
|
|
697
|
+
},
|
|
698
|
+
{
|
|
699
|
+
name: "catalogId",
|
|
700
|
+
type: "text",
|
|
701
|
+
admin: {
|
|
702
|
+
description: "Filled by Facebook login.",
|
|
703
|
+
readOnly: true,
|
|
704
|
+
condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
|
|
705
|
+
}
|
|
706
|
+
},
|
|
707
|
+
{
|
|
708
|
+
name: "catalogSourceCollection",
|
|
709
|
+
type: "text",
|
|
710
|
+
defaultValue: "catalogue-items",
|
|
711
|
+
admin: {
|
|
712
|
+
description: "Leave this as catalogue-items for the commerce plugin. That is the collection whose products sync to Meta.",
|
|
713
|
+
condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
name: "catalogItemUrlTemplate",
|
|
718
|
+
type: "text",
|
|
719
|
+
admin: {
|
|
720
|
+
description: 'Item page URL template on the live site \u2014 "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}. Required before products can sync (Meta rejects an item with no link).',
|
|
721
|
+
condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
|
|
722
|
+
}
|
|
723
|
+
},
|
|
724
|
+
{
|
|
725
|
+
name: "metaCatalogSyncPanel",
|
|
726
|
+
type: "ui",
|
|
727
|
+
admin: {
|
|
728
|
+
components: {
|
|
729
|
+
Field: {
|
|
730
|
+
path: "opscms-meta-plugin/components/MetaCatalogSync",
|
|
731
|
+
exportName: "MetaCatalogSyncField"
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
]
|
|
737
|
+
},
|
|
738
|
+
// ── Tab 4: WhatsApp Business ─────────────────────────
|
|
739
|
+
{
|
|
740
|
+
label: "\u{1F4AC} WhatsApp Business",
|
|
741
|
+
description: "Official WhatsApp for this site. Choose the number in the connect flow after Facebook login. Alert messages are prepared for you, and Meta reviews them \u2014 you can leave the page while that happens. Leave this off to keep the OpenWA bridge.",
|
|
742
|
+
fields: [
|
|
743
|
+
{
|
|
744
|
+
name: "whatsappEnabled",
|
|
745
|
+
type: "checkbox",
|
|
746
|
+
defaultValue: false,
|
|
747
|
+
admin: {
|
|
748
|
+
description: "Turned on when Facebook login saves a WhatsApp number. Disconnect turns it off and the OpenWA bridge is used again.",
|
|
749
|
+
readOnly: true
|
|
750
|
+
}
|
|
751
|
+
},
|
|
752
|
+
{
|
|
753
|
+
name: "whatsappPhoneNumberId",
|
|
754
|
+
type: "text",
|
|
755
|
+
admin: {
|
|
756
|
+
description: "Filled by Facebook login.",
|
|
757
|
+
readOnly: true,
|
|
758
|
+
condition: (_data, siblingData) => Boolean(siblingData?.whatsappEnabled)
|
|
759
|
+
}
|
|
760
|
+
},
|
|
761
|
+
{
|
|
762
|
+
name: "whatsappBusinessAccountId",
|
|
763
|
+
type: "text",
|
|
764
|
+
admin: {
|
|
765
|
+
description: "Filled by Facebook login.",
|
|
766
|
+
readOnly: true,
|
|
767
|
+
condition: (_data, siblingData) => Boolean(siblingData?.whatsappEnabled)
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
]
|
|
771
|
+
},
|
|
772
|
+
// ── Tab 5: Threads ────────────────────────────────────
|
|
773
|
+
{
|
|
774
|
+
label: "\u{1F9F5} Threads",
|
|
775
|
+
description: "Threads is a separate product/API from Facebook & Instagram (its own OAuth flow, on the same Meta App) \u2014 connect it independently.",
|
|
776
|
+
fields: [
|
|
777
|
+
{
|
|
778
|
+
name: "threadsEnabled",
|
|
779
|
+
type: "checkbox",
|
|
780
|
+
defaultValue: false,
|
|
781
|
+
admin: { description: "Enable Threads for this site \u2014 set automatically once Connect Threads succeeds; can also be toggled off to disable without disconnecting." }
|
|
782
|
+
},
|
|
783
|
+
{
|
|
784
|
+
name: "threadsConnectPanel",
|
|
785
|
+
type: "ui",
|
|
786
|
+
admin: {
|
|
787
|
+
components: {
|
|
788
|
+
Field: {
|
|
789
|
+
path: "opscms-meta-plugin/components/ThreadsConnectPanel",
|
|
790
|
+
exportName: "ThreadsConnectPanelField"
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
},
|
|
795
|
+
{
|
|
796
|
+
type: "row",
|
|
797
|
+
fields: [
|
|
798
|
+
{
|
|
799
|
+
name: "threadsUserId",
|
|
800
|
+
type: "text",
|
|
801
|
+
admin: { description: "Set by Connect Threads.", readOnly: true, width: "50%" }
|
|
802
|
+
},
|
|
803
|
+
{
|
|
804
|
+
name: "threadsUsername",
|
|
805
|
+
type: "text",
|
|
806
|
+
admin: { description: "Set by Connect Threads.", readOnly: true, width: "50%" }
|
|
807
|
+
}
|
|
808
|
+
]
|
|
809
|
+
},
|
|
810
|
+
{
|
|
811
|
+
name: "threadsAccessToken",
|
|
812
|
+
type: "text",
|
|
813
|
+
admin: {
|
|
814
|
+
hidden: true,
|
|
815
|
+
description: "Internal \u2014 long-lived Threads access token."
|
|
816
|
+
},
|
|
817
|
+
hooks: {
|
|
818
|
+
beforeChange: [
|
|
819
|
+
async ({ value, originalDoc, req }) => await encryptBeforeChange({ value, originalDoc, field: { name: "threadsAccessToken" }, req })
|
|
820
|
+
],
|
|
821
|
+
afterRead: [
|
|
822
|
+
({ value, req, context }) => decryptAfterRead({ value, req, context })
|
|
823
|
+
]
|
|
824
|
+
}
|
|
825
|
+
},
|
|
826
|
+
{
|
|
827
|
+
name: "threadsTokenExpiresAt",
|
|
828
|
+
type: "date",
|
|
829
|
+
admin: {
|
|
830
|
+
hidden: true,
|
|
831
|
+
description: "Internal \u2014 when threadsAccessToken expires (~60 days from Connect Threads)."
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
]
|
|
835
|
+
}
|
|
836
|
+
]
|
|
837
|
+
}
|
|
838
|
+
],
|
|
839
|
+
timestamps: true
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
// src/endpoints/metaCatalogFeed.ts
|
|
843
|
+
function csvEscape(value) {
|
|
844
|
+
const str = value === null || value === void 0 ? "" : String(value);
|
|
845
|
+
if (str.includes(",") || str.includes('"') || str.includes("\n")) {
|
|
846
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
847
|
+
}
|
|
848
|
+
return str;
|
|
849
|
+
}
|
|
850
|
+
function firstDefined(...values) {
|
|
851
|
+
for (const v of values) {
|
|
852
|
+
if (v !== void 0 && v !== null && v !== "") return v;
|
|
853
|
+
}
|
|
854
|
+
return void 0;
|
|
855
|
+
}
|
|
856
|
+
function stripHtml(input) {
|
|
857
|
+
return input.replace(/<[^>]+>/g, "").trim();
|
|
858
|
+
}
|
|
859
|
+
function resolveImageUrl(media, serverUrl4) {
|
|
860
|
+
if (!media) return "";
|
|
861
|
+
if (typeof media === "string") {
|
|
862
|
+
if (media.startsWith("http://") || media.startsWith("https://")) return media;
|
|
863
|
+
return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
|
|
864
|
+
}
|
|
865
|
+
if (typeof media === "object") {
|
|
866
|
+
const m = media;
|
|
867
|
+
const url = m.url || void 0;
|
|
868
|
+
if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
|
|
869
|
+
const filename = m.filename || void 0;
|
|
870
|
+
if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
|
|
871
|
+
}
|
|
872
|
+
return "";
|
|
873
|
+
}
|
|
874
|
+
var metaCatalogFeedEndpoint = {
|
|
875
|
+
path: "/meta-catalog/feed",
|
|
876
|
+
method: "get",
|
|
877
|
+
handler: async (req) => {
|
|
878
|
+
const siteSlug = req.query?.site;
|
|
879
|
+
if (!siteSlug) {
|
|
880
|
+
return Response.json({ error: "Missing required query param: site" }, { status: 400 });
|
|
881
|
+
}
|
|
882
|
+
const sites = await req.payload.find({
|
|
883
|
+
collection: "sites",
|
|
884
|
+
where: { slug: { equals: siteSlug } },
|
|
885
|
+
limit: 1,
|
|
886
|
+
depth: 0,
|
|
887
|
+
overrideAccess: true
|
|
888
|
+
});
|
|
889
|
+
if (sites.totalDocs === 0) {
|
|
890
|
+
return Response.json({ error: "Site not found" }, { status: 404 });
|
|
891
|
+
}
|
|
892
|
+
const siteId = sites.docs[0].id;
|
|
893
|
+
const configs = await req.payload.find({
|
|
894
|
+
collection: asCollectionSlug("meta-config"),
|
|
895
|
+
where: { site: { equals: siteId }, isActive: { equals: true }, catalogEnabled: { equals: true } },
|
|
896
|
+
limit: 1,
|
|
897
|
+
depth: 0,
|
|
898
|
+
overrideAccess: true
|
|
899
|
+
});
|
|
900
|
+
if (configs.totalDocs === 0) {
|
|
901
|
+
return Response.json({ error: "Commerce Catalog not enabled for this site" }, { status: 404 });
|
|
902
|
+
}
|
|
903
|
+
const config = configs.docs[0];
|
|
904
|
+
const sourceCollection = config.catalogSourceCollection;
|
|
905
|
+
const urlTemplate = config.catalogItemUrlTemplate;
|
|
906
|
+
if (!sourceCollection) {
|
|
907
|
+
return Response.json({ error: "catalogSourceCollection not configured for this site" }, { status: 400 });
|
|
908
|
+
}
|
|
909
|
+
if (!urlTemplate) {
|
|
910
|
+
return Response.json({ error: "catalogItemUrlTemplate not configured for this site" }, { status: 400 });
|
|
911
|
+
}
|
|
912
|
+
const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
|
|
913
|
+
let items;
|
|
914
|
+
try {
|
|
915
|
+
const result = await req.payload.find({
|
|
916
|
+
collection: asCollectionSlug(sourceCollection),
|
|
917
|
+
where: { site: { equals: siteId } },
|
|
918
|
+
limit: 1e3,
|
|
919
|
+
depth: 1,
|
|
920
|
+
overrideAccess: true
|
|
921
|
+
});
|
|
922
|
+
items = result.docs;
|
|
923
|
+
} catch (err) {
|
|
924
|
+
req.payload.logger.error(`[MetaCatalogFeed] Failed to query collection "${sourceCollection}": ${err}`);
|
|
925
|
+
return Response.json({ error: `Failed to query collection "${sourceCollection}"` }, { status: 500 });
|
|
926
|
+
}
|
|
927
|
+
const header = ["id", "title", "description", "availability", "condition", "price", "link", "image_link"];
|
|
928
|
+
const rows = [header.join(",")];
|
|
929
|
+
for (const item of items) {
|
|
930
|
+
const id = String(item.id);
|
|
931
|
+
const title = String(firstDefined(item.title, item.name, item.heading) ?? "");
|
|
932
|
+
const rawDescription = firstDefined(item.description, item.excerpt, item.body);
|
|
933
|
+
const description = rawDescription ? stripHtml(String(rawDescription)).slice(0, 5e3) : "";
|
|
934
|
+
const price = firstDefined(item.price, item.price_from, item.priceFrom);
|
|
935
|
+
const available = item.available === void 0 ? true : Boolean(item.available);
|
|
936
|
+
const slug = String(firstDefined(item.slug, item.id));
|
|
937
|
+
const link = urlTemplate.replace("{slug}", encodeURIComponent(slug));
|
|
938
|
+
const image = firstDefined(item.image, item.featuredImage, item.photo);
|
|
939
|
+
const imageLink = resolveImageUrl(image, serverUrl4);
|
|
940
|
+
if (!title || price === void 0) continue;
|
|
941
|
+
rows.push([
|
|
942
|
+
csvEscape(id),
|
|
943
|
+
csvEscape(title),
|
|
944
|
+
csvEscape(description),
|
|
945
|
+
csvEscape(available ? "in stock" : "out of stock"),
|
|
946
|
+
csvEscape("new"),
|
|
947
|
+
csvEscape(`${Number(price).toFixed(2)} NGN`),
|
|
948
|
+
csvEscape(link),
|
|
949
|
+
csvEscape(imageLink)
|
|
950
|
+
].join(","));
|
|
951
|
+
}
|
|
952
|
+
return new Response(rows.join("\n"), {
|
|
953
|
+
status: 200,
|
|
954
|
+
headers: {
|
|
955
|
+
"Content-Type": "text/csv; charset=utf-8",
|
|
956
|
+
"Cache-Control": "public, max-age=3600"
|
|
957
|
+
}
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
|
|
962
|
+
// src/actions/metaActions.ts
|
|
963
|
+
import { createHash } from "crypto";
|
|
964
|
+
|
|
965
|
+
// src/utils/metaCredentials.ts
|
|
966
|
+
async function getMetaCredentials(payload, siteSlug, _req) {
|
|
967
|
+
const isMasked = (v) => v.includes("\u2022");
|
|
968
|
+
const buildCreds = (cfg) => {
|
|
969
|
+
const rawToken = cfg.accessToken;
|
|
970
|
+
if (!rawToken) return null;
|
|
971
|
+
const expiresAt = cfg.oauthExpiresAt;
|
|
972
|
+
if (expiresAt && new Date(expiresAt).getTime() <= Date.now()) {
|
|
973
|
+
payload.logger.warn(`[MetaCredentials] accessToken expired for config ${cfg.id} \u2014 marking disconnected.`);
|
|
974
|
+
payload.update({
|
|
975
|
+
collection: asCollectionSlug("meta-config"),
|
|
976
|
+
id: cfg.id,
|
|
977
|
+
data: { connectionStatus: "disconnected" },
|
|
978
|
+
overrideAccess: true,
|
|
979
|
+
context: { skipConnectionTest: true }
|
|
980
|
+
}).catch((err) => payload.logger.warn(`[MetaCredentials] Failed to mark config ${cfg.id} disconnected: ${err}`));
|
|
981
|
+
return null;
|
|
982
|
+
}
|
|
983
|
+
if (isMasked(rawToken)) {
|
|
984
|
+
payload.logger.error(
|
|
985
|
+
`[MetaCredentials] Credential masking leaked through for config ${cfg.id}. This indicates a Payload framework bug. Failing closed \u2014 do NOT fall back to raw SQL.`
|
|
986
|
+
);
|
|
987
|
+
return null;
|
|
988
|
+
}
|
|
989
|
+
const accessToken = rawToken.startsWith("enc:") ? decryptCredential(rawToken) : rawToken;
|
|
990
|
+
if (!accessToken || isMasked(accessToken)) return null;
|
|
991
|
+
return {
|
|
992
|
+
accessToken,
|
|
993
|
+
businessManagerId: cfg.businessManagerId || void 0,
|
|
994
|
+
pixelId: cfg.pixelEnabled && cfg.pixelId ? cfg.pixelId : void 0,
|
|
995
|
+
catalogId: cfg.catalogEnabled && cfg.catalogId ? cfg.catalogId : void 0,
|
|
996
|
+
whatsappPhoneNumberId: cfg.whatsappEnabled && cfg.whatsappPhoneNumberId ? cfg.whatsappPhoneNumberId : void 0,
|
|
997
|
+
whatsappBusinessAccountId: cfg.whatsappEnabled && cfg.whatsappBusinessAccountId ? cfg.whatsappBusinessAccountId : void 0
|
|
998
|
+
};
|
|
999
|
+
};
|
|
1000
|
+
if (!siteSlug) return null;
|
|
1001
|
+
const sites = await payload.find({
|
|
1002
|
+
collection: "sites",
|
|
1003
|
+
where: { slug: { equals: siteSlug } },
|
|
1004
|
+
limit: 1,
|
|
1005
|
+
depth: 0,
|
|
1006
|
+
overrideAccess: true
|
|
1007
|
+
});
|
|
1008
|
+
if (sites.totalDocs === 0) return null;
|
|
1009
|
+
const configs = await payload.find({
|
|
1010
|
+
collection: asCollectionSlug("meta-config"),
|
|
1011
|
+
where: { site: { equals: sites.docs[0].id }, isActive: { equals: true } },
|
|
1012
|
+
limit: 1,
|
|
1013
|
+
depth: 0,
|
|
1014
|
+
overrideAccess: true,
|
|
1015
|
+
context: { preventMasking: true }
|
|
1016
|
+
});
|
|
1017
|
+
if (configs.totalDocs === 0) return null;
|
|
1018
|
+
return buildCreds(configs.docs[0]);
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
// src/sync/conversionsApi.ts
|
|
1022
|
+
async function sendConversionEvent(creds, input, log) {
|
|
1023
|
+
if (!creds.pixelId) {
|
|
1024
|
+
return { ok: false, error: "Meta Pixel not enabled/configured for this site" };
|
|
1025
|
+
}
|
|
1026
|
+
if (!creds.accessToken) {
|
|
1027
|
+
return { ok: false, error: "Meta access token not configured for this site" };
|
|
1028
|
+
}
|
|
1029
|
+
const event = {
|
|
1030
|
+
event_name: input.eventName,
|
|
1031
|
+
event_time: input.eventTime ?? Math.floor(Date.now() / 1e3),
|
|
1032
|
+
action_source: input.actionSource ?? "website"
|
|
1033
|
+
};
|
|
1034
|
+
if (input.eventId) event.event_id = input.eventId;
|
|
1035
|
+
if (input.eventSourceUrl) event.event_source_url = input.eventSourceUrl;
|
|
1036
|
+
if (input.customData) event.custom_data = input.customData;
|
|
1037
|
+
const userData = {};
|
|
1038
|
+
if (input.userData?.emailHash) userData.em = [input.userData.emailHash];
|
|
1039
|
+
if (input.userData?.phoneHash) userData.ph = [input.userData.phoneHash];
|
|
1040
|
+
if (input.userData?.clientIpAddress) userData.client_ip_address = input.userData.clientIpAddress;
|
|
1041
|
+
if (input.userData?.clientUserAgent) userData.client_user_agent = input.userData.clientUserAgent;
|
|
1042
|
+
if (Object.keys(userData).length > 0) event.user_data = userData;
|
|
1043
|
+
try {
|
|
1044
|
+
const res = await fetch(
|
|
1045
|
+
`https://graph.facebook.com/v21.0/${creds.pixelId}/events`,
|
|
1046
|
+
{
|
|
1047
|
+
method: "POST",
|
|
1048
|
+
headers: { "Content-Type": "application/json" },
|
|
1049
|
+
body: JSON.stringify({
|
|
1050
|
+
data: [event],
|
|
1051
|
+
access_token: creds.accessToken
|
|
1052
|
+
}),
|
|
1053
|
+
signal: AbortSignal.timeout(15e3)
|
|
1054
|
+
}
|
|
1055
|
+
);
|
|
1056
|
+
const body = await res.json().catch(() => ({}));
|
|
1057
|
+
if (!res.ok) {
|
|
1058
|
+
const msg = body?.error?.message || `Meta CAPI error: ${res.status}`;
|
|
1059
|
+
log?.("warn", `[MetaConversionsApi] ${input.eventName} failed: ${msg}`);
|
|
1060
|
+
return { ok: false, status: res.status, error: msg };
|
|
1061
|
+
}
|
|
1062
|
+
log?.("info", `[MetaConversionsApi] Sent ${input.eventName} to pixel ${creds.pixelId}`);
|
|
1063
|
+
return { ok: true, status: res.status, eventsReceived: body.events_received };
|
|
1064
|
+
} catch (err) {
|
|
1065
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1066
|
+
log?.("error", `[MetaConversionsApi] ${input.eventName} network error: ${msg}`);
|
|
1067
|
+
return { ok: false, error: msg };
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// src/actions/metaActions.ts
|
|
1072
|
+
function hashPii(value) {
|
|
1073
|
+
return createHash("sha256").update(value.trim().toLowerCase()).digest("hex");
|
|
1074
|
+
}
|
|
1075
|
+
function dottedPathLookup(ctx, path) {
|
|
1076
|
+
return path.split(".").reduce((o, k) => o === void 0 || o === null ? void 0 : o[k], ctx);
|
|
1077
|
+
}
|
|
1078
|
+
function resolveValue(template, ctx) {
|
|
1079
|
+
const wholeMatch = template.trim().match(/^\{\{\s*([\w.]+)\s*\}\}$/);
|
|
1080
|
+
if (wholeMatch) {
|
|
1081
|
+
const val = dottedPathLookup(ctx, wholeMatch[1]);
|
|
1082
|
+
return val !== void 0 ? val : template;
|
|
1083
|
+
}
|
|
1084
|
+
if (template.includes("{{")) {
|
|
1085
|
+
return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_match, key) => {
|
|
1086
|
+
const val = dottedPathLookup(ctx, key);
|
|
1087
|
+
return val !== void 0 && val !== null ? String(val) : "";
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
return template;
|
|
1091
|
+
}
|
|
1092
|
+
async function metaConversionEventHandler(ctx) {
|
|
1093
|
+
const { payload, workflowContext, step } = ctx;
|
|
1094
|
+
const siteSlug = workflowContext.siteSlug;
|
|
1095
|
+
const creds = await getMetaCredentials(payload, siteSlug);
|
|
1096
|
+
if (!creds) return { success: false, error: "Missing Meta credentials for site: " + siteSlug };
|
|
1097
|
+
if (!creds.pixelId) return { success: false, error: `Meta Pixel not enabled for site: ${siteSlug}` };
|
|
1098
|
+
const eventName = step.event_name;
|
|
1099
|
+
if (!eventName) return { success: false, error: "meta-conversion-event requires event_name" };
|
|
1100
|
+
const rawValue = step.value ? resolveValue(String(step.value), workflowContext) : void 0;
|
|
1101
|
+
const numericValue = rawValue !== void 0 ? Number(rawValue) : void 0;
|
|
1102
|
+
const currency = step.currency ? String(resolveValue(String(step.currency), workflowContext)) : "NGN";
|
|
1103
|
+
const contentName = step.content_name ? String(resolveValue(String(step.content_name), workflowContext)) : void 0;
|
|
1104
|
+
const eventSourceUrl = step.event_source_url ? String(resolveValue(String(step.event_source_url), workflowContext)) : void 0;
|
|
1105
|
+
const email = step.email ? String(resolveValue(String(step.email), workflowContext)) : void 0;
|
|
1106
|
+
const phone = step.phone ? String(resolveValue(String(step.phone), workflowContext)) : void 0;
|
|
1107
|
+
const customData = {};
|
|
1108
|
+
if (numericValue !== void 0 && !Number.isNaN(numericValue)) {
|
|
1109
|
+
customData.value = numericValue;
|
|
1110
|
+
customData.currency = currency;
|
|
1111
|
+
}
|
|
1112
|
+
if (contentName) customData.content_name = contentName;
|
|
1113
|
+
const userData = {};
|
|
1114
|
+
if (email) userData.emailHash = hashPii(email);
|
|
1115
|
+
if (phone) userData.phoneHash = hashPii(phone.replace(/[^0-9]/g, ""));
|
|
1116
|
+
const result = await sendConversionEvent(
|
|
1117
|
+
creds,
|
|
1118
|
+
{
|
|
1119
|
+
eventName,
|
|
1120
|
+
eventSourceUrl,
|
|
1121
|
+
customData: Object.keys(customData).length > 0 ? customData : void 0,
|
|
1122
|
+
userData: Object.keys(userData).length > 0 ? userData : void 0
|
|
1123
|
+
},
|
|
1124
|
+
(level, msg) => payload.logger[level](msg)
|
|
1125
|
+
);
|
|
1126
|
+
if (!result.ok) return { success: false, error: result.error };
|
|
1127
|
+
return { success: true, data: { meta_event_sent: eventName, meta_events_received: result.eventsReceived } };
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
// src/utils/metaGraphClient.ts
|
|
1131
|
+
var MAX_RETRIES = 2;
|
|
1132
|
+
var BASE_DELAY_MS = 800;
|
|
1133
|
+
function sleep(ms) {
|
|
1134
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1135
|
+
}
|
|
1136
|
+
async function parseGraphError(res) {
|
|
1137
|
+
try {
|
|
1138
|
+
const body = await res.json();
|
|
1139
|
+
if (body?.error?.message) return body.error.message;
|
|
1140
|
+
} catch {
|
|
1141
|
+
}
|
|
1142
|
+
return `Graph API error: ${res.status}`;
|
|
1143
|
+
}
|
|
1144
|
+
async function callWithRetry(url, init) {
|
|
1145
|
+
let lastErr;
|
|
1146
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
1147
|
+
try {
|
|
1148
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(2e4) });
|
|
1149
|
+
if (!res.ok && res.status >= 500 && attempt < MAX_RETRIES) {
|
|
1150
|
+
await sleep(BASE_DELAY_MS * Math.pow(2, attempt));
|
|
1151
|
+
continue;
|
|
1152
|
+
}
|
|
1153
|
+
return res;
|
|
1154
|
+
} catch (err) {
|
|
1155
|
+
lastErr = err instanceof Error ? err : new Error(String(err));
|
|
1156
|
+
if (attempt < MAX_RETRIES) {
|
|
1157
|
+
await sleep(BASE_DELAY_MS * Math.pow(2, attempt));
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
throw lastErr ?? new Error("Graph API request failed");
|
|
1162
|
+
}
|
|
1163
|
+
var GRAPH_API_VERSION = "v21.0";
|
|
1164
|
+
var GRAPH_BASE = `https://graph.facebook.com/${GRAPH_API_VERSION}`;
|
|
1165
|
+
var THREADS_BASE = "https://graph.threads.net";
|
|
1166
|
+
async function graphGet(path, params) {
|
|
1167
|
+
const qs = new URLSearchParams(params).toString();
|
|
1168
|
+
const res = await callWithRetry(`${GRAPH_BASE}${path}?${qs}`, { method: "GET" });
|
|
1169
|
+
if (!res.ok) return { ok: false, status: res.status, error: await parseGraphError(res) };
|
|
1170
|
+
return { ok: true, status: res.status, data: await res.json() };
|
|
1171
|
+
}
|
|
1172
|
+
async function graphPost(path, params) {
|
|
1173
|
+
const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
|
|
1174
|
+
method: "POST",
|
|
1175
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1176
|
+
body: new URLSearchParams(params).toString()
|
|
1177
|
+
});
|
|
1178
|
+
if (!res.ok) return { ok: false, status: res.status, error: await parseGraphError(res) };
|
|
1179
|
+
return { ok: true, status: res.status, data: await res.json() };
|
|
1180
|
+
}
|
|
1181
|
+
async function graphPostJson(path, body, accessToken) {
|
|
1182
|
+
const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
|
|
1183
|
+
method: "POST",
|
|
1184
|
+
headers: {
|
|
1185
|
+
"Content-Type": "application/json",
|
|
1186
|
+
Authorization: `Bearer ${accessToken}`
|
|
1187
|
+
},
|
|
1188
|
+
body: JSON.stringify(body)
|
|
1189
|
+
});
|
|
1190
|
+
if (!res.ok) return { ok: false, status: res.status, error: await parseGraphError(res) };
|
|
1191
|
+
return { ok: true, status: res.status, data: await readGraphJson(res) };
|
|
1192
|
+
}
|
|
1193
|
+
async function readGraphJson(res) {
|
|
1194
|
+
const text2 = await res.text();
|
|
1195
|
+
if (!text2) return {};
|
|
1196
|
+
return JSON.parse(text2);
|
|
1197
|
+
}
|
|
1198
|
+
async function graphDelete(path, accessToken) {
|
|
1199
|
+
const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
|
|
1200
|
+
method: "DELETE",
|
|
1201
|
+
headers: { Authorization: `Bearer ${accessToken}` }
|
|
1202
|
+
});
|
|
1203
|
+
if (!res.ok) return { ok: false, status: res.status, error: await parseGraphError(res) };
|
|
1204
|
+
return { ok: true, status: res.status, data: await readGraphJson(res) };
|
|
1205
|
+
}
|
|
1206
|
+
async function threadsGet(path, params) {
|
|
1207
|
+
const qs = new URLSearchParams(params).toString();
|
|
1208
|
+
const res = await callWithRetry(`${THREADS_BASE}${path}?${qs}`, { method: "GET" });
|
|
1209
|
+
if (!res.ok) return { ok: false, status: res.status, error: await parseGraphError(res) };
|
|
1210
|
+
return { ok: true, status: res.status, data: await res.json() };
|
|
1211
|
+
}
|
|
1212
|
+
async function threadsPost(path, params) {
|
|
1213
|
+
const res = await callWithRetry(`${THREADS_BASE}${path}`, {
|
|
1214
|
+
method: "POST",
|
|
1215
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1216
|
+
body: new URLSearchParams(params).toString()
|
|
1217
|
+
});
|
|
1218
|
+
if (!res.ok) return { ok: false, status: res.status, error: await parseGraphError(res) };
|
|
1219
|
+
return { ok: true, status: res.status, data: await res.json() };
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// src/oauth/popupResult.ts
|
|
1223
|
+
var META_OAUTH_MESSAGE_SOURCE = "payload-meta-oauth";
|
|
1224
|
+
function oauthPopupResponse(args) {
|
|
1225
|
+
const message = JSON.stringify({
|
|
1226
|
+
source: META_OAUTH_MESSAGE_SOURCE,
|
|
1227
|
+
ok: args.ok,
|
|
1228
|
+
error: args.error
|
|
1229
|
+
}).replace(/</g, "\\u003c");
|
|
1230
|
+
const nextUrl = JSON.stringify(args.nextUrl).replace(/</g, "\\u003c");
|
|
1231
|
+
const heading = args.ok ? "Facebook login finished." : "Facebook login did not finish.";
|
|
1232
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><title>Meta</title></head><body><p>${heading} You can close this window.</p><script>(function(){var message=${message};var nextUrl=${nextUrl};try{if(window.opener&&!window.opener.closed){window.opener.postMessage(message,window.location.origin);window.close();return;}}catch(e){}window.location.replace(nextUrl);})();</script></body></html>`;
|
|
1233
|
+
return new Response(html, {
|
|
1234
|
+
status: 200,
|
|
1235
|
+
headers: {
|
|
1236
|
+
"content-type": "text/html; charset=utf-8",
|
|
1237
|
+
"cache-control": "no-store",
|
|
1238
|
+
"referrer-policy": "no-referrer"
|
|
1239
|
+
}
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// src/sync/catalogProduct.ts
|
|
1244
|
+
var COMMERCE_COLLECTION = "catalogue-items";
|
|
1245
|
+
function firstDefined2(...values) {
|
|
1246
|
+
for (const value of values) {
|
|
1247
|
+
if (value !== void 0 && value !== null && value !== "") return value;
|
|
1248
|
+
}
|
|
1249
|
+
return void 0;
|
|
1250
|
+
}
|
|
1251
|
+
function plainText(value) {
|
|
1252
|
+
if (typeof value === "string") return value;
|
|
1253
|
+
if (typeof value === "number") return String(value);
|
|
1254
|
+
if (value && typeof value === "object") {
|
|
1255
|
+
const record = value;
|
|
1256
|
+
for (const entry of Object.values(record)) {
|
|
1257
|
+
if (typeof entry === "string" && entry.trim()) return entry;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return "";
|
|
1261
|
+
}
|
|
1262
|
+
function stripHtml2(input) {
|
|
1263
|
+
return input.replace(/<[^>]+>/g, "").trim();
|
|
1264
|
+
}
|
|
1265
|
+
function resolveImageUrl2(media, serverUrl4) {
|
|
1266
|
+
if (!media) return "";
|
|
1267
|
+
if (typeof media === "string") {
|
|
1268
|
+
if (media.startsWith("http://") || media.startsWith("https://")) return media;
|
|
1269
|
+
return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
|
|
1270
|
+
}
|
|
1271
|
+
if (typeof media === "object") {
|
|
1272
|
+
const record = media;
|
|
1273
|
+
const url = typeof record.url === "string" ? record.url : "";
|
|
1274
|
+
if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
|
|
1275
|
+
const filename = typeof record.filename === "string" ? record.filename : "";
|
|
1276
|
+
if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
|
|
1277
|
+
}
|
|
1278
|
+
return "";
|
|
1279
|
+
}
|
|
1280
|
+
function relationId2(value) {
|
|
1281
|
+
if (typeof value === "string" || typeof value === "number") return value;
|
|
1282
|
+
if (value && typeof value === "object" && "id" in value) {
|
|
1283
|
+
const id = value.id;
|
|
1284
|
+
if (typeof id === "string" || typeof id === "number") return id;
|
|
1285
|
+
}
|
|
1286
|
+
return void 0;
|
|
1287
|
+
}
|
|
1288
|
+
function catalogSourceSlug(configured) {
|
|
1289
|
+
const slug = typeof configured === "string" ? configured.trim() : "";
|
|
1290
|
+
return slug || COMMERCE_COLLECTION;
|
|
1291
|
+
}
|
|
1292
|
+
function toCatalogItem(doc, options) {
|
|
1293
|
+
const title = plainText(firstDefined2(doc.title, doc.name, doc.heading)).trim();
|
|
1294
|
+
const price = firstDefined2(doc.price, doc.price_from, doc.priceFrom);
|
|
1295
|
+
if (!title || price === void 0 || price === null || price === "") return null;
|
|
1296
|
+
const amount = Number(price);
|
|
1297
|
+
if (!Number.isFinite(amount)) return null;
|
|
1298
|
+
const slug = plainText(firstDefined2(doc.slug, doc.id));
|
|
1299
|
+
const template = options.urlTemplate.trim();
|
|
1300
|
+
if (!template.includes("{slug}")) return null;
|
|
1301
|
+
const rawDescription = firstDefined2(doc.description, doc.excerpt, doc.body);
|
|
1302
|
+
const description = rawDescription ? stripHtml2(plainText(rawDescription)).slice(0, 5e3) : title;
|
|
1303
|
+
const available = doc.available === void 0 ? true : Boolean(doc.available);
|
|
1304
|
+
const currency = (options.currency || "NGN").toUpperCase();
|
|
1305
|
+
const image = resolveImageUrl2(firstDefined2(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
|
|
1306
|
+
const item = {
|
|
1307
|
+
id: String(doc.id),
|
|
1308
|
+
title,
|
|
1309
|
+
description,
|
|
1310
|
+
availability: available ? "in stock" : "out of stock",
|
|
1311
|
+
condition: "new",
|
|
1312
|
+
price: `${amount.toFixed(2)} ${currency}`,
|
|
1313
|
+
link: template.replace("{slug}", encodeURIComponent(slug))
|
|
1314
|
+
};
|
|
1315
|
+
if (image) item.image_link = image;
|
|
1316
|
+
if (options.brand) item.brand = options.brand;
|
|
1317
|
+
return item;
|
|
1318
|
+
}
|
|
1319
|
+
function updateRequest(item) {
|
|
1320
|
+
return { method: "UPDATE", data: item };
|
|
1321
|
+
}
|
|
1322
|
+
function deleteRequest(retailerId) {
|
|
1323
|
+
return { method: "DELETE", data: { id: retailerId } };
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
// src/sync/catalogSync.ts
|
|
1327
|
+
function decryptToken(value) {
|
|
1328
|
+
if (typeof value !== "string" || !value || value.includes("\u2022")) return "";
|
|
1329
|
+
return value.startsWith("enc:") ? decryptCredential(value) : value;
|
|
1330
|
+
}
|
|
1331
|
+
function tokenForCatalog(config) {
|
|
1332
|
+
return decryptToken(config.oauthUserAccessToken) || decryptToken(config.accessToken);
|
|
1333
|
+
}
|
|
1334
|
+
async function findCatalogConfig(payload, siteId) {
|
|
1335
|
+
const configs = await payload.find({
|
|
1336
|
+
collection: asCollectionSlug("meta-config"),
|
|
1337
|
+
where: {
|
|
1338
|
+
and: [
|
|
1339
|
+
{ site: { equals: siteId } },
|
|
1340
|
+
{ isActive: { equals: true } },
|
|
1341
|
+
{ catalogEnabled: { equals: true } }
|
|
1342
|
+
]
|
|
1343
|
+
},
|
|
1344
|
+
limit: 1,
|
|
1345
|
+
depth: 0,
|
|
1346
|
+
overrideAccess: true,
|
|
1347
|
+
context: { preventMasking: true }
|
|
1348
|
+
});
|
|
1349
|
+
const config = configs.docs[0];
|
|
1350
|
+
if (!config) return null;
|
|
1351
|
+
const catalogId = typeof config.catalogId === "string" ? config.catalogId.trim() : "";
|
|
1352
|
+
const urlTemplate = typeof config.catalogItemUrlTemplate === "string" ? config.catalogItemUrlTemplate.trim() : "";
|
|
1353
|
+
const token = tokenForCatalog(config);
|
|
1354
|
+
if (!catalogId || !urlTemplate || !token) return null;
|
|
1355
|
+
return {
|
|
1356
|
+
id: config.id,
|
|
1357
|
+
catalogId,
|
|
1358
|
+
sourceCollection: catalogSourceSlug(config.catalogSourceCollection),
|
|
1359
|
+
urlTemplate,
|
|
1360
|
+
token,
|
|
1361
|
+
brand: typeof config.facebookPageName === "string" ? config.facebookPageName : void 0
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
async function pushBatch(catalogId, token, requests) {
|
|
1365
|
+
const result = await graphPost(
|
|
1366
|
+
`/${catalogId}/items_batch`,
|
|
1367
|
+
{
|
|
1368
|
+
access_token: token,
|
|
1369
|
+
item_type: "PRODUCT",
|
|
1370
|
+
allow_upsert: "true",
|
|
1371
|
+
requests: JSON.stringify(requests)
|
|
1372
|
+
}
|
|
1373
|
+
);
|
|
1374
|
+
if (!result.ok) return result.error || "Meta catalog update failed";
|
|
1375
|
+
const messages = (result.data?.validation_status ?? []).flatMap((row) => row.errors ?? []).map((error) => error.message).filter((message) => Boolean(message));
|
|
1376
|
+
return messages.length ? messages.join("; ") : null;
|
|
1377
|
+
}
|
|
1378
|
+
async function syncCatalogDoc(payload, doc, method, collectionSlug) {
|
|
1379
|
+
const siteId = relationId2(doc.site);
|
|
1380
|
+
if (siteId == null || doc.id == null) return;
|
|
1381
|
+
const config = await findCatalogConfig(payload, siteId);
|
|
1382
|
+
if (!config || config.sourceCollection !== collectionSlug) return;
|
|
1383
|
+
const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
|
|
1384
|
+
const request = method === "DELETE" ? deleteRequest(String(doc.id)) : (() => {
|
|
1385
|
+
const item = toCatalogItem(doc, {
|
|
1386
|
+
urlTemplate: config.urlTemplate,
|
|
1387
|
+
serverUrl: serverUrl4,
|
|
1388
|
+
brand: config.brand
|
|
1389
|
+
});
|
|
1390
|
+
return item ? updateRequest(item) : null;
|
|
1391
|
+
})();
|
|
1392
|
+
if (!request) return;
|
|
1393
|
+
const error = await pushBatch(config.catalogId, config.token, [request]);
|
|
1394
|
+
if (error) {
|
|
1395
|
+
payload.logger.warn(`[MetaCatalog] ${method} ${collectionSlug} ${doc.id} failed: ${error}`);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
async function syncCatalogCollection(payload, config, siteId) {
|
|
1399
|
+
const result = { synced: 0, skipped: 0, errors: [] };
|
|
1400
|
+
const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
|
|
1401
|
+
let page = 1;
|
|
1402
|
+
for (; ; ) {
|
|
1403
|
+
const found = await payload.find({
|
|
1404
|
+
collection: asCollectionSlug(config.sourceCollection),
|
|
1405
|
+
where: { site: { equals: siteId } },
|
|
1406
|
+
limit: 100,
|
|
1407
|
+
page,
|
|
1408
|
+
depth: 1,
|
|
1409
|
+
overrideAccess: true
|
|
1410
|
+
});
|
|
1411
|
+
const requests = [];
|
|
1412
|
+
for (const doc of found.docs) {
|
|
1413
|
+
const item = toCatalogItem(doc, {
|
|
1414
|
+
urlTemplate: config.urlTemplate,
|
|
1415
|
+
serverUrl: serverUrl4,
|
|
1416
|
+
brand: config.brand
|
|
1417
|
+
});
|
|
1418
|
+
if (!item) {
|
|
1419
|
+
result.skipped += 1;
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
requests.push(updateRequest(item));
|
|
1423
|
+
}
|
|
1424
|
+
for (let index = 0; index < requests.length; index += 20) {
|
|
1425
|
+
const chunk = requests.slice(index, index + 20);
|
|
1426
|
+
const error = await pushBatch(config.catalogId, config.token, chunk);
|
|
1427
|
+
if (error) result.errors.push(error);
|
|
1428
|
+
else result.synced += chunk.length;
|
|
1429
|
+
}
|
|
1430
|
+
if (!found.hasNextPage) break;
|
|
1431
|
+
page += 1;
|
|
1432
|
+
}
|
|
1433
|
+
return result;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
// src/utils/metaBusinesses.ts
|
|
1437
|
+
async function listBusinesses(token, businessManagerId) {
|
|
1438
|
+
const pinned = typeof businessManagerId === "string" ? businessManagerId.trim() : "";
|
|
1439
|
+
if (pinned) return { ok: true, businesses: [{ id: pinned, name: pinned }] };
|
|
1440
|
+
const listed = await graphGet("/me/businesses", {
|
|
1441
|
+
fields: "id,name",
|
|
1442
|
+
access_token: token,
|
|
1443
|
+
limit: "25"
|
|
1444
|
+
});
|
|
1445
|
+
if (!listed.ok) {
|
|
1446
|
+
return { ok: false, error: listed.error || "Could not read businesses for this Facebook login." };
|
|
1447
|
+
}
|
|
1448
|
+
return {
|
|
1449
|
+
ok: true,
|
|
1450
|
+
businesses: (listed.data?.data ?? []).map((business) => ({
|
|
1451
|
+
id: business.id,
|
|
1452
|
+
name: business.name || business.id
|
|
1453
|
+
}))
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
// src/utils/wabaSubscription.ts
|
|
1458
|
+
async function subscribeWabaToApp(token, wabaId) {
|
|
1459
|
+
if (!token || !wabaId) return { ok: false, error: "A token and a business account are needed to subscribe." };
|
|
1460
|
+
const result = await graphPostJson(`/${encodeURIComponent(wabaId)}/subscribed_apps`, {}, token);
|
|
1461
|
+
return result.ok ? { ok: true } : { ok: false, error: result.error ?? "Meta refused the subscription." };
|
|
1462
|
+
}
|
|
1463
|
+
async function unsubscribeWabaFromApp(token, wabaId) {
|
|
1464
|
+
if (!token || !wabaId) return { ok: false, error: "A token and a business account are needed to unsubscribe." };
|
|
1465
|
+
const result = await graphDelete(`/${encodeURIComponent(wabaId)}/subscribed_apps`, token);
|
|
1466
|
+
return result.ok ? { ok: true } : { ok: false, error: result.error ?? "Meta refused to remove the subscription." };
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// src/endpoints/metaOAuth.ts
|
|
1470
|
+
var OAUTH_SCOPES = [
|
|
1471
|
+
"business_management",
|
|
1472
|
+
"pages_show_list",
|
|
1473
|
+
"pages_read_engagement",
|
|
1474
|
+
"pages_manage_metadata",
|
|
1475
|
+
"instagram_basic",
|
|
1476
|
+
"ads_management",
|
|
1477
|
+
"catalog_management",
|
|
1478
|
+
"whatsapp_business_management",
|
|
1479
|
+
"whatsapp_business_messaging"
|
|
1480
|
+
].join(",");
|
|
1481
|
+
function isAdminOrAbove(req) {
|
|
1482
|
+
const role = getUserWithRole(req.user)?.role;
|
|
1483
|
+
return role === "super-admin" || role === "admin" || role === "editor";
|
|
1484
|
+
}
|
|
1485
|
+
function oauthFinished(args) {
|
|
1486
|
+
const adminBase = `${serverUrl()}/admin/collections/meta-config`;
|
|
1487
|
+
const nextPath = args.configId ? `${adminBase}/${args.configId}` : adminBase;
|
|
1488
|
+
const params = new URLSearchParams();
|
|
1489
|
+
if (args.ok) params.set("meta_oauth_success", "1");
|
|
1490
|
+
if (args.error) params.set("meta_oauth_error", args.error);
|
|
1491
|
+
const nextUrl = params.size ? `${nextPath}?${params}` : nextPath;
|
|
1492
|
+
return oauthPopupResponse({ ok: args.ok, error: args.error ?? null, nextUrl });
|
|
1493
|
+
}
|
|
1494
|
+
function serverUrl() {
|
|
1495
|
+
return (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
|
|
1496
|
+
}
|
|
1497
|
+
function callbackRedirectUri() {
|
|
1498
|
+
return `${serverUrl()}/api/meta-oauth/callback`;
|
|
1499
|
+
}
|
|
1500
|
+
async function loadConfig(payload, configId) {
|
|
1501
|
+
return await payload.findByID({
|
|
1502
|
+
collection: asCollectionSlug("meta-config"),
|
|
1503
|
+
id: configId,
|
|
1504
|
+
depth: 0,
|
|
1505
|
+
overrideAccess: true,
|
|
1506
|
+
context: { preventMasking: true }
|
|
1507
|
+
});
|
|
1508
|
+
}
|
|
1509
|
+
var metaOAuthAppInfoEndpoint = {
|
|
1510
|
+
path: "/meta-oauth/app-info",
|
|
1511
|
+
method: "get",
|
|
1512
|
+
handler: async (req) => {
|
|
1513
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1514
|
+
const creds = getMetaAppCredentials();
|
|
1515
|
+
return Response.json({ configured: Boolean(creds), maskedAppId: getMaskedMetaAppId() });
|
|
1516
|
+
}
|
|
1517
|
+
};
|
|
1518
|
+
var metaOAuthStartEndpoint = {
|
|
1519
|
+
path: "/meta-oauth/start",
|
|
1520
|
+
method: "get",
|
|
1521
|
+
handler: async (req) => {
|
|
1522
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1523
|
+
const configId = req.query?.configId;
|
|
1524
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1525
|
+
let config;
|
|
1526
|
+
try {
|
|
1527
|
+
config = await loadConfig(req.payload, configId);
|
|
1528
|
+
} catch {
|
|
1529
|
+
return Response.json({ error: "Config not found" }, { status: 404 });
|
|
1530
|
+
}
|
|
1531
|
+
if (!callerOwnsConfigSite(req, config)) {
|
|
1532
|
+
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1533
|
+
}
|
|
1534
|
+
const appCreds = getMetaAppCredentials();
|
|
1535
|
+
if (!appCreds) {
|
|
1536
|
+
return Response.json({ error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." }, { status: 400 });
|
|
1537
|
+
}
|
|
1538
|
+
const state = signOAuthState(configId);
|
|
1539
|
+
const params = new URLSearchParams({
|
|
1540
|
+
client_id: appCreds.appId,
|
|
1541
|
+
redirect_uri: callbackRedirectUri(),
|
|
1542
|
+
state,
|
|
1543
|
+
scope: OAUTH_SCOPES,
|
|
1544
|
+
response_type: "code"
|
|
1545
|
+
});
|
|
1546
|
+
if (req.query?.popup === "1") params.set("display", "popup");
|
|
1547
|
+
return Response.redirect(`https://www.facebook.com/${GRAPH_API_VERSION}/dialog/oauth?${params}`, 302);
|
|
1548
|
+
}
|
|
1549
|
+
};
|
|
1550
|
+
var metaOAuthCallbackEndpoint = {
|
|
1551
|
+
path: "/meta-oauth/callback",
|
|
1552
|
+
method: "get",
|
|
1553
|
+
handler: async (req) => {
|
|
1554
|
+
const code = req.query?.code;
|
|
1555
|
+
const state = req.query?.state;
|
|
1556
|
+
const oauthError = req.query?.error_description;
|
|
1557
|
+
if (oauthError) {
|
|
1558
|
+
return oauthFinished({ ok: false, error: oauthError });
|
|
1559
|
+
}
|
|
1560
|
+
if (!code || !state) {
|
|
1561
|
+
return oauthFinished({ ok: false, error: "Missing code or state" });
|
|
1562
|
+
}
|
|
1563
|
+
const configId = verifyOAuthState(state);
|
|
1564
|
+
if (!configId) {
|
|
1565
|
+
return oauthFinished({ ok: false, error: "Invalid or expired connect request \u2014 try again" });
|
|
1566
|
+
}
|
|
1567
|
+
try {
|
|
1568
|
+
await loadConfig(req.payload, configId);
|
|
1569
|
+
} catch {
|
|
1570
|
+
return oauthFinished({ ok: false, error: "Config not found" });
|
|
1571
|
+
}
|
|
1572
|
+
const appCreds = getMetaAppCredentials();
|
|
1573
|
+
if (!appCreds) {
|
|
1574
|
+
return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." });
|
|
1575
|
+
}
|
|
1576
|
+
const shortLived = await graphGet("/oauth/access_token", {
|
|
1577
|
+
client_id: appCreds.appId,
|
|
1578
|
+
client_secret: appCreds.appSecret,
|
|
1579
|
+
redirect_uri: callbackRedirectUri(),
|
|
1580
|
+
code
|
|
1581
|
+
});
|
|
1582
|
+
if (!shortLived.ok || !shortLived.data?.access_token) {
|
|
1583
|
+
return oauthFinished({ ok: false, configId, error: shortLived.error || "Token exchange failed" });
|
|
1584
|
+
}
|
|
1585
|
+
const longLived = await graphGet("/oauth/access_token", {
|
|
1586
|
+
grant_type: "fb_exchange_token",
|
|
1587
|
+
client_id: appCreds.appId,
|
|
1588
|
+
client_secret: appCreds.appSecret,
|
|
1589
|
+
fb_exchange_token: shortLived.data.access_token
|
|
1590
|
+
});
|
|
1591
|
+
if (!longLived.ok || !longLived.data?.access_token) {
|
|
1592
|
+
return oauthFinished({ ok: false, configId, error: longLived.error || "Long-lived token exchange failed" });
|
|
1593
|
+
}
|
|
1594
|
+
await req.payload.update({
|
|
1595
|
+
collection: asCollectionSlug("meta-config"),
|
|
1596
|
+
id: configId,
|
|
1597
|
+
data: {
|
|
1598
|
+
authMethod: "oauth",
|
|
1599
|
+
oauthUserAccessToken: encryptCredential(longLived.data.access_token)
|
|
1600
|
+
},
|
|
1601
|
+
overrideAccess: true,
|
|
1602
|
+
context: { skipConnectionTest: true }
|
|
1603
|
+
});
|
|
1604
|
+
return oauthFinished({ ok: true, configId });
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
var metaOAuthDisconnectEndpoint = {
|
|
1608
|
+
path: "/meta-oauth/disconnect",
|
|
1609
|
+
method: "post",
|
|
1610
|
+
handler: async (req) => {
|
|
1611
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1612
|
+
const body = await req.json?.();
|
|
1613
|
+
const configId = body?.configId;
|
|
1614
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1615
|
+
let config;
|
|
1616
|
+
try {
|
|
1617
|
+
config = await loadConfig(req.payload, configId);
|
|
1618
|
+
} catch {
|
|
1619
|
+
return Response.json({ error: "Config not found" }, { status: 404 });
|
|
1620
|
+
}
|
|
1621
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1622
|
+
const wabaId = typeof config.whatsappBusinessAccountId === "string" ? config.whatsappBusinessAccountId : "";
|
|
1623
|
+
const token = tokenForCatalog(config);
|
|
1624
|
+
if (wabaId && token) {
|
|
1625
|
+
const removed = await unsubscribeWabaFromApp(token, wabaId);
|
|
1626
|
+
if (!removed.ok) req.payload.logger.warn(`[meta:oauth] could not unsubscribe ${wabaId} on disconnect: ${removed.error}`);
|
|
1627
|
+
}
|
|
1628
|
+
const cleared = clearedMetaUserConnection();
|
|
1629
|
+
await req.payload.update({
|
|
1630
|
+
collection: asCollectionSlug("meta-config"),
|
|
1631
|
+
id: configId,
|
|
1632
|
+
data: cleared,
|
|
1633
|
+
overrideAccess: true,
|
|
1634
|
+
context: { skipConnectionTest: true }
|
|
1635
|
+
});
|
|
1636
|
+
return Response.json({ ok: true, ...cleared });
|
|
1637
|
+
}
|
|
1638
|
+
};
|
|
1639
|
+
var metaOAuthPagesEndpoint = {
|
|
1640
|
+
path: "/meta-oauth/pages",
|
|
1641
|
+
method: "get",
|
|
1642
|
+
handler: async (req) => {
|
|
1643
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1644
|
+
const configId = req.query?.configId;
|
|
1645
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1646
|
+
const config = await loadConfig(req.payload, configId);
|
|
1647
|
+
if (!callerOwnsConfigSite(req, config)) {
|
|
1648
|
+
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1649
|
+
}
|
|
1650
|
+
const rawToken = config.oauthUserAccessToken;
|
|
1651
|
+
if (!rawToken) return Response.json({ error: 'Not connected \u2014 click "Connect to Meta Business" first' }, { status: 400 });
|
|
1652
|
+
const userToken2 = rawToken.startsWith("enc:") ? decryptCredential(rawToken) : rawToken;
|
|
1653
|
+
const result = await graphGet("/me/accounts", {
|
|
1654
|
+
fields: "id,name",
|
|
1655
|
+
access_token: userToken2,
|
|
1656
|
+
limit: "100"
|
|
1657
|
+
});
|
|
1658
|
+
if (!result.ok) return Response.json({ error: result.error }, { status: 502 });
|
|
1659
|
+
return Response.json({ pages: result.data?.data ?? [] });
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
var metaOAuthSelectPageEndpoint = {
|
|
1663
|
+
path: "/meta-oauth/select-page",
|
|
1664
|
+
method: "post",
|
|
1665
|
+
handler: async (req) => {
|
|
1666
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1667
|
+
const body = await req.json?.();
|
|
1668
|
+
const configId = body?.configId;
|
|
1669
|
+
const pageId = body?.pageId;
|
|
1670
|
+
if (!configId || !pageId) return Response.json({ error: "Missing configId or pageId" }, { status: 400 });
|
|
1671
|
+
const config = await loadConfig(req.payload, configId);
|
|
1672
|
+
if (!callerOwnsConfigSite(req, config)) {
|
|
1673
|
+
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1674
|
+
}
|
|
1675
|
+
const rawToken = config.oauthUserAccessToken;
|
|
1676
|
+
if (!rawToken) return Response.json({ error: 'Not connected \u2014 click "Connect to Meta Business" first' }, { status: 400 });
|
|
1677
|
+
const userToken2 = rawToken.startsWith("enc:") ? decryptCredential(rawToken) : rawToken;
|
|
1678
|
+
const pagesResult = await graphGet("/me/accounts", {
|
|
1679
|
+
fields: "id,name,access_token",
|
|
1680
|
+
access_token: userToken2,
|
|
1681
|
+
limit: "100"
|
|
1682
|
+
});
|
|
1683
|
+
if (!pagesResult.ok) return Response.json({ error: pagesResult.error }, { status: 502 });
|
|
1684
|
+
const page = (pagesResult.data?.data ?? []).find((p) => p.id === pageId);
|
|
1685
|
+
if (!page || !page.access_token) {
|
|
1686
|
+
return Response.json({ error: "Page not found or not accessible with the current connection" }, { status: 404 });
|
|
1687
|
+
}
|
|
1688
|
+
const igResult = await graphGet(`/${pageId}`, {
|
|
1689
|
+
fields: "instagram_business_account{id,username}",
|
|
1690
|
+
access_token: page.access_token
|
|
1691
|
+
});
|
|
1692
|
+
const igAccount = igResult.ok ? igResult.data?.instagram_business_account : void 0;
|
|
1693
|
+
const oauthExpiresAt = new Date(Date.now() + 60 * 24 * 60 * 60 * 1e3).toISOString();
|
|
1694
|
+
await req.payload.update({
|
|
1695
|
+
collection: asCollectionSlug("meta-config"),
|
|
1696
|
+
id: configId,
|
|
1697
|
+
data: {
|
|
1698
|
+
facebookPageId: page.id,
|
|
1699
|
+
facebookPageName: page.name,
|
|
1700
|
+
accessToken: encryptCredential(page.access_token),
|
|
1701
|
+
instagramBusinessAccountId: igAccount?.id || null,
|
|
1702
|
+
instagramUsername: igAccount?.username || null,
|
|
1703
|
+
oauthExpiresAt,
|
|
1704
|
+
// accessToken is populated now — this is the point the
|
|
1705
|
+
// connection is genuinely usable, not the earlier OAuth
|
|
1706
|
+
// handshake step (see the comment in the callback endpoint).
|
|
1707
|
+
connectionStatus: "connected"
|
|
1708
|
+
},
|
|
1709
|
+
overrideAccess: true,
|
|
1710
|
+
context: { skipConnectionTest: true }
|
|
1711
|
+
});
|
|
1712
|
+
return Response.json({
|
|
1713
|
+
ok: true,
|
|
1714
|
+
facebookPageId: page.id,
|
|
1715
|
+
facebookPageName: page.name,
|
|
1716
|
+
instagramBusinessAccountId: igAccount?.id || null,
|
|
1717
|
+
instagramUsername: igAccount?.username || null
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
var metaOAuthListPixelsEndpoint = {
|
|
1722
|
+
path: "/meta-oauth/pixels",
|
|
1723
|
+
method: "get",
|
|
1724
|
+
handler: async (req) => {
|
|
1725
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1726
|
+
const configId = req.query?.configId;
|
|
1727
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1728
|
+
const config = await loadConfig(req.payload, configId);
|
|
1729
|
+
if (!callerOwnsConfigSite(req, config)) {
|
|
1730
|
+
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1731
|
+
}
|
|
1732
|
+
const token = tokenForCatalog(config);
|
|
1733
|
+
if (!token) return Response.json({ error: "Not connected" }, { status: 400 });
|
|
1734
|
+
const businesses = await listBusinesses(token, config.businessManagerId);
|
|
1735
|
+
if (!businesses.ok) return Response.json({ error: businesses.error }, { status: 502 });
|
|
1736
|
+
const pixels = [];
|
|
1737
|
+
for (const business of businesses.businesses) {
|
|
1738
|
+
const result = await graphGet(`/${business.id}/owned_pixels`, {
|
|
1739
|
+
fields: "id,name",
|
|
1740
|
+
access_token: token,
|
|
1741
|
+
limit: "100"
|
|
1742
|
+
});
|
|
1743
|
+
if (!result.ok) continue;
|
|
1744
|
+
for (const pixel of result.data?.data ?? []) {
|
|
1745
|
+
pixels.push({ id: pixel.id, name: pixel.name || pixel.id, businessId: business.id });
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
return Response.json({ pixels, businesses: businesses.businesses });
|
|
1749
|
+
}
|
|
1750
|
+
};
|
|
1751
|
+
var metaOAuthSelectPixelEndpoint = {
|
|
1752
|
+
path: "/meta-oauth/select-pixel",
|
|
1753
|
+
method: "post",
|
|
1754
|
+
handler: async (req) => {
|
|
1755
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1756
|
+
const body = await req.json?.();
|
|
1757
|
+
if (!body?.configId || !body.pixelId) {
|
|
1758
|
+
return Response.json({ error: "Missing configId or pixelId" }, { status: 400 });
|
|
1759
|
+
}
|
|
1760
|
+
const config = await loadConfig(req.payload, body.configId);
|
|
1761
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1762
|
+
const token = tokenForCatalog(config);
|
|
1763
|
+
if (!token) return Response.json({ error: "Not connected" }, { status: 400 });
|
|
1764
|
+
const pixel = await graphGet(`/${body.pixelId}`, {
|
|
1765
|
+
fields: "id,name",
|
|
1766
|
+
access_token: token
|
|
1767
|
+
});
|
|
1768
|
+
if (!pixel.ok || !pixel.data?.id) {
|
|
1769
|
+
return Response.json({ error: pixel.error || "That Pixel is not on this Facebook login." }, { status: 404 });
|
|
1770
|
+
}
|
|
1771
|
+
await req.payload.update({
|
|
1772
|
+
collection: asCollectionSlug("meta-config"),
|
|
1773
|
+
id: body.configId,
|
|
1774
|
+
data: { pixelId: pixel.data.id, pixelEnabled: true },
|
|
1775
|
+
overrideAccess: true,
|
|
1776
|
+
context: { skipConnectionTest: true }
|
|
1777
|
+
});
|
|
1778
|
+
return Response.json({ ok: true, pixelId: pixel.data.id, name: pixel.data.name || pixel.data.id });
|
|
1779
|
+
}
|
|
1780
|
+
};
|
|
1781
|
+
var metaOAuthCreatePixelEndpoint = {
|
|
1782
|
+
path: "/meta-oauth/pixels",
|
|
1783
|
+
method: "post",
|
|
1784
|
+
handler: async (req) => {
|
|
1785
|
+
if (!isAdminOrAbove(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1786
|
+
const body = await req.json?.();
|
|
1787
|
+
const configId = body?.configId;
|
|
1788
|
+
const name = body?.name?.trim();
|
|
1789
|
+
if (!configId || !name) return Response.json({ error: "Missing configId or name" }, { status: 400 });
|
|
1790
|
+
const config = await loadConfig(req.payload, configId);
|
|
1791
|
+
if (!callerOwnsConfigSite(req, config)) {
|
|
1792
|
+
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1793
|
+
}
|
|
1794
|
+
const token = tokenForCatalog(config);
|
|
1795
|
+
if (!token) return Response.json({ error: "Not connected" }, { status: 400 });
|
|
1796
|
+
const businesses = await listBusinesses(token, body.businessId || config.businessManagerId);
|
|
1797
|
+
if (!businesses.ok) return Response.json({ error: businesses.error }, { status: 502 });
|
|
1798
|
+
const business = businesses.businesses.find((item) => item.id === body.businessId) || businesses.businesses[0];
|
|
1799
|
+
if (!business) return Response.json({ error: "This Facebook login has no Business Manager to own a Pixel." }, { status: 400 });
|
|
1800
|
+
const result = await graphPost(`/${business.id}/adspixels`, {
|
|
1801
|
+
name,
|
|
1802
|
+
access_token: token
|
|
1803
|
+
});
|
|
1804
|
+
if (!result.ok || !result.data?.id) {
|
|
1805
|
+
return Response.json({ error: result.error || "Pixel creation failed" }, { status: 502 });
|
|
1806
|
+
}
|
|
1807
|
+
await req.payload.update({
|
|
1808
|
+
collection: asCollectionSlug("meta-config"),
|
|
1809
|
+
id: configId,
|
|
1810
|
+
data: { pixelId: result.data.id, pixelEnabled: true, businessManagerId: business.id },
|
|
1811
|
+
overrideAccess: true,
|
|
1812
|
+
context: { skipConnectionTest: true }
|
|
1813
|
+
});
|
|
1814
|
+
return Response.json({ ok: true, pixelId: result.data.id, businessId: business.id });
|
|
1815
|
+
}
|
|
1816
|
+
};
|
|
1817
|
+
|
|
1818
|
+
// src/endpoints/threadsOAuth.ts
|
|
1819
|
+
var THREADS_SCOPES = "threads_basic,threads_content_publish";
|
|
1820
|
+
function isAdminOrAbove2(req) {
|
|
1821
|
+
const role = getUserWithRole(req.user)?.role;
|
|
1822
|
+
return role === "super-admin" || role === "admin" || role === "editor";
|
|
1823
|
+
}
|
|
1824
|
+
function serverUrl2() {
|
|
1825
|
+
return (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
|
|
1826
|
+
}
|
|
1827
|
+
function callbackRedirectUri2() {
|
|
1828
|
+
return `${serverUrl2()}/api/threads-oauth/callback`;
|
|
1829
|
+
}
|
|
1830
|
+
async function loadConfig2(payload, configId) {
|
|
1831
|
+
return await payload.findByID({
|
|
1832
|
+
collection: asCollectionSlug("meta-config"),
|
|
1833
|
+
id: configId,
|
|
1834
|
+
depth: 0,
|
|
1835
|
+
overrideAccess: true,
|
|
1836
|
+
context: { preventMasking: true }
|
|
1837
|
+
});
|
|
1838
|
+
}
|
|
1839
|
+
var threadsOAuthStartEndpoint = {
|
|
1840
|
+
path: "/threads-oauth/start",
|
|
1841
|
+
method: "get",
|
|
1842
|
+
handler: async (req) => {
|
|
1843
|
+
if (!isAdminOrAbove2(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1844
|
+
const configId = req.query?.configId;
|
|
1845
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1846
|
+
let config;
|
|
1847
|
+
try {
|
|
1848
|
+
config = await loadConfig2(req.payload, configId);
|
|
1849
|
+
} catch {
|
|
1850
|
+
return Response.json({ error: "Config not found" }, { status: 404 });
|
|
1851
|
+
}
|
|
1852
|
+
if (!callerOwnsConfigSite(req, config)) {
|
|
1853
|
+
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1854
|
+
}
|
|
1855
|
+
const appCreds = getMetaAppCredentials();
|
|
1856
|
+
if (!appCreds) {
|
|
1857
|
+
return Response.json({ error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." }, { status: 400 });
|
|
1858
|
+
}
|
|
1859
|
+
const state = signOAuthState(configId);
|
|
1860
|
+
const params = new URLSearchParams({
|
|
1861
|
+
client_id: appCreds.appId,
|
|
1862
|
+
redirect_uri: callbackRedirectUri2(),
|
|
1863
|
+
state,
|
|
1864
|
+
scope: THREADS_SCOPES,
|
|
1865
|
+
response_type: "code"
|
|
1866
|
+
});
|
|
1867
|
+
return Response.redirect(`https://threads.net/oauth/authorize?${params}`, 302);
|
|
1868
|
+
}
|
|
1869
|
+
};
|
|
1870
|
+
var threadsOAuthCallbackEndpoint = {
|
|
1871
|
+
path: "/threads-oauth/callback",
|
|
1872
|
+
method: "get",
|
|
1873
|
+
handler: async (req) => {
|
|
1874
|
+
const code = req.query?.code;
|
|
1875
|
+
const state = req.query?.state;
|
|
1876
|
+
const oauthError = req.query?.error_description;
|
|
1877
|
+
const adminBase = `${serverUrl2()}/admin/collections/meta-config`;
|
|
1878
|
+
if (oauthError) {
|
|
1879
|
+
return Response.redirect(`${adminBase}?threads_oauth_error=${encodeURIComponent(oauthError)}`, 302);
|
|
1880
|
+
}
|
|
1881
|
+
if (!code || !state) {
|
|
1882
|
+
return Response.redirect(`${adminBase}?threads_oauth_error=${encodeURIComponent("Missing code or state")}`, 302);
|
|
1883
|
+
}
|
|
1884
|
+
const configId = verifyOAuthState(state);
|
|
1885
|
+
if (!configId) {
|
|
1886
|
+
return Response.redirect(`${adminBase}?threads_oauth_error=${encodeURIComponent("Invalid or expired connect request \u2014 try again")}`, 302);
|
|
1887
|
+
}
|
|
1888
|
+
try {
|
|
1889
|
+
await loadConfig2(req.payload, configId);
|
|
1890
|
+
} catch {
|
|
1891
|
+
return Response.redirect(`${adminBase}?threads_oauth_error=${encodeURIComponent("Config not found")}`, 302);
|
|
1892
|
+
}
|
|
1893
|
+
const appCreds = getMetaAppCredentials();
|
|
1894
|
+
if (!appCreds) {
|
|
1895
|
+
return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET.")}`, 302);
|
|
1896
|
+
}
|
|
1897
|
+
const shortLived = await threadsPost("/oauth/access_token", {
|
|
1898
|
+
client_id: appCreds.appId,
|
|
1899
|
+
client_secret: appCreds.appSecret,
|
|
1900
|
+
grant_type: "authorization_code",
|
|
1901
|
+
redirect_uri: callbackRedirectUri2(),
|
|
1902
|
+
code
|
|
1903
|
+
});
|
|
1904
|
+
if (!shortLived.ok || !shortLived.data?.access_token) {
|
|
1905
|
+
return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent(shortLived.error || "Token exchange failed")}`, 302);
|
|
1906
|
+
}
|
|
1907
|
+
const longLived = await threadsGet("/access_token", {
|
|
1908
|
+
grant_type: "th_exchange_token",
|
|
1909
|
+
client_secret: appCreds.appSecret,
|
|
1910
|
+
access_token: shortLived.data.access_token
|
|
1911
|
+
});
|
|
1912
|
+
const finalToken = longLived.ok && longLived.data?.access_token ? longLived.data.access_token : shortLived.data.access_token;
|
|
1913
|
+
const threadsTokenExpiresAt = new Date(
|
|
1914
|
+
Date.now() + (longLived.ok ? longLived.data?.expires_in ?? 60 * 24 * 60 * 60 : 60 * 24 * 60 * 60) * 1e3
|
|
1915
|
+
).toISOString();
|
|
1916
|
+
const profile = await threadsGet("/v1.0/me", {
|
|
1917
|
+
fields: "id,username",
|
|
1918
|
+
access_token: finalToken
|
|
1919
|
+
});
|
|
1920
|
+
await req.payload.update({
|
|
1921
|
+
collection: asCollectionSlug("meta-config"),
|
|
1922
|
+
id: configId,
|
|
1923
|
+
data: {
|
|
1924
|
+
threadsEnabled: true,
|
|
1925
|
+
threadsAccessToken: encryptCredential(finalToken),
|
|
1926
|
+
threadsTokenExpiresAt,
|
|
1927
|
+
threadsUserId: profile.data?.id || null,
|
|
1928
|
+
threadsUsername: profile.data?.username || null
|
|
1929
|
+
},
|
|
1930
|
+
overrideAccess: true,
|
|
1931
|
+
context: { skipConnectionTest: true }
|
|
1932
|
+
});
|
|
1933
|
+
return Response.redirect(`${adminBase}/${configId}?threads_oauth_success=1`, 302);
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
|
|
1937
|
+
// src/endpoints/metaCatalogSync.ts
|
|
1938
|
+
function isAdminOrAbove3(req) {
|
|
1939
|
+
const role = getUserWithRole(req.user)?.role;
|
|
1940
|
+
return role === "super-admin" || role === "admin" || role === "editor";
|
|
1941
|
+
}
|
|
1942
|
+
async function loadConfig3(req, configId) {
|
|
1943
|
+
return await req.payload.findByID({
|
|
1944
|
+
collection: asCollectionSlug("meta-config"),
|
|
1945
|
+
id: configId,
|
|
1946
|
+
depth: 0,
|
|
1947
|
+
overrideAccess: true,
|
|
1948
|
+
context: { preventMasking: true }
|
|
1949
|
+
});
|
|
1950
|
+
}
|
|
1951
|
+
function userToken(config) {
|
|
1952
|
+
const raw = tokenForCatalog(config);
|
|
1953
|
+
return raw;
|
|
1954
|
+
}
|
|
1955
|
+
var metaOAuthMeEndpoint = {
|
|
1956
|
+
path: "/meta-oauth/me",
|
|
1957
|
+
method: "get",
|
|
1958
|
+
handler: async (req) => {
|
|
1959
|
+
if (!isAdminOrAbove3(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1960
|
+
const configId = req.query?.configId;
|
|
1961
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1962
|
+
const config = await loadConfig3(req, configId);
|
|
1963
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1964
|
+
const raw = config.oauthUserAccessToken;
|
|
1965
|
+
if (typeof raw !== "string" || !raw) {
|
|
1966
|
+
return Response.json({ connected: false });
|
|
1967
|
+
}
|
|
1968
|
+
const token = raw.startsWith("enc:") ? decryptCredential(raw) : raw;
|
|
1969
|
+
const me = await graphGet("/me", {
|
|
1970
|
+
fields: "id,name",
|
|
1971
|
+
access_token: token
|
|
1972
|
+
});
|
|
1973
|
+
if (!me.ok) return Response.json({ connected: true, error: me.error }, { status: 502 });
|
|
1974
|
+
return Response.json({ connected: true, id: me.data?.id, name: me.data?.name });
|
|
1975
|
+
}
|
|
1976
|
+
};
|
|
1977
|
+
var metaCatalogListEndpoint = {
|
|
1978
|
+
path: "/meta-catalog/catalogs",
|
|
1979
|
+
method: "get",
|
|
1980
|
+
handler: async (req) => {
|
|
1981
|
+
if (!isAdminOrAbove3(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1982
|
+
const configId = req.query?.configId;
|
|
1983
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
1984
|
+
const config = await loadConfig3(req, configId);
|
|
1985
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
1986
|
+
const token = userToken(config);
|
|
1987
|
+
if (!token) return Response.json({ error: "Connect this site with Facebook before choosing a catalog." }, { status: 400 });
|
|
1988
|
+
const businesses = await listBusinesses(token, config.businessManagerId);
|
|
1989
|
+
if (!businesses.ok) return Response.json({ error: businesses.error }, { status: 502 });
|
|
1990
|
+
const catalogs = [];
|
|
1991
|
+
for (const business of businesses.businesses) {
|
|
1992
|
+
const owned = await graphGet(
|
|
1993
|
+
`/${business.id}/owned_product_catalogs`,
|
|
1994
|
+
{ fields: "id,name", access_token: token, limit: "50" }
|
|
1995
|
+
);
|
|
1996
|
+
if (!owned.ok) continue;
|
|
1997
|
+
for (const catalog of owned.data?.data ?? []) {
|
|
1998
|
+
catalogs.push({
|
|
1999
|
+
id: catalog.id,
|
|
2000
|
+
name: catalog.name || catalog.id,
|
|
2001
|
+
businessId: business.id,
|
|
2002
|
+
businessName: business.name || business.id
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
return Response.json({ catalogs, businesses: businesses.businesses });
|
|
2007
|
+
}
|
|
2008
|
+
};
|
|
2009
|
+
var metaCatalogCreateEndpoint = {
|
|
2010
|
+
path: "/meta-catalog/create",
|
|
2011
|
+
method: "post",
|
|
2012
|
+
handler: async (req) => {
|
|
2013
|
+
if (!isAdminOrAbove3(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2014
|
+
const body = await req.json?.();
|
|
2015
|
+
const name = body?.name?.trim();
|
|
2016
|
+
if (!body?.configId || !name) return Response.json({ error: "Missing configId or name" }, { status: 400 });
|
|
2017
|
+
const config = await loadConfig3(req, body.configId);
|
|
2018
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2019
|
+
const token = userToken(config);
|
|
2020
|
+
if (!token) return Response.json({ error: "Connect this site with Facebook before creating a catalog." }, { status: 400 });
|
|
2021
|
+
const businesses = await listBusinesses(token, body.businessId || config.businessManagerId);
|
|
2022
|
+
if (!businesses.ok) return Response.json({ error: businesses.error }, { status: 502 });
|
|
2023
|
+
const business = businesses.businesses.find((item) => item.id === body.businessId) || businesses.businesses[0];
|
|
2024
|
+
if (!business) return Response.json({ error: "This Facebook login has no Business Manager to own a catalog." }, { status: 400 });
|
|
2025
|
+
const created = await graphPost(`/${business.id}/owned_product_catalogs`, {
|
|
2026
|
+
name,
|
|
2027
|
+
access_token: token
|
|
2028
|
+
});
|
|
2029
|
+
if (!created.ok || !created.data?.id) {
|
|
2030
|
+
return Response.json({ error: created.error || "Catalog creation failed" }, { status: 502 });
|
|
2031
|
+
}
|
|
2032
|
+
await req.payload.update({
|
|
2033
|
+
collection: asCollectionSlug("meta-config"),
|
|
2034
|
+
id: body.configId,
|
|
2035
|
+
data: {
|
|
2036
|
+
catalogEnabled: true,
|
|
2037
|
+
catalogId: created.data.id,
|
|
2038
|
+
catalogSourceCollection: catalogSourceSlug(config.catalogSourceCollection),
|
|
2039
|
+
businessManagerId: business.id
|
|
2040
|
+
},
|
|
2041
|
+
overrideAccess: true,
|
|
2042
|
+
context: { skipConnectionTest: true }
|
|
2043
|
+
});
|
|
2044
|
+
return Response.json({ ok: true, catalogId: created.data.id, businessId: business.id, name });
|
|
2045
|
+
}
|
|
2046
|
+
};
|
|
2047
|
+
var metaCatalogSelectEndpoint = {
|
|
2048
|
+
path: "/meta-catalog/select",
|
|
2049
|
+
method: "post",
|
|
2050
|
+
handler: async (req) => {
|
|
2051
|
+
if (!isAdminOrAbove3(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2052
|
+
const body = await req.json?.();
|
|
2053
|
+
if (!body?.configId || !body.catalogId) {
|
|
2054
|
+
return Response.json({ error: "Missing configId or catalogId" }, { status: 400 });
|
|
2055
|
+
}
|
|
2056
|
+
const config = await loadConfig3(req, body.configId);
|
|
2057
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2058
|
+
await req.payload.update({
|
|
2059
|
+
collection: asCollectionSlug("meta-config"),
|
|
2060
|
+
id: body.configId,
|
|
2061
|
+
data: {
|
|
2062
|
+
catalogEnabled: true,
|
|
2063
|
+
catalogId: body.catalogId,
|
|
2064
|
+
catalogSourceCollection: catalogSourceSlug(config.catalogSourceCollection),
|
|
2065
|
+
...body.businessId ? { businessManagerId: body.businessId } : {}
|
|
2066
|
+
},
|
|
2067
|
+
overrideAccess: true,
|
|
2068
|
+
context: { skipConnectionTest: true }
|
|
2069
|
+
});
|
|
2070
|
+
const sourceCollection = catalogSourceSlug(config.catalogSourceCollection);
|
|
2071
|
+
return Response.json({ ok: true, catalogId: body.catalogId, sourceCollection });
|
|
2072
|
+
}
|
|
2073
|
+
};
|
|
2074
|
+
var metaCatalogSyncEndpoint = {
|
|
2075
|
+
path: "/meta-catalog/sync",
|
|
2076
|
+
method: "post",
|
|
2077
|
+
handler: async (req) => {
|
|
2078
|
+
if (!isAdminOrAbove3(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2079
|
+
const body = await req.json?.();
|
|
2080
|
+
if (!body?.configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
2081
|
+
const config = await loadConfig3(req, body.configId);
|
|
2082
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2083
|
+
if (!config.catalogEnabled) {
|
|
2084
|
+
return Response.json({ error: "Turn on Commerce Catalog and choose a catalog first." }, { status: 400 });
|
|
2085
|
+
}
|
|
2086
|
+
if (!config.catalogItemUrlTemplate) {
|
|
2087
|
+
return Response.json({ error: "Set the item page URL template (it must contain {slug}) before syncing." }, { status: 400 });
|
|
2088
|
+
}
|
|
2089
|
+
const siteId = relationId2(config.site);
|
|
2090
|
+
if (siteId == null) return Response.json({ error: "This Meta connection has no site." }, { status: 400 });
|
|
2091
|
+
const ready = await findCatalogConfig(req.payload, siteId);
|
|
2092
|
+
if (!ready) {
|
|
2093
|
+
return Response.json({ error: "Connect with Facebook and choose a catalog before syncing products." }, { status: 400 });
|
|
2094
|
+
}
|
|
2095
|
+
const result = await syncCatalogCollection(req.payload, ready, siteId);
|
|
2096
|
+
return Response.json(result);
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
2099
|
+
|
|
2100
|
+
// src/templates/body.ts
|
|
2101
|
+
import { createHash as createHash2 } from "crypto";
|
|
2102
|
+
var PLACEHOLDER = /\{\{\s*([A-Za-z_][\w.\-[\]]*)\s*\}\}/g;
|
|
2103
|
+
var MAX_BODY = 1024;
|
|
2104
|
+
var MAX_EMOJI = 6;
|
|
2105
|
+
var EMOJI = /\p{Extended_Pictographic}/gu;
|
|
2106
|
+
function nameFor(path, taken) {
|
|
2107
|
+
let base = path.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
2108
|
+
if (!/^[a-z]/.test(base)) base = `v_${base}`;
|
|
2109
|
+
let name = base;
|
|
2110
|
+
for (let n = 2; taken.has(name); n += 1) name = `${base}_${n}`;
|
|
2111
|
+
taken.add(name);
|
|
2112
|
+
return name;
|
|
2113
|
+
}
|
|
2114
|
+
var sampleFor = (path) => {
|
|
2115
|
+
const last = path.split(".").pop() ?? path;
|
|
2116
|
+
const words = last.replace(/[_\-[\]]+/g, " ").trim() || "value";
|
|
2117
|
+
return `Sample ${words}`;
|
|
2118
|
+
};
|
|
2119
|
+
function toMetaBody(message) {
|
|
2120
|
+
const normalised = message.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
2121
|
+
if (!normalised) return { ok: false, problems: ["The message is empty."] };
|
|
2122
|
+
const taken = /* @__PURE__ */ new Set();
|
|
2123
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
2124
|
+
const text2 = normalised.replace(PLACEHOLDER, (_whole, path) => {
|
|
2125
|
+
let parameter = byPath.get(path);
|
|
2126
|
+
if (!parameter) {
|
|
2127
|
+
parameter = { name: nameFor(path, taken), path, example: sampleFor(path) };
|
|
2128
|
+
byPath.set(path, parameter);
|
|
2129
|
+
}
|
|
2130
|
+
return `{{${parameter.name}}}`;
|
|
2131
|
+
});
|
|
2132
|
+
const problems = [];
|
|
2133
|
+
if (text2.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
|
|
2134
|
+
if (/^\s*\{\{[^}]+\}\}/.test(text2)) problems.push("The message cannot start with a variable. Put some words before it.");
|
|
2135
|
+
if (/\{\{[^}]+\}\}\s*$/.test(text2)) problems.push("The message cannot end with a variable. Put some words after it.");
|
|
2136
|
+
if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text2)) problems.push("Two variables cannot sit next to each other. Put words between them.");
|
|
2137
|
+
const withoutVariables = text2.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
|
|
2138
|
+
if (byPath.size > 0 && withoutVariables.length === 0) problems.push("The message cannot be only variables.");
|
|
2139
|
+
const words = text2.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
|
|
2140
|
+
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.");
|
|
2141
|
+
if ((text2.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
|
|
2142
|
+
return problems.length ? { ok: false, problems } : { ok: true, body: { text: text2, parameters: [...byPath.values()] } };
|
|
2143
|
+
}
|
|
2144
|
+
function contentHash(message) {
|
|
2145
|
+
return createHash2("sha256").update(message.replace(/\r\n/g, "\n").trim()).digest("hex").slice(0, 12);
|
|
2146
|
+
}
|
|
2147
|
+
function metaTemplateName(siteId, templateKey, hash) {
|
|
2148
|
+
const key = templateKey.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 60) || "message";
|
|
2149
|
+
return `opscms_${String(siteId).replace(/[^a-z0-9]/gi, "")}_${key}_${hash.slice(0, 8)}`;
|
|
2150
|
+
}
|
|
2151
|
+
function valueAtPath(data, path) {
|
|
2152
|
+
const parts = path.replace(/\[(\w+)\]/g, ".$1").split(".");
|
|
2153
|
+
let current = data;
|
|
2154
|
+
for (const part of parts) {
|
|
2155
|
+
if (current == null || typeof current !== "object") return "";
|
|
2156
|
+
current = current[part];
|
|
2157
|
+
}
|
|
2158
|
+
const raw = current == null ? "" : typeof current === "object" ? "" : String(current);
|
|
2159
|
+
return raw.replace(/[\r\n\t]+/g, " ").replace(/ {2,}/g, " ").trim().slice(0, 200);
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
// src/templates/graph.ts
|
|
2163
|
+
var TEMPLATE_LANGUAGE = process.env.META_TEMPLATE_LANGUAGE || "en_US";
|
|
2164
|
+
var TEMPLATE_CATEGORY = "UTILITY";
|
|
2165
|
+
function statusFromMeta(value) {
|
|
2166
|
+
switch (typeof value === "string" ? value.toUpperCase() : "") {
|
|
2167
|
+
case "APPROVED":
|
|
2168
|
+
return "approved";
|
|
2169
|
+
case "REJECTED":
|
|
2170
|
+
return "rejected";
|
|
2171
|
+
case "PAUSED":
|
|
2172
|
+
return "paused";
|
|
2173
|
+
case "DISABLED":
|
|
2174
|
+
return "disabled";
|
|
2175
|
+
default:
|
|
2176
|
+
return "pending";
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
async function submitTemplate(token, wabaId, template) {
|
|
2180
|
+
const { body } = template;
|
|
2181
|
+
const component = { type: "BODY", text: body.text };
|
|
2182
|
+
if (body.parameters.length > 0) {
|
|
2183
|
+
component.example = { body_text_named_params: body.parameters.map((p) => ({ param_name: p.name, example: p.example })) };
|
|
2184
|
+
}
|
|
2185
|
+
const result = await graphPostJson(
|
|
2186
|
+
`/${encodeURIComponent(wabaId)}/message_templates`,
|
|
2187
|
+
{
|
|
2188
|
+
name: template.name,
|
|
2189
|
+
language: template.language ?? TEMPLATE_LANGUAGE,
|
|
2190
|
+
category: template.category ?? TEMPLATE_CATEGORY,
|
|
2191
|
+
parameter_format: "NAMED",
|
|
2192
|
+
components: [component]
|
|
2193
|
+
},
|
|
2194
|
+
token
|
|
2195
|
+
);
|
|
2196
|
+
if (!result.ok) return { ok: false, error: result.error ?? "Meta refused the template." };
|
|
2197
|
+
const id = result.data?.id;
|
|
2198
|
+
if (!id) return { ok: false, error: "Meta accepted the template but did not return its id." };
|
|
2199
|
+
return { ok: true, id: String(id), status: statusFromMeta(result.data?.status), category: result.data?.category ?? null, reason: null };
|
|
2200
|
+
}
|
|
2201
|
+
async function readTemplate(token, templateId) {
|
|
2202
|
+
const result = await graphGet(`/${encodeURIComponent(templateId)}`, {
|
|
2203
|
+
fields: "status,category,rejected_reason",
|
|
2204
|
+
access_token: token
|
|
2205
|
+
});
|
|
2206
|
+
if (!result.ok) return { ok: false, error: result.error ?? "Meta could not be asked about the template." };
|
|
2207
|
+
const reason = result.data?.rejected_reason && result.data.rejected_reason !== "NONE" ? result.data.rejected_reason : null;
|
|
2208
|
+
return { ok: true, status: statusFromMeta(result.data?.status), category: result.data?.category ?? null, reason };
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
// src/templates/sync.ts
|
|
2212
|
+
var NEEDS_ATTENTION_EVENT = "meta.template.needs_attention";
|
|
2213
|
+
var PROBLEM_STATUSES = /* @__PURE__ */ new Set(["rejected", "paused", "disabled", "invalid", "failed"]);
|
|
2214
|
+
var relationId3 = (value) => {
|
|
2215
|
+
if (typeof value === "number" || typeof value === "string") return value;
|
|
2216
|
+
if (value && typeof value === "object") {
|
|
2217
|
+
const id = value.id;
|
|
2218
|
+
if (typeof id === "number" || typeof id === "string") return id;
|
|
2219
|
+
}
|
|
2220
|
+
return null;
|
|
2221
|
+
};
|
|
2222
|
+
function whatsappTemplateKeys(steps) {
|
|
2223
|
+
if (!Array.isArray(steps)) return [];
|
|
2224
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2225
|
+
for (const step of steps) {
|
|
2226
|
+
if (step?.blockType !== "send_notification") continue;
|
|
2227
|
+
const channel = step.channel;
|
|
2228
|
+
const channels = Array.isArray(channel) ? channel : typeof channel === "string" ? [channel] : [];
|
|
2229
|
+
const key = typeof step.template_key === "string" ? step.template_key.trim() : "";
|
|
2230
|
+
if (key && channels.includes("whatsapp")) keys.add(key);
|
|
2231
|
+
}
|
|
2232
|
+
return [...keys];
|
|
2233
|
+
}
|
|
2234
|
+
async function connectionForSite(payload, siteId) {
|
|
2235
|
+
const found = await payload.find({
|
|
2236
|
+
collection: asCollectionSlug("meta-config"),
|
|
2237
|
+
where: { and: [{ site: { equals: siteId } }, { isActive: { equals: true } }, { whatsappEnabled: { equals: true } }] },
|
|
2238
|
+
limit: 1,
|
|
2239
|
+
depth: 1,
|
|
2240
|
+
overrideAccess: true,
|
|
2241
|
+
context: { preventMasking: true }
|
|
2242
|
+
});
|
|
2243
|
+
const config = found.docs[0];
|
|
2244
|
+
if (!config || config.authMethod !== "oauth") return null;
|
|
2245
|
+
const wabaId = typeof config.whatsappBusinessAccountId === "string" ? config.whatsappBusinessAccountId.trim() : "";
|
|
2246
|
+
const token = tokenForCatalog(config);
|
|
2247
|
+
const site = config.site;
|
|
2248
|
+
if (!wabaId || !token || !site || typeof site !== "object" || !site.slug) return null;
|
|
2249
|
+
return {
|
|
2250
|
+
siteId,
|
|
2251
|
+
siteSlug: site.slug,
|
|
2252
|
+
siteName: site.siteIdentity?.companyName?.trim() || site.name || site.slug,
|
|
2253
|
+
organizationId: relationId3(config.organization) ?? relationId3(site.organization),
|
|
2254
|
+
wabaId,
|
|
2255
|
+
token
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
async function messageForKey(payload, siteId, key) {
|
|
2259
|
+
const found = await payload.find({
|
|
2260
|
+
collection: asCollectionSlug("notification-templates"),
|
|
2261
|
+
where: { and: [{ key: { equals: key } }, { or: [{ site: { equals: siteId } }, { is_global: { equals: true } }] }] },
|
|
2262
|
+
limit: 10,
|
|
2263
|
+
depth: 0,
|
|
2264
|
+
overrideAccess: true
|
|
2265
|
+
});
|
|
2266
|
+
const docs = found.docs;
|
|
2267
|
+
const own = docs.find((d) => relationId3(d.site) === siteId);
|
|
2268
|
+
const chosen = own ?? docs.find((d) => d.is_global);
|
|
2269
|
+
const body = chosen?.channels?.message?.body;
|
|
2270
|
+
return typeof body === "string" && body.trim() ? body : null;
|
|
2271
|
+
}
|
|
2272
|
+
var recordFilter = (siteId, templateKey, hash) => ({ and: [{ site: { equals: siteId } }, { templateKey: { equals: templateKey } }, { contentHash: { equals: hash } }] });
|
|
2273
|
+
async function alertOnce(ctx, connection, record) {
|
|
2274
|
+
if (!PROBLEM_STATUSES.has(record.status) || record.alertedStatus === record.status) return;
|
|
2275
|
+
const { payload, req, host } = ctx;
|
|
2276
|
+
if (!host) {
|
|
2277
|
+
payload.logger.warn(`[meta:templates] ${connection.siteSlug}: template "${record.templateKey}" is ${record.status}: ${record.rejectionReason ?? ""}`);
|
|
2278
|
+
return;
|
|
2279
|
+
}
|
|
2280
|
+
try {
|
|
2281
|
+
if (connection.organizationId != null) await host.ensureEventHandler(payload, NEEDS_ATTENTION_EVENT, { id: connection.siteId, organizationId: connection.organizationId });
|
|
2282
|
+
await host.emitSystemEvent(
|
|
2283
|
+
payload,
|
|
2284
|
+
NEEDS_ATTENTION_EVENT,
|
|
2285
|
+
{
|
|
2286
|
+
siteSlug: connection.siteSlug,
|
|
2287
|
+
data: {
|
|
2288
|
+
siteName: connection.siteName,
|
|
2289
|
+
templateKey: record.templateKey,
|
|
2290
|
+
status: record.status,
|
|
2291
|
+
reason: record.rejectionReason || "Meta did not give a reason.",
|
|
2292
|
+
metaName: record.metaName
|
|
2293
|
+
}
|
|
2294
|
+
},
|
|
2295
|
+
req
|
|
2296
|
+
);
|
|
2297
|
+
await payload.update({ collection: asCollectionSlug("meta-approvals"), id: record.id, data: { alertedStatus: record.status }, overrideAccess: true, depth: 0 });
|
|
2298
|
+
} catch (err) {
|
|
2299
|
+
payload.logger.error(`[meta:templates] could not raise the alert for "${record.templateKey}" on ${connection.siteSlug}: ${err}`);
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
async function submitRecord(ctx, connection, record) {
|
|
2303
|
+
const { payload } = ctx;
|
|
2304
|
+
const converted = toMetaBody(record.body);
|
|
2305
|
+
if (!converted.ok) return updateRecord(payload, record, { status: "invalid", rejectionReason: converted.problems.join(" ") });
|
|
2306
|
+
const result = await submitTemplate(connection.token, connection.wabaId, { name: record.metaName, body: converted.body, language: record.language });
|
|
2307
|
+
if (!result.ok) return updateRecord(payload, record, { status: "failed", rejectionReason: result.error, parameters: converted.body.parameters });
|
|
2308
|
+
return updateRecord(payload, record, {
|
|
2309
|
+
status: result.status,
|
|
2310
|
+
metaTemplateId: result.id,
|
|
2311
|
+
category: result.category,
|
|
2312
|
+
rejectionReason: result.reason,
|
|
2313
|
+
parameters: converted.body.parameters,
|
|
2314
|
+
wabaId: connection.wabaId,
|
|
2315
|
+
alertedStatus: null
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2318
|
+
async function updateRecord(payload, record, data) {
|
|
2319
|
+
const updated = await payload.update({ collection: asCollectionSlug("meta-approvals"), id: record.id, data, overrideAccess: true, depth: 0 });
|
|
2320
|
+
return updated;
|
|
2321
|
+
}
|
|
2322
|
+
async function syncSiteTemplates(ctx, siteId, keys) {
|
|
2323
|
+
const { payload } = ctx;
|
|
2324
|
+
if (keys.length === 0) return;
|
|
2325
|
+
const connection = await connectionForSite(payload, siteId);
|
|
2326
|
+
if (!connection) return;
|
|
2327
|
+
for (const key of new Set(keys)) {
|
|
2328
|
+
try {
|
|
2329
|
+
const message = await messageForKey(payload, siteId, key);
|
|
2330
|
+
if (message == null) {
|
|
2331
|
+
payload.logger.warn(`[meta:templates] ${connection.siteSlug}: no WhatsApp message is written for template "${key}"`);
|
|
2332
|
+
continue;
|
|
2333
|
+
}
|
|
2334
|
+
const hash = contentHash(message);
|
|
2335
|
+
const existing = await payload.find({ collection: asCollectionSlug("meta-approvals"), where: recordFilter(siteId, key, hash), limit: 1, depth: 0, overrideAccess: true });
|
|
2336
|
+
const found = existing.docs[0];
|
|
2337
|
+
if (found) {
|
|
2338
|
+
if (found.status === "failed") await alertOnce(ctx, connection, await submitRecord(ctx, connection, found));
|
|
2339
|
+
continue;
|
|
2340
|
+
}
|
|
2341
|
+
let created;
|
|
2342
|
+
try {
|
|
2343
|
+
created = await payload.create({
|
|
2344
|
+
collection: asCollectionSlug("meta-approvals"),
|
|
2345
|
+
data: {
|
|
2346
|
+
site: siteId,
|
|
2347
|
+
templateKey: key,
|
|
2348
|
+
contentHash: hash,
|
|
2349
|
+
metaName: metaTemplateName(siteId, key, hash),
|
|
2350
|
+
language: TEMPLATE_LANGUAGE,
|
|
2351
|
+
status: "pending",
|
|
2352
|
+
body: message,
|
|
2353
|
+
wabaId: connection.wabaId
|
|
2354
|
+
},
|
|
2355
|
+
overrideAccess: true,
|
|
2356
|
+
depth: 0
|
|
2357
|
+
});
|
|
2358
|
+
} catch (err) {
|
|
2359
|
+
if (/unique|duplicate/i.test(String(err))) continue;
|
|
2360
|
+
throw err;
|
|
2361
|
+
}
|
|
2362
|
+
await alertOnce(ctx, connection, await submitRecord(ctx, connection, created));
|
|
2363
|
+
} catch (err) {
|
|
2364
|
+
payload.logger.error(`[meta:templates] ${connection.siteSlug}: could not prepare template "${key}": ${err}`);
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
async function syncAllTemplatesForSite(ctx, siteId) {
|
|
2369
|
+
const found = await ctx.payload.find({ collection: asCollectionSlug("workflows"), where: { site: { equals: siteId } }, limit: 200, depth: 0, overrideAccess: true });
|
|
2370
|
+
const keys = found.docs.flatMap((workflow) => whatsappTemplateKeys(workflow.steps));
|
|
2371
|
+
await syncSiteTemplates(ctx, siteId, keys);
|
|
2372
|
+
}
|
|
2373
|
+
async function syncAfterTemplateChange(ctx, template) {
|
|
2374
|
+
const key = typeof template.key === "string" ? template.key : "";
|
|
2375
|
+
if (!key) return;
|
|
2376
|
+
const ownSite = template.is_global ? null : relationId3(template.site);
|
|
2377
|
+
const found = await ctx.payload.find({
|
|
2378
|
+
collection: asCollectionSlug("workflows"),
|
|
2379
|
+
where: { "steps.template_key": { equals: key } },
|
|
2380
|
+
limit: 200,
|
|
2381
|
+
depth: 0,
|
|
2382
|
+
overrideAccess: true
|
|
2383
|
+
});
|
|
2384
|
+
const sites = /* @__PURE__ */ new Set();
|
|
2385
|
+
for (const workflow of found.docs) {
|
|
2386
|
+
const site = relationId3(workflow.site);
|
|
2387
|
+
if (site == null || ownSite != null && site !== ownSite) continue;
|
|
2388
|
+
if (whatsappTemplateKeys(workflow.steps).includes(key)) sites.add(site);
|
|
2389
|
+
}
|
|
2390
|
+
for (const site of sites) await syncSiteTemplates(ctx, site, [key]);
|
|
2391
|
+
}
|
|
2392
|
+
async function applyStatusChange(ctx, record, change) {
|
|
2393
|
+
const siteId = relationId3(record.site);
|
|
2394
|
+
if (siteId == null) return;
|
|
2395
|
+
const data = { status: change.status };
|
|
2396
|
+
if (change.category) data.category = change.category;
|
|
2397
|
+
data.rejectionReason = change.reason ?? (change.status === "approved" ? null : record.rejectionReason);
|
|
2398
|
+
if (change.status === "approved" || change.status === "pending") data.alertedStatus = null;
|
|
2399
|
+
const updated = await updateRecord(ctx.payload, record, data);
|
|
2400
|
+
const connection = await connectionForSite(ctx.payload, siteId);
|
|
2401
|
+
if (connection) await alertOnce(ctx, connection, updated);
|
|
2402
|
+
}
|
|
2403
|
+
async function findRecordForReport(payload, report) {
|
|
2404
|
+
const clauses = [];
|
|
2405
|
+
if (report.templateId) clauses.push({ metaTemplateId: { equals: report.templateId } });
|
|
2406
|
+
if (report.templateName) clauses.push({ metaName: { equals: report.templateName } });
|
|
2407
|
+
if (clauses.length === 0) return null;
|
|
2408
|
+
const found = await payload.find({ collection: asCollectionSlug("meta-approvals"), where: { or: clauses }, limit: 1, depth: 0, overrideAccess: true });
|
|
2409
|
+
return found.docs[0] ?? null;
|
|
2410
|
+
}
|
|
2411
|
+
async function checkPendingTemplates(ctx, limit = 50) {
|
|
2412
|
+
const { payload } = ctx;
|
|
2413
|
+
const result = { checked: 0, changed: 0, retried: 0 };
|
|
2414
|
+
const found = await payload.find({
|
|
2415
|
+
collection: asCollectionSlug("meta-approvals"),
|
|
2416
|
+
where: { status: { in: ["pending", "failed"] } },
|
|
2417
|
+
limit,
|
|
2418
|
+
depth: 0,
|
|
2419
|
+
sort: "updatedAt",
|
|
2420
|
+
overrideAccess: true
|
|
2421
|
+
});
|
|
2422
|
+
for (const record of found.docs) {
|
|
2423
|
+
const siteId = relationId3(record.site);
|
|
2424
|
+
if (siteId == null) continue;
|
|
2425
|
+
try {
|
|
2426
|
+
const connection = await connectionForSite(payload, siteId);
|
|
2427
|
+
if (!connection) continue;
|
|
2428
|
+
if (record.status === "failed") {
|
|
2429
|
+
result.retried += 1;
|
|
2430
|
+
await alertOnce(ctx, connection, await submitRecord(ctx, connection, record));
|
|
2431
|
+
continue;
|
|
2432
|
+
}
|
|
2433
|
+
if (!record.metaTemplateId) continue;
|
|
2434
|
+
result.checked += 1;
|
|
2435
|
+
const read = await readTemplate(connection.token, record.metaTemplateId);
|
|
2436
|
+
if (!read.ok) {
|
|
2437
|
+
payload.logger.warn(`[meta:templates] could not read "${record.templateKey}" on ${connection.siteSlug}: ${read.error}`);
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
if (read.status !== record.status) {
|
|
2441
|
+
result.changed += 1;
|
|
2442
|
+
await applyStatusChange(ctx, record, { status: read.status, category: read.category, reason: read.reason });
|
|
2443
|
+
}
|
|
2444
|
+
} catch (err) {
|
|
2445
|
+
payload.logger.error(`[meta:templates] check of "${record.templateKey}" failed: ${err}`);
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
return result;
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
// src/endpoints/metaWhatsApp.ts
|
|
2452
|
+
function phonesFromWaba(waba, phones) {
|
|
2453
|
+
const options = [];
|
|
2454
|
+
for (const phone of phones) {
|
|
2455
|
+
if (!phone.id) continue;
|
|
2456
|
+
options.push({
|
|
2457
|
+
id: phone.id,
|
|
2458
|
+
displayPhone: phone.display_phone_number || phone.id,
|
|
2459
|
+
verifiedName: phone.verified_name || "",
|
|
2460
|
+
wabaId: waba.id,
|
|
2461
|
+
wabaName: waba.name || waba.id
|
|
2462
|
+
});
|
|
2463
|
+
}
|
|
2464
|
+
return options;
|
|
2465
|
+
}
|
|
2466
|
+
function isAdminOrAbove4(req) {
|
|
2467
|
+
const role = getUserWithRole(req.user)?.role;
|
|
2468
|
+
return role === "super-admin" || role === "admin" || role === "editor";
|
|
2469
|
+
}
|
|
2470
|
+
async function loadConfig4(req, configId) {
|
|
2471
|
+
return await req.payload.findByID({
|
|
2472
|
+
collection: asCollectionSlug("meta-config"),
|
|
2473
|
+
id: configId,
|
|
2474
|
+
depth: 0,
|
|
2475
|
+
overrideAccess: true,
|
|
2476
|
+
context: { preventMasking: true }
|
|
2477
|
+
});
|
|
2478
|
+
}
|
|
2479
|
+
async function numbersForToken(token, businessManagerId) {
|
|
2480
|
+
const businesses = await listBusinesses(token, businessManagerId);
|
|
2481
|
+
if (!businesses.ok) return businesses;
|
|
2482
|
+
const numbers = [];
|
|
2483
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2484
|
+
for (const business of businesses.businesses) {
|
|
2485
|
+
for (const edge of ["owned_whatsapp_business_accounts", "client_whatsapp_business_accounts"]) {
|
|
2486
|
+
const accounts = await graphGet(
|
|
2487
|
+
`/${business.id}/${edge}`,
|
|
2488
|
+
{ fields: "id,name", access_token: token, limit: "25" }
|
|
2489
|
+
);
|
|
2490
|
+
if (!accounts.ok) continue;
|
|
2491
|
+
for (const waba of accounts.data?.data ?? []) {
|
|
2492
|
+
const phones = await graphGet(`/${waba.id}/phone_numbers`, {
|
|
2493
|
+
fields: "id,display_phone_number,verified_name",
|
|
2494
|
+
access_token: token,
|
|
2495
|
+
limit: "25"
|
|
2496
|
+
});
|
|
2497
|
+
if (!phones.ok) continue;
|
|
2498
|
+
for (const option of phonesFromWaba(waba, phones.data?.data ?? [])) {
|
|
2499
|
+
if (seen.has(option.id)) continue;
|
|
2500
|
+
seen.add(option.id);
|
|
2501
|
+
numbers.push(option);
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
return { ok: true, numbers };
|
|
2507
|
+
}
|
|
2508
|
+
var metaWhatsAppNumbersEndpoint = {
|
|
2509
|
+
path: "/meta-whatsapp/numbers",
|
|
2510
|
+
method: "get",
|
|
2511
|
+
handler: async (req) => {
|
|
2512
|
+
if (!isAdminOrAbove4(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2513
|
+
const configId = req.query?.configId;
|
|
2514
|
+
if (!configId) return Response.json({ error: "Missing configId" }, { status: 400 });
|
|
2515
|
+
const config = await loadConfig4(req, configId);
|
|
2516
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2517
|
+
const token = tokenForCatalog(config);
|
|
2518
|
+
if (!token) return Response.json({ error: "Connect this site with Facebook before choosing a WhatsApp number." }, { status: 400 });
|
|
2519
|
+
const listed = await numbersForToken(token, config.businessManagerId);
|
|
2520
|
+
if (!listed.ok) return Response.json({ error: listed.error }, { status: 502 });
|
|
2521
|
+
return Response.json({ numbers: listed.numbers });
|
|
2522
|
+
}
|
|
2523
|
+
};
|
|
2524
|
+
var createMetaWhatsAppSelectEndpoint = (host) => ({
|
|
2525
|
+
path: "/meta-whatsapp/select",
|
|
2526
|
+
method: "post",
|
|
2527
|
+
handler: async (req) => {
|
|
2528
|
+
if (!isAdminOrAbove4(req)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2529
|
+
const body = await req.json?.();
|
|
2530
|
+
if (!body?.configId || !body.phoneNumberId) {
|
|
2531
|
+
return Response.json({ error: "Missing configId or phoneNumberId" }, { status: 400 });
|
|
2532
|
+
}
|
|
2533
|
+
const config = await loadConfig4(req, body.configId);
|
|
2534
|
+
if (!callerOwnsConfigSite(req, config)) return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
2535
|
+
const token = tokenForCatalog(config);
|
|
2536
|
+
if (!token) return Response.json({ error: "Connect this site with Facebook first." }, { status: 400 });
|
|
2537
|
+
const listed = await numbersForToken(token, config.businessManagerId);
|
|
2538
|
+
if (!listed.ok) return Response.json({ error: listed.error }, { status: 502 });
|
|
2539
|
+
const chosen = listed.numbers.find((number) => number.id === body.phoneNumberId);
|
|
2540
|
+
if (!chosen) {
|
|
2541
|
+
return Response.json({ error: "That WhatsApp number is not on this Facebook login." }, { status: 404 });
|
|
2542
|
+
}
|
|
2543
|
+
await req.payload.update({
|
|
2544
|
+
collection: asCollectionSlug("meta-config"),
|
|
2545
|
+
id: body.configId,
|
|
2546
|
+
data: {
|
|
2547
|
+
whatsappEnabled: true,
|
|
2548
|
+
whatsappPhoneNumberId: chosen.id,
|
|
2549
|
+
whatsappBusinessAccountId: chosen.wabaId
|
|
2550
|
+
},
|
|
2551
|
+
overrideAccess: true,
|
|
2552
|
+
context: { skipConnectionTest: true }
|
|
2553
|
+
});
|
|
2554
|
+
const subscription = await subscribeWabaToApp(token, chosen.wabaId);
|
|
2555
|
+
if (!subscription.ok) req.payload.logger.warn(`[meta:whatsapp] could not subscribe ${chosen.wabaId} to the app: ${subscription.error}`);
|
|
2556
|
+
const siteId = config.site && typeof config.site === "object" ? config.site.id : config.site;
|
|
2557
|
+
if (siteId != null) {
|
|
2558
|
+
setTimeout(() => {
|
|
2559
|
+
syncAllTemplatesForSite({ payload: req.payload, req, host }, siteId).catch((err) => req.payload.logger.error(`[meta:templates] submitting a new site's templates failed: ${err}`));
|
|
2560
|
+
}, 2e3);
|
|
2561
|
+
}
|
|
2562
|
+
return Response.json({
|
|
2563
|
+
ok: true,
|
|
2564
|
+
phoneNumberId: chosen.id,
|
|
2565
|
+
displayPhone: chosen.displayPhone,
|
|
2566
|
+
wabaId: chosen.wabaId,
|
|
2567
|
+
webhookSubscribed: subscription.ok,
|
|
2568
|
+
...subscription.ok ? {} : { webhookWarning: subscription.error }
|
|
2569
|
+
});
|
|
2570
|
+
}
|
|
2571
|
+
});
|
|
2572
|
+
var metaWhatsAppSelectEndpoint = createMetaWhatsAppSelectEndpoint();
|
|
2573
|
+
|
|
2574
|
+
// src/whatsapp/templateErrors.ts
|
|
2575
|
+
function explainTemplateSendError(body) {
|
|
2576
|
+
const aboutTemplate = /template/i.test(body) || /132001|132015|132016/.test(body);
|
|
2577
|
+
if (!aboutTemplate) return null;
|
|
2578
|
+
const waiting = /not approved|pending review|is pending|\bpending\b|does not exist|doesn't exist|not exist|paused|disabled|132001|132015|132016/i.test(body);
|
|
2579
|
+
if (waiting) {
|
|
2580
|
+
return {
|
|
2581
|
+
retryable: true,
|
|
2582
|
+
error: "This message's template is not approved by Meta yet. It will send after it is approved."
|
|
2583
|
+
};
|
|
2584
|
+
}
|
|
2585
|
+
return {
|
|
2586
|
+
retryable: false,
|
|
2587
|
+
error: "Meta could not send this message from its template."
|
|
2588
|
+
};
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2591
|
+
// src/channels/phone.ts
|
|
2592
|
+
function toE164Digits(phone, defaultCountryCode) {
|
|
2593
|
+
const trimmed = phone.trim();
|
|
2594
|
+
if (trimmed.startsWith("+")) return trimmed.replace(/\D/g, "");
|
|
2595
|
+
const digits = trimmed.replace(/\D/g, "");
|
|
2596
|
+
if (!digits) return "";
|
|
2597
|
+
if (digits.startsWith("00")) return digits.slice(2);
|
|
2598
|
+
const cc = (defaultCountryCode ?? "").replace(/\D/g, "");
|
|
2599
|
+
if (!cc) return digits;
|
|
2600
|
+
if (digits.startsWith(cc) && digits.length > cc.length + 6) return digits;
|
|
2601
|
+
if (digits.startsWith("0")) return cc + digits.slice(1);
|
|
2602
|
+
if (digits.length <= 11) return cc + digits;
|
|
2603
|
+
return digits;
|
|
2604
|
+
}
|
|
2605
|
+
|
|
2606
|
+
// src/channels/whatsapp.ts
|
|
2607
|
+
var WHATSAPP_TIMEOUT_MS = 1e4;
|
|
2608
|
+
async function sendViaMetaCloud(to, text2, cfg, log, template) {
|
|
2609
|
+
const payload = template ? {
|
|
2610
|
+
messaging_product: "whatsapp",
|
|
2611
|
+
to,
|
|
2612
|
+
type: "template",
|
|
2613
|
+
template: {
|
|
2614
|
+
name: template.name,
|
|
2615
|
+
language: { code: template.languageCode },
|
|
2616
|
+
components: [
|
|
2617
|
+
{
|
|
2618
|
+
type: "body",
|
|
2619
|
+
parameters: template.bodyParameters.map((value) => ({ type: "text", ...value.name ? { parameter_name: value.name } : {}, text: value.text }))
|
|
2620
|
+
}
|
|
2621
|
+
]
|
|
2622
|
+
}
|
|
2623
|
+
} : {
|
|
2624
|
+
messaging_product: "whatsapp",
|
|
2625
|
+
to,
|
|
2626
|
+
type: "text",
|
|
2627
|
+
text: { body: text2 }
|
|
2628
|
+
};
|
|
2629
|
+
try {
|
|
2630
|
+
const res = await fetch(
|
|
2631
|
+
`https://graph.facebook.com/v20.0/${cfg.phoneNumberId}/messages`,
|
|
2632
|
+
{
|
|
2633
|
+
method: "POST",
|
|
2634
|
+
headers: {
|
|
2635
|
+
"Content-Type": "application/json",
|
|
2636
|
+
Authorization: `Bearer ${cfg.accessToken}`
|
|
2637
|
+
},
|
|
2638
|
+
body: JSON.stringify(payload),
|
|
2639
|
+
signal: AbortSignal.timeout(WHATSAPP_TIMEOUT_MS)
|
|
2640
|
+
}
|
|
2641
|
+
);
|
|
2642
|
+
if (!res.ok) {
|
|
2643
|
+
const body = await res.text();
|
|
2644
|
+
const explained = explainTemplateSendError(body);
|
|
2645
|
+
const retryable = explained?.retryable ?? (res.status >= 500 || res.status === 429);
|
|
2646
|
+
log?.[retryable ? "warn" : "error"](
|
|
2647
|
+
`[meta:whatsapp] send ${retryable ? "deferred" : "failed"} (${res.status}): ${body}`
|
|
2648
|
+
);
|
|
2649
|
+
return {
|
|
2650
|
+
ok: false,
|
|
2651
|
+
retryable,
|
|
2652
|
+
error: explained?.error ?? `Meta Cloud responded ${res.status}: ${body.slice(0, 200)}`
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
return { ok: true };
|
|
2656
|
+
} catch (err) {
|
|
2657
|
+
log?.warn(`[meta:whatsapp] network error (will retry): ${err}`);
|
|
2658
|
+
return { ok: false, retryable: true, error: `Meta Cloud unreachable: ${err instanceof Error ? err.message : String(err)}` };
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
async function siteIdForSlug(payload, slug) {
|
|
2662
|
+
try {
|
|
2663
|
+
const found = await payload.find({ collection: "sites", where: { slug: { equals: slug } }, limit: 1, depth: 0, overrideAccess: true, select: { id: true } });
|
|
2664
|
+
const id = found.docs[0]?.id;
|
|
2665
|
+
return typeof id === "number" ? id : void 0;
|
|
2666
|
+
} catch {
|
|
2667
|
+
return void 0;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
async function officialNumberFor(payload, siteSlug) {
|
|
2671
|
+
const siteId = await siteIdForSlug(payload, siteSlug);
|
|
2672
|
+
if (siteId == null) return null;
|
|
2673
|
+
try {
|
|
2674
|
+
const found = await payload.find({
|
|
2675
|
+
collection: "meta-config",
|
|
2676
|
+
where: {
|
|
2677
|
+
and: [{ site: { equals: siteId } }, { isActive: { equals: true } }, { whatsappEnabled: { equals: true } }]
|
|
2678
|
+
},
|
|
2679
|
+
limit: 1,
|
|
2680
|
+
depth: 0,
|
|
2681
|
+
overrideAccess: true,
|
|
2682
|
+
context: { preventMasking: true }
|
|
2683
|
+
});
|
|
2684
|
+
const cfg = found.docs[0];
|
|
2685
|
+
if (cfg?.authMethod !== "oauth") return null;
|
|
2686
|
+
const phoneNumberId = typeof cfg?.whatsappPhoneNumberId === "string" ? cfg.whatsappPhoneNumberId.trim() : "";
|
|
2687
|
+
const raw = cfg?.oauthUserAccessToken || cfg?.accessToken;
|
|
2688
|
+
if (!phoneNumberId || typeof raw !== "string" || !raw || raw.includes("\u2022")) return null;
|
|
2689
|
+
const accessToken = decryptCredential(raw);
|
|
2690
|
+
if (!accessToken || accessToken.startsWith("enc:") || accessToken.includes("\u2022")) return null;
|
|
2691
|
+
return { phoneNumberId, accessToken, siteId };
|
|
2692
|
+
} catch (err) {
|
|
2693
|
+
payload.logger.warn(`[meta:whatsapp] official WhatsApp lookup failed: ${err}`);
|
|
2694
|
+
return null;
|
|
2695
|
+
}
|
|
2696
|
+
}
|
|
2697
|
+
var metaWhatsAppChannel = {
|
|
2698
|
+
id: "meta-whatsapp",
|
|
2699
|
+
channel: "whatsapp",
|
|
2700
|
+
priority: 10,
|
|
2701
|
+
// Nothing set in the settings: a gateway in the environment is tried after the host's other WhatsApp service.
|
|
2702
|
+
environmentPriority: 20,
|
|
2703
|
+
// The on/off switch of the host's WhatsApp tab; a host without one leaves the channel on.
|
|
2704
|
+
isEnabled: (settings) => settings?.whatsapp_enabled !== false,
|
|
2705
|
+
async resolve({ payload, siteSlug }) {
|
|
2706
|
+
return siteSlug ? officialNumberFor(payload, siteSlug) : null;
|
|
2707
|
+
},
|
|
2708
|
+
resolveFromEnvironment() {
|
|
2709
|
+
const phoneNumberId = process.env.META_PHONE_NUMBER_ID;
|
|
2710
|
+
const accessToken = process.env.META_ACCESS_TOKEN;
|
|
2711
|
+
return phoneNumberId && accessToken ? { phoneNumberId, accessToken } : null;
|
|
2712
|
+
},
|
|
2713
|
+
async send({ payload, config, to, message, template, templateKey, variables }) {
|
|
2714
|
+
const normalised = toE164Digits(to, process.env.WHATSAPP_DEFAULT_COUNTRY_CODE ?? "234");
|
|
2715
|
+
if (!normalised) {
|
|
2716
|
+
payload.logger.warn("[meta:whatsapp] recipient has no usable digits \u2014 message not sent");
|
|
2717
|
+
return { success: false, error: "recipient has no usable digits" };
|
|
2718
|
+
}
|
|
2719
|
+
let reference = template ?? null;
|
|
2720
|
+
if (!reference && templateKey && config.siteId != null) {
|
|
2721
|
+
const decision = await approvedTemplateFor(payload, config.siteId, templateKey, variables);
|
|
2722
|
+
if (!decision.ok) return { success: false, deferred: decision.wait, error: decision.error };
|
|
2723
|
+
reference = decision.reference;
|
|
2724
|
+
}
|
|
2725
|
+
const sent = await sendViaMetaCloud(normalised, message, config, payload.logger, reference);
|
|
2726
|
+
if (sent.ok) return { success: true };
|
|
2727
|
+
return { success: false, deferred: sent.retryable === true, error: sent.error ?? "WhatsApp send failed" };
|
|
2728
|
+
}
|
|
2729
|
+
};
|
|
2730
|
+
var WORDS = {
|
|
2731
|
+
rejected: "Meta rejected it",
|
|
2732
|
+
paused: "Meta paused it",
|
|
2733
|
+
disabled: "Meta disabled it",
|
|
2734
|
+
invalid: "its wording does not follow Meta's rules",
|
|
2735
|
+
failed: "it could not be submitted to Meta"
|
|
2736
|
+
};
|
|
2737
|
+
async function approvedTemplateFor(payload, siteId, templateKey, variables) {
|
|
2738
|
+
const found = await payload.find({
|
|
2739
|
+
collection: asCollectionSlug("meta-approvals"),
|
|
2740
|
+
where: { and: [{ site: { equals: siteId } }, { templateKey: { equals: templateKey } }] },
|
|
2741
|
+
sort: "-createdAt",
|
|
2742
|
+
limit: 1,
|
|
2743
|
+
depth: 0,
|
|
2744
|
+
overrideAccess: true
|
|
2745
|
+
});
|
|
2746
|
+
const record = found.docs[0];
|
|
2747
|
+
if (!record) {
|
|
2748
|
+
return { ok: false, wait: false, error: `WhatsApp message "${templateKey}" has not been submitted to Meta yet. Save the workflow that sends it again once this site's WhatsApp number is connected.` };
|
|
2749
|
+
}
|
|
2750
|
+
if (record.status === "pending") {
|
|
2751
|
+
return { ok: false, wait: true, error: `WhatsApp message "${templateKey}" is still with Meta for review. It will be sent once it is approved.` };
|
|
2752
|
+
}
|
|
2753
|
+
if (record.status !== "approved") {
|
|
2754
|
+
const why = record.rejectionReason ? ` (${record.rejectionReason})` : "";
|
|
2755
|
+
return { ok: false, wait: false, error: `WhatsApp message "${templateKey}" cannot be sent: ${WORDS[record.status] ?? record.status}${why}. Change its wording to submit it again.` };
|
|
2756
|
+
}
|
|
2757
|
+
const parameters = (record.parameters ?? []).map((parameter) => ({ name: parameter.name, text: valueAtPath(variables, parameter.path) || "-" }));
|
|
2758
|
+
return { ok: true, reference: { name: record.metaName, languageCode: record.language, bodyParameters: parameters } };
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
// src/webhook/signature.ts
|
|
2762
|
+
import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
2763
|
+
function handshakeChallenge(query, verifyToken) {
|
|
2764
|
+
if (!verifyToken) return null;
|
|
2765
|
+
const mode = query?.["hub.mode"];
|
|
2766
|
+
const token = query?.["hub.verify_token"];
|
|
2767
|
+
const challenge = query?.["hub.challenge"];
|
|
2768
|
+
if (mode !== "subscribe" || typeof token !== "string" || typeof challenge !== "string") return null;
|
|
2769
|
+
const a = Buffer.from(token);
|
|
2770
|
+
const b = Buffer.from(verifyToken);
|
|
2771
|
+
if (a.length !== b.length || !timingSafeEqual3(a, b)) return null;
|
|
2772
|
+
return challenge;
|
|
2773
|
+
}
|
|
2774
|
+
function signatureMatches(rawBody, header, appSecret) {
|
|
2775
|
+
if (!header || !appSecret) return false;
|
|
2776
|
+
const match = /^sha256=([0-9a-f]{64})$/i.exec(header.trim());
|
|
2777
|
+
if (!match) return false;
|
|
2778
|
+
const expected = createHmac2("sha256", appSecret).update(rawBody).digest();
|
|
2779
|
+
const provided = Buffer.from(match[1], "hex");
|
|
2780
|
+
return provided.length === expected.length && timingSafeEqual3(provided, expected);
|
|
2781
|
+
}
|
|
2782
|
+
|
|
2783
|
+
// src/webhook/templateEvents.ts
|
|
2784
|
+
import { createHash as createHash3 } from "crypto";
|
|
2785
|
+
var TEMPLATE_EVENT_BY_FIELD = {
|
|
2786
|
+
message_template_status_update: "meta.template.status_changed",
|
|
2787
|
+
template_category_update: "meta.template.category_changed",
|
|
2788
|
+
template_correct_category_detection: "meta.template.category_changed",
|
|
2789
|
+
message_template_quality_update: "meta.template.quality_changed",
|
|
2790
|
+
message_template_components_update: "meta.template.components_changed"
|
|
2791
|
+
};
|
|
2792
|
+
var text = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
|
|
2793
|
+
function templateEventsFrom(body) {
|
|
2794
|
+
const delivery = body;
|
|
2795
|
+
if (!delivery || delivery.object !== "whatsapp_business_account" || !Array.isArray(delivery.entry)) return [];
|
|
2796
|
+
const events = [];
|
|
2797
|
+
for (const entry of delivery.entry) {
|
|
2798
|
+
const wabaId = text(entry?.id);
|
|
2799
|
+
if (!wabaId || !Array.isArray(entry.changes)) continue;
|
|
2800
|
+
for (const change of entry.changes) {
|
|
2801
|
+
const field = typeof change?.field === "string" ? change.field : "";
|
|
2802
|
+
const eventName = TEMPLATE_EVENT_BY_FIELD[field];
|
|
2803
|
+
if (!eventName) continue;
|
|
2804
|
+
const value = change.value ?? {};
|
|
2805
|
+
const templateId = text(value.message_template_id);
|
|
2806
|
+
const status = text(value.event) ?? text(value.new_category) ?? text(value.new_quality_score) ?? text(value.correct_category);
|
|
2807
|
+
const reason = text(value.reason) ?? text(value.disable_info?.disable_date);
|
|
2808
|
+
const eventId = createHash3("sha256").update(JSON.stringify([wabaId, field, entry.time ?? null, templateId, status, reason])).digest("hex").slice(0, 32);
|
|
2809
|
+
events.push({
|
|
2810
|
+
eventName,
|
|
2811
|
+
wabaId,
|
|
2812
|
+
data: {
|
|
2813
|
+
field,
|
|
2814
|
+
eventId,
|
|
2815
|
+
wabaId,
|
|
2816
|
+
templateId,
|
|
2817
|
+
templateName: text(value.message_template_name),
|
|
2818
|
+
language: text(value.message_template_language),
|
|
2819
|
+
status,
|
|
2820
|
+
reason
|
|
2821
|
+
}
|
|
2822
|
+
});
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
return events;
|
|
2826
|
+
}
|
|
2827
|
+
|
|
2828
|
+
// src/endpoints/metaWebhook.ts
|
|
2829
|
+
function createMetaWebhookEndpoints(host) {
|
|
2830
|
+
const handshake = {
|
|
2831
|
+
path: "/meta-webhook",
|
|
2832
|
+
method: "get",
|
|
2833
|
+
handler: async (req) => {
|
|
2834
|
+
const challenge = handshakeChallenge(req.query, process.env.META_WEBHOOK_VERIFY_TOKEN);
|
|
2835
|
+
if (challenge === null) return Response.json({ error: "Verification failed" }, { status: 403 });
|
|
2836
|
+
return new Response(challenge, { status: 200, headers: { "content-type": "text/plain" } });
|
|
2837
|
+
}
|
|
2838
|
+
};
|
|
2839
|
+
const receive = {
|
|
2840
|
+
path: "/meta-webhook",
|
|
2841
|
+
method: "post",
|
|
2842
|
+
handler: async (req) => {
|
|
2843
|
+
const credentials = getMetaAppCredentials();
|
|
2844
|
+
if (!credentials) return Response.json({ error: "The Meta app is not configured on this server" }, { status: 503 });
|
|
2845
|
+
const rawBody = await req.text?.() ?? "";
|
|
2846
|
+
if (!signatureMatches(rawBody, req.headers?.get("x-hub-signature-256"), credentials.appSecret)) {
|
|
2847
|
+
return Response.json({ error: "Invalid signature" }, { status: 401 });
|
|
2848
|
+
}
|
|
2849
|
+
let body;
|
|
2850
|
+
try {
|
|
2851
|
+
body = JSON.parse(rawBody);
|
|
2852
|
+
} catch {
|
|
2853
|
+
return Response.json({ error: "Invalid body" }, { status: 400 });
|
|
2854
|
+
}
|
|
2855
|
+
const events = templateEventsFrom(body);
|
|
2856
|
+
for (const event of events) {
|
|
2857
|
+
try {
|
|
2858
|
+
const record = await findRecordForReport(req.payload, { templateId: event.data.templateId, templateName: event.data.templateName });
|
|
2859
|
+
if (!record) continue;
|
|
2860
|
+
if (event.eventName === "meta.template.status_changed") {
|
|
2861
|
+
await applyStatusChange({ payload: req.payload, req, host }, record, { status: statusFromMeta(event.data.status), reason: event.data.reason });
|
|
2862
|
+
} else if (event.eventName === "meta.template.category_changed" && event.data.status) {
|
|
2863
|
+
await applyStatusChange({ payload: req.payload, req, host }, record, { status: record.status, category: event.data.status });
|
|
2864
|
+
}
|
|
2865
|
+
} catch (err) {
|
|
2866
|
+
req.payload.logger.error(`[meta:webhook] could not record ${event.eventName}: ${err}`);
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
if (events.length === 0 || !host) return Response.json({ ok: true, handled: 0 });
|
|
2870
|
+
let failed = 0;
|
|
2871
|
+
let handled = 0;
|
|
2872
|
+
for (const event of events) {
|
|
2873
|
+
const configs = await req.payload.find({
|
|
2874
|
+
collection: asCollectionSlug("meta-config"),
|
|
2875
|
+
where: { and: [{ whatsappBusinessAccountId: { equals: event.wabaId } }, { isActive: { equals: true } }] },
|
|
2876
|
+
limit: 50,
|
|
2877
|
+
depth: 1,
|
|
2878
|
+
overrideAccess: true
|
|
2879
|
+
});
|
|
2880
|
+
for (const config of configs.docs) {
|
|
2881
|
+
const slug = typeof config.site === "object" && config.site ? config.site.slug : void 0;
|
|
2882
|
+
if (!slug) continue;
|
|
2883
|
+
try {
|
|
2884
|
+
await host.emitSystemEvent(req.payload, event.eventName, { siteSlug: slug, data: event.data }, req);
|
|
2885
|
+
handled += 1;
|
|
2886
|
+
} catch (err) {
|
|
2887
|
+
failed += 1;
|
|
2888
|
+
req.payload.logger.error(`[meta:webhook] could not hand ${event.eventName} to the host for ${slug}: ${err}`);
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
if (failed > 0) return Response.json({ error: "Not every event could be handled" }, { status: 500 });
|
|
2893
|
+
return Response.json({ ok: true, handled });
|
|
2894
|
+
}
|
|
2895
|
+
};
|
|
2896
|
+
return [handshake, receive];
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
// src/login/facebook.ts
|
|
2900
|
+
import { createHmac as createHmac3 } from "crypto";
|
|
2901
|
+
var LOGIN_SCOPE = "email,public_profile";
|
|
2902
|
+
async function exchangeLoginCode(code, app, redirectUri) {
|
|
2903
|
+
const result = await graphGet("/oauth/access_token", {
|
|
2904
|
+
client_id: app.appId,
|
|
2905
|
+
client_secret: app.appSecret,
|
|
2906
|
+
redirect_uri: redirectUri,
|
|
2907
|
+
code
|
|
2908
|
+
});
|
|
2909
|
+
if (!result.ok || !result.data?.access_token) return { ok: false, error: result.error ?? "Facebook did not accept the sign-in." };
|
|
2910
|
+
return { ok: true, accessToken: result.data.access_token };
|
|
2911
|
+
}
|
|
2912
|
+
async function fetchLoginProfile(accessToken, appSecret) {
|
|
2913
|
+
const proof = createHmac3("sha256", appSecret).update(accessToken).digest("hex");
|
|
2914
|
+
const result = await graphGet("/me", {
|
|
2915
|
+
fields: "id,name,email",
|
|
2916
|
+
access_token: accessToken,
|
|
2917
|
+
appsecret_proof: proof
|
|
2918
|
+
});
|
|
2919
|
+
if (!result.ok || !result.data?.id) return { ok: false, error: result.error ?? "Facebook did not say who this is." };
|
|
2920
|
+
const profile = { id: String(result.data.id) };
|
|
2921
|
+
if (typeof result.data.name === "string") profile.name = result.data.name;
|
|
2922
|
+
if (typeof result.data.email === "string" && result.data.email.trim()) profile.email = result.data.email.trim().toLowerCase();
|
|
2923
|
+
return { ok: true, profile };
|
|
2924
|
+
}
|
|
2925
|
+
|
|
2926
|
+
// src/login/resolveUser.ts
|
|
2927
|
+
var refusal = (user) => {
|
|
2928
|
+
if (user.role === "super-admin") return "not_allowed";
|
|
2929
|
+
if (user.twoFactorEnabled === true) return "two_factor";
|
|
2930
|
+
return null;
|
|
2931
|
+
};
|
|
2932
|
+
async function resolveLoginUser(payload, usersSlug, profile) {
|
|
2933
|
+
const collection = usersSlug;
|
|
2934
|
+
const find = async (where) => (await payload.find({
|
|
2935
|
+
collection,
|
|
2936
|
+
where,
|
|
2937
|
+
limit: 1,
|
|
2938
|
+
depth: 0,
|
|
2939
|
+
overrideAccess: true,
|
|
2940
|
+
// The session list is hidden from ordinary reads; a sign-in needs it to add this one.
|
|
2941
|
+
showHiddenFields: true
|
|
2942
|
+
})).docs[0];
|
|
2943
|
+
try {
|
|
2944
|
+
const linked = await find({ facebookId: { equals: profile.id } });
|
|
2945
|
+
if (linked) {
|
|
2946
|
+
if (linked.suspended) return { ok: false, code: "suspended" };
|
|
2947
|
+
const refused2 = refusal(linked);
|
|
2948
|
+
return refused2 ? { ok: false, code: refused2 } : { ok: true, user: linked, linked: false };
|
|
2949
|
+
}
|
|
2950
|
+
if (!profile.email) return { ok: false, code: "no_email" };
|
|
2951
|
+
const byEmail = await find({ email: { equals: profile.email.toLowerCase() } });
|
|
2952
|
+
if (!byEmail) return { ok: false, code: "no_account" };
|
|
2953
|
+
if (byEmail.suspended) return { ok: false, code: "suspended" };
|
|
2954
|
+
const refused = refusal(byEmail);
|
|
2955
|
+
if (refused) return { ok: false, code: refused };
|
|
2956
|
+
if (typeof byEmail.facebookId === "string" && byEmail.facebookId && byEmail.facebookId !== profile.id) return { ok: false, code: "conflict" };
|
|
2957
|
+
await payload.update({
|
|
2958
|
+
collection,
|
|
2959
|
+
id: byEmail.id,
|
|
2960
|
+
data: { facebookId: profile.id },
|
|
2961
|
+
overrideAccess: true,
|
|
2962
|
+
// Joining an account is not an ownership change.
|
|
2963
|
+
context: { skipOwnership: true }
|
|
2964
|
+
});
|
|
2965
|
+
return { ok: true, user: { ...byEmail, facebookId: profile.id }, linked: true };
|
|
2966
|
+
} catch (error) {
|
|
2967
|
+
payload.logger.error({ err: error }, "[meta-login] Could not look up the account");
|
|
2968
|
+
return { ok: false, code: "failed" };
|
|
2969
|
+
}
|
|
2970
|
+
}
|
|
2971
|
+
|
|
2972
|
+
// src/login/session.ts
|
|
2973
|
+
import { getFieldsToSign, jwtSign } from "payload";
|
|
2974
|
+
import { addSessionToUser, generatePayloadCookie } from "payload/shared";
|
|
2975
|
+
async function startPlatformSession(req, usersSlug, user, secure) {
|
|
2976
|
+
const { payload } = req;
|
|
2977
|
+
const collection = payload.collections[usersSlug];
|
|
2978
|
+
if (!collection) throw new Error(`There is no "${usersSlug}" collection to sign in to.`);
|
|
2979
|
+
const config = collection.config;
|
|
2980
|
+
if (!config.auth) throw new Error(`"${usersSlug}" is not a collection people sign in to.`);
|
|
2981
|
+
const account = { ...user };
|
|
2982
|
+
for (const hook of config.hooks?.beforeLogin ?? []) {
|
|
2983
|
+
await hook({ collection: config, context: req.context, req, user: account });
|
|
2984
|
+
}
|
|
2985
|
+
const { sid } = await addSessionToUser({ collectionConfig: config, payload, req, user: account });
|
|
2986
|
+
const fieldsToSign = getFieldsToSign({ collectionConfig: config, email: account.email, user: account, ...sid ? { sid } : {} });
|
|
2987
|
+
const { token } = await jwtSign({ fieldsToSign, secret: payload.secret, tokenExpiration: config.auth.tokenExpiration ?? 7200 });
|
|
2988
|
+
req.user = { ...account, collection: usersSlug };
|
|
2989
|
+
for (const hook of config.hooks?.afterLogin ?? []) {
|
|
2990
|
+
await hook({ collection: config, context: req.context, req, token, user: account });
|
|
2991
|
+
}
|
|
2992
|
+
const cookie = generatePayloadCookie({ collectionAuthConfig: config.auth, cookiePrefix: payload.config.cookiePrefix, token, returnCookieAsObject: false });
|
|
2993
|
+
return { token, cookie: secure && !/;\s*Secure/i.test(cookie) ? `${cookie}; Secure` : cookie };
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
// src/login/state.ts
|
|
2997
|
+
import { randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
2998
|
+
var STATE_COOKIE = "opscms-fb-state";
|
|
2999
|
+
var STATE_MAX_AGE_SECONDS = 600;
|
|
3000
|
+
var COOKIE_PATH = "/api/meta-login";
|
|
3001
|
+
var newState = () => randomBytes2(24).toString("hex");
|
|
3002
|
+
function stateCookie(value, secure) {
|
|
3003
|
+
return `${STATE_COOKIE}=${value}; Path=${COOKIE_PATH}; Max-Age=${STATE_MAX_AGE_SECONDS}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`;
|
|
3004
|
+
}
|
|
3005
|
+
function clearedStateCookie(secure) {
|
|
3006
|
+
return `${STATE_COOKIE}=; Path=${COOKIE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`;
|
|
3007
|
+
}
|
|
3008
|
+
function readCookie(header, name) {
|
|
3009
|
+
if (!header) return null;
|
|
3010
|
+
for (const part of header.split(";")) {
|
|
3011
|
+
const index = part.indexOf("=");
|
|
3012
|
+
if (index < 0) continue;
|
|
3013
|
+
if (part.slice(0, index).trim() === name) return part.slice(index + 1).trim();
|
|
3014
|
+
}
|
|
3015
|
+
return null;
|
|
3016
|
+
}
|
|
3017
|
+
function statesMatch(fromFacebook, fromCookie) {
|
|
3018
|
+
if (!fromFacebook || !fromCookie) return false;
|
|
3019
|
+
const a = Buffer.from(fromFacebook);
|
|
3020
|
+
const b = Buffer.from(fromCookie);
|
|
3021
|
+
return a.length === b.length && timingSafeEqual4(a, b);
|
|
3022
|
+
}
|
|
3023
|
+
|
|
3024
|
+
// src/endpoints/metaLogin.ts
|
|
3025
|
+
var serverUrl3 = () => (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
|
|
3026
|
+
var isSecure = () => serverUrl3().startsWith("https://");
|
|
3027
|
+
var callbackUri = () => `${serverUrl3()}/api/meta-login/callback`;
|
|
3028
|
+
var SIGN_IN_ATTEMPTS = { max: 30, windowMs: 15 * 6e4 };
|
|
3029
|
+
function backToLogin(code) {
|
|
3030
|
+
const headers = new Headers({ Location: `${serverUrl3()}/admin/login?fb_error=${code}` });
|
|
3031
|
+
headers.append("Set-Cookie", clearedStateCookie(isSecure()));
|
|
3032
|
+
return new Response(null, { status: 302, headers });
|
|
3033
|
+
}
|
|
3034
|
+
function createMetaLoginEndpoints(host) {
|
|
3035
|
+
const throttled = async (req) => {
|
|
3036
|
+
if (!host?.rateLimit) return false;
|
|
3037
|
+
const verdict = await host.rateLimit.check(`meta-login:${host.rateLimit.clientIp(req)}`, SIGN_IN_ATTEMPTS.max, SIGN_IN_ATTEMPTS.windowMs);
|
|
3038
|
+
return !verdict.allowed;
|
|
3039
|
+
};
|
|
3040
|
+
const usersSlug = (req) => req.payload.config.admin?.user ?? "users";
|
|
3041
|
+
const status = {
|
|
3042
|
+
path: "/meta-login/status",
|
|
3043
|
+
method: "get",
|
|
3044
|
+
handler: async () => Response.json({ enabled: Boolean(getMetaAppCredentials()) }, { headers: { "cache-control": "no-store" } })
|
|
3045
|
+
};
|
|
3046
|
+
const start = {
|
|
3047
|
+
path: "/meta-login/start",
|
|
3048
|
+
method: "get",
|
|
3049
|
+
handler: async (req) => {
|
|
3050
|
+
const app = getMetaAppCredentials();
|
|
3051
|
+
if (!app) return backToLogin("not_configured");
|
|
3052
|
+
if (await throttled(req)) return new Response("Too many sign-in attempts. Try again in a few minutes.", { status: 429 });
|
|
3053
|
+
const state = newState();
|
|
3054
|
+
const params = new URLSearchParams({ client_id: app.appId, redirect_uri: callbackUri(), state, scope: LOGIN_SCOPE, response_type: "code" });
|
|
3055
|
+
const headers = new Headers({ Location: `https://www.facebook.com/${GRAPH_API_VERSION}/dialog/oauth?${params}` });
|
|
3056
|
+
headers.append("Set-Cookie", stateCookie(state, isSecure()));
|
|
3057
|
+
return new Response(null, { status: 302, headers });
|
|
3058
|
+
}
|
|
3059
|
+
};
|
|
3060
|
+
const callback = {
|
|
3061
|
+
path: "/meta-login/callback",
|
|
3062
|
+
method: "get",
|
|
3063
|
+
handler: async (req) => {
|
|
3064
|
+
const app = getMetaAppCredentials();
|
|
3065
|
+
if (!app) return backToLogin("not_configured");
|
|
3066
|
+
if (await throttled(req)) return new Response("Too many sign-in attempts. Try again in a few minutes.", { status: 429 });
|
|
3067
|
+
if (req.query?.error) return backToLogin("denied");
|
|
3068
|
+
const code = typeof req.query?.code === "string" ? req.query.code : void 0;
|
|
3069
|
+
const state = typeof req.query?.state === "string" ? req.query.state : void 0;
|
|
3070
|
+
if (!code || !statesMatch(state, readCookie(req.headers.get("cookie"), STATE_COOKIE))) return backToLogin("state");
|
|
3071
|
+
const token = await exchangeLoginCode(code, app, callbackUri());
|
|
3072
|
+
if (!token.ok) {
|
|
3073
|
+
req.payload.logger.warn(`[meta-login] Facebook did not accept the sign-in: ${token.error}`);
|
|
3074
|
+
return backToLogin("failed");
|
|
3075
|
+
}
|
|
3076
|
+
const profile = await fetchLoginProfile(token.accessToken, app.appSecret);
|
|
3077
|
+
if (!profile.ok) {
|
|
3078
|
+
req.payload.logger.warn(`[meta-login] Could not read the Facebook profile: ${profile.error}`);
|
|
3079
|
+
return backToLogin("failed");
|
|
3080
|
+
}
|
|
3081
|
+
const slug = usersSlug(req);
|
|
3082
|
+
const resolution = await resolveLoginUser(req.payload, slug, profile.profile);
|
|
3083
|
+
if (!resolution.ok) return backToLogin(resolution.code);
|
|
3084
|
+
let session;
|
|
3085
|
+
try {
|
|
3086
|
+
session = await startPlatformSession(req, slug, resolution.user, isSecure());
|
|
3087
|
+
} catch (error) {
|
|
3088
|
+
const status2 = error.status;
|
|
3089
|
+
req.payload.logger.warn(`[meta-login] Sign-in refused: ${error instanceof Error ? error.message : String(error)}`);
|
|
3090
|
+
return backToLogin(status2 === 403 ? "suspended" : "failed");
|
|
3091
|
+
}
|
|
3092
|
+
if (resolution.linked) req.payload.logger.info(`[meta-login] Account ${String(resolution.user.id)} was joined to a Facebook account (same email).`);
|
|
3093
|
+
const headers = new Headers({ Location: `${serverUrl3()}/admin` });
|
|
3094
|
+
headers.append("Set-Cookie", session.cookie);
|
|
3095
|
+
headers.append("Set-Cookie", clearedStateCookie(isSecure()));
|
|
3096
|
+
return new Response(null, { status: 302, headers });
|
|
3097
|
+
}
|
|
3098
|
+
};
|
|
3099
|
+
const unlink = {
|
|
3100
|
+
path: "/meta-login/unlink",
|
|
3101
|
+
method: "post",
|
|
3102
|
+
handler: async (req) => {
|
|
3103
|
+
if (!req.user) return Response.json({ error: "Sign in first." }, { status: 401 });
|
|
3104
|
+
await req.payload.update({
|
|
3105
|
+
collection: usersSlug(req),
|
|
3106
|
+
id: req.user.id,
|
|
3107
|
+
data: { facebookId: null },
|
|
3108
|
+
overrideAccess: true,
|
|
3109
|
+
context: { skipOwnership: true }
|
|
3110
|
+
});
|
|
3111
|
+
return Response.json({ unlinked: true });
|
|
3112
|
+
}
|
|
3113
|
+
};
|
|
3114
|
+
return [status, start, callback, unlink];
|
|
3115
|
+
}
|
|
3116
|
+
|
|
3117
|
+
// src/fields/facebookIdField.ts
|
|
3118
|
+
var facebookIdField = {
|
|
3119
|
+
name: "facebookId",
|
|
3120
|
+
type: "text",
|
|
3121
|
+
unique: true,
|
|
3122
|
+
index: true,
|
|
3123
|
+
access: {
|
|
3124
|
+
create: () => false,
|
|
3125
|
+
update: () => false,
|
|
3126
|
+
read: ({ req, doc }) => {
|
|
3127
|
+
const user = req.user;
|
|
3128
|
+
if (!user) return false;
|
|
3129
|
+
return user.role === "super-admin" || doc?.id !== void 0 && String(doc.id) === String(user.id);
|
|
3130
|
+
}
|
|
3131
|
+
},
|
|
3132
|
+
admin: {
|
|
3133
|
+
readOnly: true,
|
|
3134
|
+
position: "sidebar",
|
|
3135
|
+
description: 'Set when this person signs in with Facebook and the email matches. To disconnect it, they use "Disconnect Facebook".'
|
|
3136
|
+
}
|
|
3137
|
+
};
|
|
3138
|
+
function attachFacebookLogin(collection, usersSlug) {
|
|
3139
|
+
if (collection.slug !== usersSlug) return collection;
|
|
3140
|
+
if (collection.fields.some((field) => "name" in field && field.name === facebookIdField.name)) return collection;
|
|
3141
|
+
return { ...collection, fields: [...collection.fields, facebookIdField] };
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
// src/collections/MetaApprovals.ts
|
|
3145
|
+
var MetaApprovals = {
|
|
3146
|
+
slug: "meta-approvals",
|
|
3147
|
+
labels: { singular: "Meta Approval", plural: "Meta Approvals" },
|
|
3148
|
+
admin: {
|
|
3149
|
+
useAsTitle: "templateKey",
|
|
3150
|
+
defaultColumns: ["templateKey", "site", "status", "rejectionReason", "updatedAt"],
|
|
3151
|
+
group: "Integrations",
|
|
3152
|
+
// Internal bookkeeping. The status shows on the notification template.
|
|
3153
|
+
hidden: true
|
|
3154
|
+
},
|
|
3155
|
+
access: {
|
|
3156
|
+
read: siteScopedRead(),
|
|
3157
|
+
create: () => false,
|
|
3158
|
+
update: () => false,
|
|
3159
|
+
delete: siteScopedDelete()
|
|
3160
|
+
},
|
|
3161
|
+
indexes: [{ fields: ["site", "templateKey", "contentHash"], unique: true }],
|
|
3162
|
+
fields: [
|
|
3163
|
+
{ name: "site", type: "relationship", relationTo: "sites", required: true, index: true, admin: { readOnly: true } },
|
|
3164
|
+
{ name: "templateKey", type: "text", required: true, index: true, admin: { readOnly: true, description: "The notification template this was made from." } },
|
|
3165
|
+
{ name: "contentHash", type: "text", required: true, admin: { readOnly: true, description: "A fingerprint of the wording that was submitted." } },
|
|
3166
|
+
{ name: "metaName", type: "text", required: true, admin: { readOnly: true, description: "The name Meta knows the template by." } },
|
|
3167
|
+
{ name: "language", type: "text", required: true, admin: { readOnly: true } },
|
|
3168
|
+
{ name: "category", type: "text", admin: { readOnly: true, description: "As Meta classified it." } },
|
|
3169
|
+
{
|
|
3170
|
+
name: "status",
|
|
3171
|
+
type: "select",
|
|
3172
|
+
required: true,
|
|
3173
|
+
defaultValue: "pending",
|
|
3174
|
+
index: true,
|
|
3175
|
+
options: [
|
|
3176
|
+
{ label: "With Meta for review", value: "pending" },
|
|
3177
|
+
{ label: "Approved", value: "approved" },
|
|
3178
|
+
{ label: "Rejected by Meta", value: "rejected" },
|
|
3179
|
+
{ label: "Paused by Meta", value: "paused" },
|
|
3180
|
+
{ label: "Disabled by Meta", value: "disabled" },
|
|
3181
|
+
{ label: "Wording Meta would refuse", value: "invalid" },
|
|
3182
|
+
{ label: "Could not be submitted", value: "failed" }
|
|
3183
|
+
],
|
|
3184
|
+
admin: { readOnly: true }
|
|
3185
|
+
},
|
|
3186
|
+
{ name: "metaTemplateId", type: "text", index: true, admin: { readOnly: true, description: "Meta's id for the template, once submitted." } },
|
|
3187
|
+
{ name: "wabaId", type: "text", admin: { readOnly: true, description: "The WhatsApp business account it was submitted to." } },
|
|
3188
|
+
{ name: "rejectionReason", type: "textarea", admin: { readOnly: true, description: "Why it is not approved, in plain words." } },
|
|
3189
|
+
{ name: "body", type: "textarea", admin: { readOnly: true, description: "The wording as submitted to Meta." } },
|
|
3190
|
+
{ name: "parameters", type: "json", admin: { readOnly: true, description: "Which workflow data fills each placeholder." } },
|
|
3191
|
+
{ name: "alertedStatus", type: "text", admin: { readOnly: true, hidden: true, description: "The last problem the owner was told about, so it is told once." } }
|
|
3192
|
+
],
|
|
3193
|
+
timestamps: true
|
|
3194
|
+
};
|
|
3195
|
+
|
|
3196
|
+
// src/jobs/templateStatus.ts
|
|
3197
|
+
function createTemplateStatusJob(host) {
|
|
3198
|
+
return {
|
|
3199
|
+
slug: "meta-template-status",
|
|
3200
|
+
schedule: [{ cron: "*/5 * * * *", queue: "default" }],
|
|
3201
|
+
inputSchema: [],
|
|
3202
|
+
outputSchema: [
|
|
3203
|
+
{ name: "checked", type: "number" },
|
|
3204
|
+
{ name: "changed", type: "number" },
|
|
3205
|
+
{ name: "retried", type: "number" }
|
|
3206
|
+
],
|
|
3207
|
+
retries: 0,
|
|
3208
|
+
handler: async ({ req }) => {
|
|
3209
|
+
try {
|
|
3210
|
+
const output = await checkPendingTemplates({ payload: req.payload, req, host });
|
|
3211
|
+
if (output.changed > 0 || output.retried > 0) {
|
|
3212
|
+
req.payload.logger.info(`[meta:templates] checked ${output.checked}, changed ${output.changed}, retried ${output.retried}`);
|
|
3213
|
+
}
|
|
3214
|
+
return { output };
|
|
3215
|
+
} catch (err) {
|
|
3216
|
+
req.payload.logger.warn(`[meta:templates] this check was skipped (${err instanceof Error ? err.message : err})`);
|
|
3217
|
+
return { output: { checked: 0, changed: 0, retried: 0 } };
|
|
3218
|
+
}
|
|
3219
|
+
}
|
|
3220
|
+
};
|
|
3221
|
+
}
|
|
3222
|
+
|
|
3223
|
+
// src/templates/hooks.ts
|
|
3224
|
+
var AFTER_COMMIT_MS = 2e3;
|
|
3225
|
+
var STATUS_WORDS = {
|
|
3226
|
+
pending: "with Meta for review",
|
|
3227
|
+
approved: "approved",
|
|
3228
|
+
rejected: "rejected by Meta",
|
|
3229
|
+
paused: "paused by Meta",
|
|
3230
|
+
disabled: "disabled by Meta",
|
|
3231
|
+
invalid: "not submitted: the wording does not follow Meta's rules",
|
|
3232
|
+
failed: "could not be submitted yet"
|
|
3233
|
+
};
|
|
3234
|
+
async function approvalSummary(req, templateKey) {
|
|
3235
|
+
if (typeof templateKey !== "string" || !templateKey || !req.user) return "";
|
|
3236
|
+
const found = await req.payload.find({
|
|
3237
|
+
collection: asCollectionSlug("meta-approvals"),
|
|
3238
|
+
where: { templateKey: { equals: templateKey } },
|
|
3239
|
+
sort: "-createdAt",
|
|
3240
|
+
limit: 50,
|
|
3241
|
+
depth: 1,
|
|
3242
|
+
user: req.user,
|
|
3243
|
+
overrideAccess: false
|
|
3244
|
+
});
|
|
3245
|
+
const latestBySite = /* @__PURE__ */ new Map();
|
|
3246
|
+
for (const row of found.docs) {
|
|
3247
|
+
const id = typeof row.site === "object" && row.site ? String(row.site.id) : String(row.site);
|
|
3248
|
+
if (!latestBySite.has(id)) latestBySite.set(id, row);
|
|
3249
|
+
}
|
|
3250
|
+
return [...latestBySite.values()].map((row) => {
|
|
3251
|
+
const site = typeof row.site === "object" && row.site ? row.site.name || row.site.slug || "A site" : `Site ${row.site}`;
|
|
3252
|
+
const why = row.rejectionReason && row.status !== "approved" && row.status !== "pending" ? `: ${row.rejectionReason}` : "";
|
|
3253
|
+
return `${site} \u2014 ${STATUS_WORDS[row.status] ?? row.status}${why}`;
|
|
3254
|
+
}).join("\n");
|
|
3255
|
+
}
|
|
3256
|
+
var whatsappDeliveryField = {
|
|
3257
|
+
name: "whatsappDelivery",
|
|
3258
|
+
type: "textarea",
|
|
3259
|
+
label: "WhatsApp delivery through Meta",
|
|
3260
|
+
virtual: true,
|
|
3261
|
+
admin: {
|
|
3262
|
+
readOnly: true,
|
|
3263
|
+
description: "When a site sends this message by WhatsApp through Meta, Meta must approve its exact wording first. This shows where it stands for your sites. Change the text and it is sent to Meta again."
|
|
3264
|
+
},
|
|
3265
|
+
hooks: {
|
|
3266
|
+
afterRead: [
|
|
3267
|
+
async ({ req, siblingData, data }) => {
|
|
3268
|
+
try {
|
|
3269
|
+
return await approvalSummary(req, siblingData?.key ?? data?.key);
|
|
3270
|
+
} catch (err) {
|
|
3271
|
+
req.payload.logger.warn(`[meta:templates] could not read a template's approval status: ${err}`);
|
|
3272
|
+
return "";
|
|
3273
|
+
}
|
|
3274
|
+
}
|
|
3275
|
+
]
|
|
3276
|
+
}
|
|
3277
|
+
};
|
|
3278
|
+
var relationId4 = (value) => {
|
|
3279
|
+
if (typeof value === "number" || typeof value === "string") return value;
|
|
3280
|
+
if (value && typeof value === "object") {
|
|
3281
|
+
const id = value.id;
|
|
3282
|
+
if (typeof id === "number" || typeof id === "string") return id;
|
|
3283
|
+
}
|
|
3284
|
+
return null;
|
|
3285
|
+
};
|
|
3286
|
+
function inBackground(req, label, work) {
|
|
3287
|
+
setTimeout(() => {
|
|
3288
|
+
work().catch((err) => req.payload.logger.error(`[meta:templates] ${label} failed: ${err}`));
|
|
3289
|
+
}, AFTER_COMMIT_MS);
|
|
3290
|
+
}
|
|
3291
|
+
function attachTemplateHooks(collection, host) {
|
|
3292
|
+
if (collection.slug === "workflows") {
|
|
3293
|
+
return {
|
|
3294
|
+
...collection,
|
|
3295
|
+
hooks: {
|
|
3296
|
+
...collection.hooks,
|
|
3297
|
+
afterChange: [
|
|
3298
|
+
...collection.hooks?.afterChange ?? [],
|
|
3299
|
+
({ doc, req }) => {
|
|
3300
|
+
const siteId = relationId4(doc.site);
|
|
3301
|
+
const keys = whatsappTemplateKeys(doc.steps);
|
|
3302
|
+
if (siteId != null && keys.length > 0) {
|
|
3303
|
+
inBackground(req, "submitting the workflow's templates", () => syncSiteTemplates({ payload: req.payload, req, host }, siteId, keys));
|
|
3304
|
+
}
|
|
3305
|
+
return doc;
|
|
3306
|
+
}
|
|
3307
|
+
]
|
|
3308
|
+
}
|
|
3309
|
+
};
|
|
3310
|
+
}
|
|
3311
|
+
if (collection.slug === "notification-templates") {
|
|
3312
|
+
return {
|
|
3313
|
+
...collection,
|
|
3314
|
+
fields: [...collection.fields, whatsappDeliveryField],
|
|
3315
|
+
hooks: {
|
|
3316
|
+
...collection.hooks,
|
|
3317
|
+
afterChange: [
|
|
3318
|
+
...collection.hooks?.afterChange ?? [],
|
|
3319
|
+
({ doc, req }) => {
|
|
3320
|
+
inBackground(req, "resubmitting a changed template", () => syncAfterTemplateChange({ payload: req.payload, req, host }, doc));
|
|
3321
|
+
return doc;
|
|
3322
|
+
}
|
|
3323
|
+
]
|
|
3324
|
+
}
|
|
3325
|
+
};
|
|
3326
|
+
}
|
|
3327
|
+
return collection;
|
|
3328
|
+
}
|
|
3329
|
+
|
|
3330
|
+
// src/channels/registry.ts
|
|
3331
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("opscms.notificationChannelProviders");
|
|
3332
|
+
function registerNotificationChannel(provider) {
|
|
3333
|
+
const holder = globalThis;
|
|
3334
|
+
const registry = holder[REGISTRY_KEY] ??= /* @__PURE__ */ new Map();
|
|
3335
|
+
registry.set(provider.id, provider);
|
|
3336
|
+
}
|
|
3337
|
+
|
|
3338
|
+
// src/index.ts
|
|
3339
|
+
function metaPlugin(options = {}) {
|
|
3340
|
+
if (options.registry) {
|
|
3341
|
+
options.registry.register("meta-conversion-event", metaConversionEventHandler);
|
|
3342
|
+
}
|
|
3343
|
+
return (config) => {
|
|
3344
|
+
registerNotificationChannel(metaWhatsAppChannel);
|
|
3345
|
+
const usersSlug = config.admin?.user ?? "users";
|
|
3346
|
+
const modifiedCollections = (config.collections || []).map((collection) => {
|
|
3347
|
+
const withSync = attachFacebookLogin(attachTemplateHooks(attachCommerceCatalogSync(collection), options.host), usersSlug);
|
|
3348
|
+
if (withSync.slug !== "workflows") return withSync;
|
|
3349
|
+
const stepsField = withSync.fields.find((f) => "name" in f && f.name === "steps" && f.type === "blocks");
|
|
3350
|
+
if (!stepsField) return withSync;
|
|
3351
|
+
stepsField.blocks = [
|
|
3352
|
+
...stepsField.blocks || [],
|
|
3353
|
+
{
|
|
3354
|
+
slug: "trigger_meta_conversion",
|
|
3355
|
+
labels: { singular: "Trigger Meta Conversion Event", plural: "Trigger Meta Conversion Events" },
|
|
3356
|
+
fields: [
|
|
3357
|
+
{
|
|
3358
|
+
name: "event_name",
|
|
3359
|
+
type: "select",
|
|
3360
|
+
required: true,
|
|
3361
|
+
options: [
|
|
3362
|
+
{ label: "Lead", value: "Lead" },
|
|
3363
|
+
{ label: "Purchase", value: "Purchase" },
|
|
3364
|
+
{ label: "AddToCart", value: "AddToCart" },
|
|
3365
|
+
{ label: "InitiateCheckout", value: "InitiateCheckout" },
|
|
3366
|
+
{ label: "ViewContent", value: "ViewContent" },
|
|
3367
|
+
{ label: "CompleteRegistration", value: "CompleteRegistration" }
|
|
3368
|
+
],
|
|
3369
|
+
admin: { description: "Meta standard event name." }
|
|
3370
|
+
},
|
|
3371
|
+
{
|
|
3372
|
+
name: "value",
|
|
3373
|
+
type: "text",
|
|
3374
|
+
admin: { description: "Numeric value, e.g. order total. Supports {{var}} (e.g. {{order_total}})." }
|
|
3375
|
+
},
|
|
3376
|
+
{
|
|
3377
|
+
name: "currency",
|
|
3378
|
+
type: "text",
|
|
3379
|
+
defaultValue: "NGN",
|
|
3380
|
+
admin: { description: "3-letter currency code. Supports {{var}}." }
|
|
3381
|
+
},
|
|
3382
|
+
{
|
|
3383
|
+
name: "content_name",
|
|
3384
|
+
type: "text",
|
|
3385
|
+
admin: { description: "Optional. Supports {{var}}." }
|
|
3386
|
+
},
|
|
3387
|
+
{
|
|
3388
|
+
name: "event_source_url",
|
|
3389
|
+
type: "text",
|
|
3390
|
+
admin: { description: "Optional. Supports {{var}}." }
|
|
3391
|
+
},
|
|
3392
|
+
{
|
|
3393
|
+
type: "row",
|
|
3394
|
+
fields: [
|
|
3395
|
+
{
|
|
3396
|
+
name: "email",
|
|
3397
|
+
type: "text",
|
|
3398
|
+
admin: { description: "Optional, e.g. {{doc.email}}. SHA-256 hashed before sending \u2014 improves Meta's event match quality, raw value never leaves the server.", width: "50%" }
|
|
3399
|
+
},
|
|
3400
|
+
{
|
|
3401
|
+
name: "phone",
|
|
3402
|
+
type: "text",
|
|
3403
|
+
admin: { description: "Optional, e.g. {{doc.phone}}. SHA-256 hashed before sending.", width: "50%" }
|
|
3404
|
+
}
|
|
3405
|
+
]
|
|
3406
|
+
}
|
|
3407
|
+
]
|
|
3408
|
+
}
|
|
3409
|
+
];
|
|
3410
|
+
return withSync;
|
|
3411
|
+
});
|
|
3412
|
+
return {
|
|
3413
|
+
...config,
|
|
3414
|
+
admin: {
|
|
3415
|
+
...config.admin,
|
|
3416
|
+
components: {
|
|
3417
|
+
...config.admin?.components,
|
|
3418
|
+
afterLogin: [
|
|
3419
|
+
...config.admin?.components?.afterLogin ?? [],
|
|
3420
|
+
{ path: "opscms-meta-plugin/components/MetaLoginButton", exportName: "MetaLoginButton" }
|
|
3421
|
+
]
|
|
3422
|
+
}
|
|
3423
|
+
},
|
|
3424
|
+
jobs: { ...config.jobs, tasks: [...config.jobs?.tasks ?? [], createTemplateStatusJob(options.host)] },
|
|
3425
|
+
collections: [...modifiedCollections, MetaConfig, MetaApprovals],
|
|
3426
|
+
endpoints: [
|
|
3427
|
+
...config.endpoints || [],
|
|
3428
|
+
metaCatalogFeedEndpoint,
|
|
3429
|
+
metaOAuthAppInfoEndpoint,
|
|
3430
|
+
metaOAuthStartEndpoint,
|
|
3431
|
+
metaOAuthCallbackEndpoint,
|
|
3432
|
+
metaOAuthDisconnectEndpoint,
|
|
3433
|
+
metaOAuthPagesEndpoint,
|
|
3434
|
+
metaOAuthSelectPageEndpoint,
|
|
3435
|
+
metaOAuthListPixelsEndpoint,
|
|
3436
|
+
metaOAuthSelectPixelEndpoint,
|
|
3437
|
+
metaOAuthCreatePixelEndpoint,
|
|
3438
|
+
metaOAuthMeEndpoint,
|
|
3439
|
+
metaCatalogListEndpoint,
|
|
3440
|
+
metaCatalogSelectEndpoint,
|
|
3441
|
+
metaCatalogCreateEndpoint,
|
|
3442
|
+
metaCatalogSyncEndpoint,
|
|
3443
|
+
metaWhatsAppNumbersEndpoint,
|
|
3444
|
+
createMetaWhatsAppSelectEndpoint(options.host),
|
|
3445
|
+
threadsOAuthStartEndpoint,
|
|
3446
|
+
threadsOAuthCallbackEndpoint,
|
|
3447
|
+
...createMetaWebhookEndpoints(options.host),
|
|
3448
|
+
...createMetaLoginEndpoints(options.host)
|
|
3449
|
+
]
|
|
3450
|
+
};
|
|
3451
|
+
};
|
|
3452
|
+
}
|
|
3453
|
+
function attachCommerceCatalogSync(collection) {
|
|
3454
|
+
if (collection.slug !== COMMERCE_COLLECTION) return collection;
|
|
3455
|
+
const slug = collection.slug;
|
|
3456
|
+
return {
|
|
3457
|
+
...collection,
|
|
3458
|
+
hooks: {
|
|
3459
|
+
...collection.hooks,
|
|
3460
|
+
afterChange: [
|
|
3461
|
+
...collection.hooks?.afterChange || [],
|
|
3462
|
+
async ({ doc, req }) => {
|
|
3463
|
+
if (req.context?.skipMetaCatalogSync) return doc;
|
|
3464
|
+
if (doc._status === "draft") return doc;
|
|
3465
|
+
try {
|
|
3466
|
+
await syncCatalogDoc(req.payload, doc, "UPDATE", slug);
|
|
3467
|
+
} catch (err) {
|
|
3468
|
+
req.payload.logger.warn(`[MetaCatalog] save sync failed: ${err}`);
|
|
3469
|
+
}
|
|
3470
|
+
return doc;
|
|
3471
|
+
}
|
|
3472
|
+
],
|
|
3473
|
+
afterDelete: [
|
|
3474
|
+
...collection.hooks?.afterDelete || [],
|
|
3475
|
+
async ({ doc, req }) => {
|
|
3476
|
+
if (!doc) return;
|
|
3477
|
+
try {
|
|
3478
|
+
await syncCatalogDoc(req.payload, doc, "DELETE", slug);
|
|
3479
|
+
} catch (err) {
|
|
3480
|
+
req.payload.logger.warn(`[MetaCatalog] delete sync failed: ${err}`);
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3483
|
+
]
|
|
3484
|
+
}
|
|
3485
|
+
};
|
|
3486
|
+
}
|
|
3487
|
+
export {
|
|
3488
|
+
attachFacebookLogin,
|
|
3489
|
+
createMetaLoginEndpoints,
|
|
3490
|
+
createMetaWebhookEndpoints,
|
|
3491
|
+
decryptCredential,
|
|
3492
|
+
encryptCredential,
|
|
3493
|
+
explainTemplateSendError,
|
|
3494
|
+
facebookIdField,
|
|
3495
|
+
getMetaCredentials,
|
|
3496
|
+
metaConversionEventHandler,
|
|
3497
|
+
metaPlugin,
|
|
3498
|
+
metaWhatsAppChannel,
|
|
3499
|
+
resolveLoginUser,
|
|
3500
|
+
sendConversionEvent,
|
|
3501
|
+
subscribeWabaToApp,
|
|
3502
|
+
unsubscribeWabaFromApp
|
|
3503
|
+
};
|