@oondemand/oon-core-back 0.3.60 → 0.3.62

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oondemand/oon-core-back",
3
- "version": "0.3.60",
3
+ "version": "0.3.62",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/oondemand/oon-platform.git",
@@ -91,6 +91,16 @@ function buildIntegrationRouter() {
91
91
  requestId: req.requestId || "",
92
92
  }));
93
93
  }));
94
+ router.get("/providers/:provider/configuration/:instanceId/webhook", rbac(READ_ROLES), asyncHandler(async (req, res) => {
95
+ const provider = getIntegrationProvider(req.params.provider);
96
+ const getWebhookAccess = requireProviderExtension(provider, "getWebhookAccess");
97
+ res.json({ provider: provider.key, ...await getWebhookAccess(req.params.instanceId) });
98
+ }));
99
+ router.post("/providers/:provider/configuration/:instanceId/webhook/rotate", rbac(WRITE_ROLES), asyncHandler(async (req, res) => {
100
+ const provider = getIntegrationProvider(req.params.provider);
101
+ const rotateWebhookToken = requireProviderExtension(provider, "rotateWebhookToken");
102
+ res.json({ provider: provider.key, ...await rotateWebhookToken(req.params.instanceId) });
103
+ }));
94
104
  router.get("/providers/:provider/mappings", rbac(READ_ROLES), asyncHandler(async (req, res) => {
95
105
  const provider = getIntegrationProvider(req.params.provider);
96
106
  const describe = requireProviderExtension(provider, "describe");
@@ -63,6 +63,10 @@ function maskSecret(value) {
63
63
  return `${clear.slice(0, 2)}${"•".repeat(Math.min(8, clear.length - 4))}${clear.slice(-2)}`;
64
64
  }
65
65
 
66
+ function generateWebhookToken() {
67
+ return crypto.randomBytes(32).toString("base64url");
68
+ }
69
+
66
70
  function normalizeInstanceId(value) {
67
71
  const instanceId = String(value || "default").trim().toLowerCase();
68
72
  if (!/^[a-z0-9][a-z0-9._-]*$/.test(instanceId)) {
@@ -83,6 +87,7 @@ function configurationSchema() {
83
87
  webhookTokenEncrypted: { type: String, default: "", select: false },
84
88
  appKeyMasked: { type: String, default: "" },
85
89
  credentialsConfigured: { type: Boolean, default: false },
90
+ webhookConfigured: { type: Boolean, default: false },
86
91
  connectionStatus: { type: String, enum: ["not-tested", "ok", "error"], default: "not-tested" },
87
92
  lastConnectionError: { type: String, default: "" },
88
93
  lastConnectionTestAt: { type: Date, default: null },
@@ -134,6 +139,7 @@ function environmentCredentials(instanceId) {
134
139
  function publicConfiguration(document) {
135
140
  if (!document) return null;
136
141
  const value = typeof document.toObject === "function" ? document.toObject() : { ...document };
142
+ value.webhookConfigured = Boolean(value.webhookConfigured || value.webhookTokenEncrypted);
137
143
  delete value.appKeyEncrypted;
138
144
  delete value.appSecretEncrypted;
139
145
  delete value.webhookTokenEncrypted;
@@ -142,7 +148,10 @@ function publicConfiguration(document) {
142
148
 
143
149
  async function listOmieConfigurations() {
144
150
  const { Configuration } = getOmieModels();
145
- const persisted = await Configuration.find({}).sort({ label: 1, instanceId: 1 }).lean();
151
+ const persisted = await Configuration.find({})
152
+ .select("+webhookTokenEncrypted")
153
+ .sort({ label: 1, instanceId: 1 })
154
+ .lean();
146
155
  if (persisted.length) return persisted.map(publicConfiguration);
147
156
  const env = environmentCredentials("default");
148
157
  return [{
@@ -153,6 +162,7 @@ async function listOmieConfigurations() {
153
162
  baseUrl: env.baseUrl,
154
163
  appKeyMasked: maskSecret(env.appKey),
155
164
  credentialsConfigured: Boolean(env.appKey && env.appSecret),
165
+ webhookConfigured: Boolean(env.webhookToken),
156
166
  connectionStatus: "not-tested",
157
167
  lastConnectionError: "",
158
168
  lastConnectionTestAt: null,
@@ -180,6 +190,7 @@ async function saveOmieConfiguration(instanceId, input = {}) {
180
190
  const appKey = String(input.appKey || "").trim();
181
191
  const appSecret = String(input.appSecret || "").trim();
182
192
  const webhookToken = String(input.webhookToken || "").trim();
193
+ const env = environmentCredentials(normalized);
183
194
  if (appKey) {
184
195
  update.appKeyEncrypted = encryptSecret(appKey);
185
196
  update.appKeyMasked = maskSecret(appKey);
@@ -189,10 +200,12 @@ async function saveOmieConfiguration(instanceId, input = {}) {
189
200
  }
190
201
  if (appSecret) update.appSecretEncrypted = encryptSecret(appSecret);
191
202
  else if (current?.appSecretEncrypted) update.appSecretEncrypted = current.appSecretEncrypted;
192
- if (webhookToken) update.webhookTokenEncrypted = encryptSecret(webhookToken);
193
- else if (current?.webhookTokenEncrypted) update.webhookTokenEncrypted = current.webhookTokenEncrypted;
194
203
 
195
- const env = environmentCredentials(normalized);
204
+ const effectiveWebhookToken = webhookToken
205
+ || (current?.webhookTokenEncrypted ? decryptSecret(current.webhookTokenEncrypted) : env.webhookToken)
206
+ || generateWebhookToken();
207
+ update.webhookTokenEncrypted = encryptSecret(effectiveWebhookToken);
208
+ update.webhookConfigured = true;
196
209
  const effectiveKey = appKey || (current?.appKeyEncrypted ? decryptSecret(current.appKeyEncrypted) : env.appKey);
197
210
  const effectiveSecret = appSecret
198
211
  || (current?.appSecretEncrypted ? decryptSecret(current.appSecretEncrypted) : env.appSecret);
@@ -238,6 +251,7 @@ async function resolveOmieConfiguration(instanceId = "default", options = {}) {
238
251
  webhookToken: options.includeSecrets ? env.webhookToken : undefined,
239
252
  appKeyMasked: maskSecret(env.appKey),
240
253
  credentialsConfigured: Boolean(env.appKey && env.appSecret),
254
+ webhookConfigured: Boolean(env.webhookToken),
241
255
  connectionStatus: "not-tested",
242
256
  source: "environment",
243
257
  };
@@ -253,6 +267,57 @@ async function resolveOmieConfiguration(instanceId = "default", options = {}) {
253
267
  return result;
254
268
  }
255
269
 
270
+ async function ensureOmieWebhookAccess(instanceId = "default", options = {}) {
271
+ const normalized = normalizeInstanceId(instanceId);
272
+ const rotate = Boolean(options.rotate);
273
+ const { Configuration } = getOmieModels();
274
+ const env = environmentCredentials(normalized);
275
+ const current = await Configuration.findOne({ instanceId: normalized })
276
+ .select("+appKeyEncrypted +appSecretEncrypted +webhookTokenEncrypted");
277
+
278
+ let token = !rotate && current?.webhookTokenEncrypted
279
+ ? decryptSecret(current.webhookTokenEncrypted)
280
+ : (!rotate ? env.webhookToken : "");
281
+ if (!token) token = generateWebhookToken();
282
+
283
+ if (!current) {
284
+ await saveOmieConfiguration(normalized, {
285
+ label: normalized === "default" ? "Omie" : normalized,
286
+ active: Boolean(env.appKey && env.appSecret),
287
+ baseUrl: env.baseUrl,
288
+ ...(env.appKey ? { appKey: env.appKey } : {}),
289
+ ...(env.appSecret ? { appSecret: env.appSecret } : {}),
290
+ webhookToken: token,
291
+ });
292
+ } else if (rotate || !current.webhookTokenEncrypted) {
293
+ await Configuration.updateOne(
294
+ { instanceId: normalized },
295
+ {
296
+ $set: {
297
+ webhookTokenEncrypted: encryptSecret(token),
298
+ webhookConfigured: true,
299
+ },
300
+ },
301
+ );
302
+ } else if (!current.webhookConfigured) {
303
+ await Configuration.updateOne(
304
+ { instanceId: normalized },
305
+ { $set: { webhookConfigured: true } },
306
+ );
307
+ }
308
+
309
+ return {
310
+ instanceId: normalized,
311
+ webhookConfigured: true,
312
+ rotated: rotate,
313
+ webhookPath: `/integrations/webhooks/omie/${encodeURIComponent(token)}`,
314
+ };
315
+ }
316
+
317
+ async function rotateOmieWebhookToken(instanceId = "default") {
318
+ return ensureOmieWebhookAccess(instanceId, { rotate: true });
319
+ }
320
+
256
321
  async function updateConnectionStatus(instanceId, result = {}) {
257
322
  const normalized = normalizeInstanceId(instanceId);
258
323
  const { Configuration } = getOmieModels();
@@ -297,6 +362,8 @@ module.exports = {
297
362
  DEFAULT_BASE_URL,
298
363
  decryptSecret,
299
364
  encryptSecret,
365
+ ensureOmieWebhookAccess,
366
+ generateWebhookToken,
300
367
  getOmieModels,
301
368
  listOmieConfigurations,
302
369
  maskSecret,
@@ -304,6 +371,7 @@ module.exports = {
304
371
  publicConfiguration,
305
372
  resolveInstanceByWebhookToken,
306
373
  resolveOmieConfiguration,
374
+ rotateOmieWebhookToken,
307
375
  saveOmieConfiguration,
308
376
  updateConnectionStatus,
309
377
  };
@@ -8,11 +8,13 @@ const { sanitizeIntegrationError, sanitizeIntegrationValue } = require("../integ
8
8
  const { createOmieClient, getPath, resolveTemplate, OmieApiError } = require("./client");
9
9
  const { collectOmieDefinitions, describeOmieDefinitions } = require("./definitions");
10
10
  const {
11
+ ensureOmieWebhookAccess,
11
12
  getOmieModels,
12
13
  listOmieConfigurations,
13
14
  normalizeInstanceId,
14
15
  resolveInstanceByWebhookToken,
15
16
  resolveOmieConfiguration,
17
+ rotateOmieWebhookToken,
16
18
  saveOmieConfiguration,
17
19
  updateConnectionStatus,
18
20
  } = require("./models");
@@ -173,6 +175,7 @@ async function synchronizeOmieList(definitions, list, event, context = {}) {
173
175
  const failures = [];
174
176
 
175
177
  for (const [index, item] of items.entries()) {
178
+ let externalValue;
176
179
  try {
177
180
  const mapped = mapRecord(item, list.mapping || {}, {
178
181
  input,
@@ -180,7 +183,7 @@ async function synchronizeOmieList(definitions, list, event, context = {}) {
180
183
  instanceId,
181
184
  });
182
185
  const externalField = list.target.externalKey;
183
- const externalValue = mapped[externalField]
186
+ externalValue = mapped[externalField]
184
187
  ?? getPath(item, list.sourceExternalKey || externalField);
185
188
  if (externalValue === undefined || externalValue === null || externalValue === "") {
186
189
  throw new GenericError(`Item sem chave externa ${externalField}.`, { statusCode: 422 });
@@ -226,7 +229,13 @@ async function synchronizeOmieList(definitions, list, event, context = {}) {
226
229
  context.recordItem?.({ index, externalKey: externalValue, status: current ? "updated" : "created" });
227
230
  } catch (error) {
228
231
  summary.errors += 1;
229
- const failure = { index, error: sanitizeIntegrationError(error) };
232
+ const failure = {
233
+ index,
234
+ ...(externalValue !== undefined && externalValue !== null && externalValue !== ""
235
+ ? { externalKey: sanitizeIntegrationValue(externalValue) }
236
+ : {}),
237
+ error: sanitizeIntegrationError(error),
238
+ };
230
239
  failures.push(failure);
231
240
  context.recordItem?.(failure);
232
241
  context.recordError?.(failure);
@@ -443,6 +452,8 @@ function ensureOmieProviderRegistered(config = {}) {
443
452
  getConfiguration: listOmieConfigurations,
444
453
  saveConfiguration: saveOmieConfiguration,
445
454
  testConnection: (instanceId, options) => testOmieConnection(definitions, instanceId, options),
455
+ getWebhookAccess: (instanceId) => ensureOmieWebhookAccess(instanceId),
456
+ rotateWebhookToken: (instanceId) => rotateOmieWebhookToken(instanceId),
446
457
  executeCall: (callKey, input, options) => runTrackedOperation({
447
458
  provider: "omie",
448
459
  resource: callKey,