@drawbridge/drawbridge-utils 0.0.108 → 0.0.109

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.
@@ -26,6 +26,7 @@ __export(connections_exports, {
26
26
  INPUTS: () => INPUTS,
27
27
  OAUTH_FIELDS: () => OAUTH_FIELDS,
28
28
  OUTCOMES: () => OUTCOMES,
29
+ accessToken: () => accessToken,
29
30
  availableConnections: () => availableConnections,
30
31
  build: () => build,
31
32
  connectFields: () => connectFields,
@@ -34,6 +35,7 @@ __export(connections_exports, {
34
35
  consentUrl: () => consentUrl,
35
36
  exchange: () => exchange,
36
37
  hookSupport: () => hookSupport,
38
+ isStale: () => isStale,
37
39
  mergeSettings: () => mergeSettings,
38
40
  pkcePair: () => pkcePair,
39
41
  projectConnection: () => projectConnection,
@@ -44,7 +46,8 @@ __export(connections_exports, {
44
46
  resolveConnection: () => resolveConnection,
45
47
  runHook: () => runHook,
46
48
  scopesMessage: () => scopesMessage,
47
- stepQueues: () => stepQueues
49
+ stepQueues: () => stepQueues,
50
+ tokenSettings: () => tokenSettings
48
51
  });
49
52
  module.exports = __toCommonJS(connections_exports);
50
53
 
@@ -250,6 +253,56 @@ var refresh = async ({ clientId, clientSecret, descriptor, fetcher = fetch, refr
250
253
  };
251
254
  };
252
255
 
256
+ // lib/connections/token.js
257
+ var SKEW_SECONDS = 120;
258
+ var isStale = (settings, now = Date.now()) => {
259
+ if (!(settings == null ? void 0 : settings.expiresAt)) return false;
260
+ return new Date(settings.expiresAt).getTime() - SKEW_SECONDS * 1e3 <= now;
261
+ };
262
+ var tokenSettings = ({ existing = {}, now = Date.now(), tokens }) => ({
263
+ accessToken: tokens.accessToken,
264
+ // A vendor that does not rotate its refresh token returns none on a refresh
265
+ // (Klaviyo). Keeping the existing one is what makes the NEXT refresh work —
266
+ // dropping it invalidates the grant one call later, nowhere near the cause.
267
+ ...(tokens.refreshToken || existing.refreshToken) && {
268
+ refreshToken: tokens.refreshToken || existing.refreshToken
269
+ },
270
+ // Absent when the vendor issues non-expiring tokens, and absent is meaningful
271
+ // — isStale reads it as "nothing to refresh toward".
272
+ ...tokens.expiresIn && {
273
+ expiresAt: new Date(now + tokens.expiresIn * 1e3).toISOString()
274
+ },
275
+ ...tokens.scope && { scope: tokens.scope }
276
+ });
277
+ var accessToken = async ({
278
+ clientId,
279
+ clientSecret,
280
+ fetcher,
281
+ force = false,
282
+ manifest,
283
+ now = Date.now(),
284
+ save,
285
+ settings
286
+ } = {}) => {
287
+ if (!(settings == null ? void 0 : settings.accessToken) && !(settings == null ? void 0 : settings.refreshToken)) {
288
+ throw new Error("This connection holds no credential, so there is no token to use");
289
+ }
290
+ if (!force && !isStale(settings, now)) return settings.accessToken;
291
+ if (!settings.refreshToken) {
292
+ throw new Error("This connection has expired and cannot be renewed automatically. Reconnect it.");
293
+ }
294
+ const minted = await refresh({
295
+ clientId,
296
+ clientSecret,
297
+ descriptor: manifest.auth.oauth,
298
+ ...fetcher && { fetcher },
299
+ refreshToken: settings.refreshToken
300
+ });
301
+ const next = tokenSettings({ existing: settings, now, tokens: minted });
302
+ if (save) await save(next);
303
+ return next.accessToken;
304
+ };
305
+
253
306
  // lib/connections/icons/klaviyo.js
254
307
  var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
255
308
  <rect width="500" height="500" fill="white"/>
@@ -257,6 +310,26 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
257
310
  </svg>`;
258
311
 
259
312
  // lib/connections/klaviyo.js
313
+ var REVISION = "2026-07-15";
314
+ var api = async (path, { fetcher = fetch, token }) => {
315
+ const response = await fetcher("https://a.klaviyo.com/api" + path, {
316
+ headers: {
317
+ // Bearer, not Klaviyo-API-Key — that header is for private keys, and
318
+ // sending it with an OAuth token fails in a way that reads like a bad
319
+ // token rather than a bad scheme.
320
+ authorization: "Bearer " + token,
321
+ revision: REVISION
322
+ },
323
+ signal: AbortSignal.timeout(15e3)
324
+ });
325
+ if (!response.ok) {
326
+ throw Object.assign(
327
+ new Error("Klaviyo refused the request (" + response.status + ")"),
328
+ { status: response.status }
329
+ );
330
+ }
331
+ return response.json();
332
+ };
260
333
  var klaviyo_default2 = {
261
334
  // OAuth 2.1, and PKCE is REQUIRED rather than recommended: Klaviyo refuses an
262
335
  // exchange without a code_verifier matching the challenge the consent
@@ -285,6 +358,11 @@ var klaviyo_default2 = {
285
358
  // it is a fact about someone else's records rather than a string this
286
359
  // code computes. Deriving one from a provider key produced
287
360
  // redirect_uri_mismatch on a connection nobody had touched.
361
+ // Klaviyo drops a refresh token after 90 days of NON-USE. The vendor
362
+ // never mentions this at runtime — you discover it when a refresh fails
363
+ // on a connection nobody touched — so it is declared, and it is why
364
+ // auth.probe has to run on a schedule rather than only before a call.
365
+ idleExpiry: 90 * 24 * 60 * 60,
288
366
  redirect: "/api/connection/klaviyo/callback",
289
367
  // Space separated. accounts:read is required by Klaviyo on every app
290
368
  // and must stay in the list; the rest are what a contact sync needs.
@@ -316,7 +394,78 @@ var klaviyo_default2 = {
316
394
  label: "Klaviyo account"
317
395
  }
318
396
  ],
397
+ // The three auth hooks, all pure HTTP against Klaviyo — which is why they
398
+ // live here rather than in sync. A vendor's own protocol belongs beside the
399
+ // vendor.
400
+ hooks: {
401
+ // Turn a fresh grant into settings worth showing. Without this the card
402
+ // renders an empty "Klaviyo account" field, because the merchant is never
403
+ // asked which account they connected — the consent already decided it and
404
+ // asking again would be a question we can answer ourselves.
405
+ "auth.connect": async ({ fetcher, tokens }) => {
406
+ var _a, _b, _c;
407
+ const body = await api("/accounts", { fetcher, token: tokens.accessToken });
408
+ const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
409
+ return {
410
+ account: ((_c = (_b = account == null ? void 0 : account.attributes) == null ? void 0 : _b.contact_information) == null ? void 0 : _c.organization_name) || (account == null ? void 0 : account.id) || null,
411
+ accountId: (account == null ? void 0 : account.id) || null
412
+ };
413
+ },
414
+ // Revoke at KLAVIYO, not just locally. Forgetting our copy leaves the
415
+ // grant live in the merchant's account, so a disconnect that looks
416
+ // complete here still shows Drawbridge with access over there.
417
+ //
418
+ // Basic auth with our client, exactly like the token exchange — the token
419
+ // being revoked is the subject, not the credential.
420
+ "auth.disconnect": async ({ clientId, clientSecret, fetcher = fetch, settings }) => {
421
+ const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
422
+ if (!token) return { revoked: false };
423
+ const response = await fetcher("https://a.klaviyo.com/oauth/revoke", {
424
+ body: new URLSearchParams({
425
+ token,
426
+ token_type_hint: (settings == null ? void 0 : settings.refreshToken) ? "refresh_token" : "access_token"
427
+ }),
428
+ headers: {
429
+ authorization: "Basic " + Buffer.from(clientId + ":" + clientSecret).toString("base64"),
430
+ "content-type": "application/x-www-form-urlencoded"
431
+ },
432
+ method: "POST",
433
+ signal: AbortSignal.timeout(15e3)
434
+ });
435
+ return { revoked: response.ok };
436
+ },
437
+ // THE MINT IS THE PROBE. Asking "is this token still good" by inspecting
438
+ // what we stored answers the wrong question — a grant revoked inside
439
+ // Klaviyo still looks perfect in our database. Spending the refresh token
440
+ // is the only thing that asks Klaviyo.
441
+ //
442
+ // It also keeps the grant warm: Klaviyo expires a refresh token after 90
443
+ // days of NON-USE, so a connection nobody touches dies silently without
444
+ // this running.
445
+ "auth.probe": async ({ clientId, clientSecret, fetcher, manifest, settings }) => {
446
+ const token = await accessToken({
447
+ clientId,
448
+ clientSecret,
449
+ fetcher,
450
+ // Mint even if the stored token still looks good — a probe that
451
+ // short-circuits never reaches Klaviyo and reports healthy on a
452
+ // grant revoked an hour ago.
453
+ force: true,
454
+ manifest,
455
+ settings
456
+ });
457
+ return { ok: Boolean(token) };
458
+ }
459
+ },
319
460
  icon: klaviyo_default,
461
+ // A grant with no list chosen is authenticated and useless. The list cannot
462
+ // be part of the consent flow — enumerating lists needs the token the consent
463
+ // returns — so it is always a second step, and the card must say so rather
464
+ // than showing Active over nothing.
465
+ incomplete: (data) => {
466
+ var _a;
467
+ return ((_a = data == null ? void 0 : data.settings) == null ? void 0 : _a.list) ? null : "Choose which Klaviyo list your contacts should sync into.";
468
+ },
320
469
  label: "klaviyo",
321
470
  requires: [
322
471
  "KLAVIYO_OAUTH_CLIENT_ID",
@@ -352,6 +501,16 @@ var klaviyo_default2 = {
352
501
  "lifecycle.register": false,
353
502
  "lifecycle.rehydrate": false
354
503
  },
504
+ tasks: () => [
505
+ // Mailchimp carries the same warning, deliberately worded the same way. A
506
+ // merchant who connects either one and is told nothing reasonably assumes
507
+ // contacts are flowing, and finds out weeks later that they are not.
508
+ {
509
+ message: "Contact syncing to Klaviyo lists has not shipped yet. Connecting stores your authorization so it is ready, but nothing is being sent to Klaviyo right now.",
510
+ title: "List sync not available yet",
511
+ type: "warning"
512
+ }
513
+ ],
355
514
  title: "Klaviyo"
356
515
  };
357
516
 
@@ -403,6 +562,15 @@ var mailchimp_default2 = {
403
562
  }
404
563
  ],
405
564
  icon: mailchimp_default,
565
+ // A key with no audience chosen is authenticated and inert. Mailchimp also
566
+ // needs its merge fields created on that audience before any Drawbridge total
567
+ // can be written to a member — unlike Klaviyo, its custom fields are not
568
+ // schemaless — so the audience must be picked before lifecycle.register has
569
+ // anything to register against.
570
+ incomplete: (data) => {
571
+ var _a;
572
+ return ((_a = data == null ? void 0 : data.settings) == null ? void 0 : _a.audience) ? null : "Choose which Mailchimp audience your contacts should sync into.";
573
+ },
406
574
  label: "mailchimp",
407
575
  // Uniform surface, honest answers. A key is stored and can be removed; nothing
408
576
  // else is built yet, because audience sync has not shipped. Every false here
@@ -532,16 +700,21 @@ var shopify_default2 = {
532
700
  }
533
701
  ],
534
702
  group: "ecommerce",
703
+ // The install is the whole configuration — Shopify hands back the shop and
704
+ // there is nothing further to choose. `shop` absent means the install did not
705
+ // finish, which is a credential problem rather than a setup one, so the
706
+ // stored status already says so.
707
+ incomplete: () => null,
535
708
  // verify and event lean entirely on the shared HMAC helper — Shopify's scheme
536
709
  // is exactly the shape it covers, so there is nothing vendor-specific to
537
710
  // write for either. receive is the one hook that genuinely differs by
538
- // action: /events buffers whatever arrives with the shop domain stamped on;
711
+ // channel: /events buffers whatever arrives with the shop domain stamped on;
539
712
  // /compliance enforces the topic allowlist above, because answering one late
540
713
  // is a legal deadline rather than a retry.
541
714
  hooks: {
542
715
  "inbound.event": (args) => readEventHeader({ ...args, descriptor: inbound }),
543
- "inbound.receive": ({ action, event, headers, payload }) => {
544
- if (action === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
716
+ "inbound.receive": ({ channel, event, headers, payload }) => {
717
+ if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
545
718
  throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
546
719
  }
547
720
  return {
@@ -549,7 +722,7 @@ var shopify_default2 = {
549
722
  // own GDPR shape. The app-level event stream does not; that domain
550
723
  // lives only in the header, so it is stamped on here rather than left
551
724
  // for drawbridge-sync to reach into headers nobody hands it.
552
- data: action === "compliance" ? payload : { ...payload, shop_domain: headers[inbound.headers.shop] || null },
725
+ data: channel === "compliance" ? payload : { ...payload, shop_domain: headers[inbound.headers.shop] || null },
553
726
  provider: { id: headers[inbound.headers.id] || null }
554
727
  };
555
728
  },
@@ -731,6 +904,9 @@ var webhook_default = {
731
904
  // It is the one card that reads wrong — our logo among vendor logos — and it
732
905
  // wants a mark of its own when there is one.
733
906
  icon: drawbridge_default,
907
+ // The destination url is supplied per step, not per connection, so there is
908
+ // nothing to finish here — generating the secret IS connecting.
909
+ incomplete: () => null,
734
910
  label: "webhook",
735
911
  // Gated on the encryption secret: without it the signing secret could not be
736
912
  // stored safely, so the connection must not be offered at all.
@@ -838,6 +1014,11 @@ var build = (manifest) => {
838
1014
  throw new Error(manifest.slug + " is oauth and must declare auth.oauth." + field);
839
1015
  }
840
1016
  }
1017
+ if (manifest.auth.oauth.redirect !== "/api/connection/" + manifest.slug + "/callback") {
1018
+ throw new Error(
1019
+ manifest.slug + " declares auth.oauth.redirect " + manifest.auth.oauth.redirect + " but the only callback route is /api/connection/" + manifest.slug + "/callback"
1020
+ );
1021
+ }
841
1022
  }
842
1023
  if (((_d = manifest.supports) == null ? void 0 : _d["inbound.event"]) && !((_f = (_e = manifest.inbound) == null ? void 0 : _e.headers) == null ? void 0 : _f.event)) {
843
1024
  throw new Error(manifest.slug + " supports inbound.event but declares no inbound.headers.event");
@@ -845,6 +1026,9 @@ var build = (manifest) => {
845
1026
  if (((_g = manifest.supports) == null ? void 0 : _g["inbound.verify"]) && !((_i = (_h = manifest.inbound) == null ? void 0 : _h.headers) == null ? void 0 : _i.signature)) {
846
1027
  throw new Error(manifest.slug + " supports inbound.verify but declares no inbound.headers.signature");
847
1028
  }
1029
+ if (typeof (manifest == null ? void 0 : manifest.incomplete) !== "function") {
1030
+ throw new Error(manifest.slug + " must declare incomplete( data ) \u2014 return null when the connection is usable, or the reason it is not");
1031
+ }
848
1032
  if (!Array.isArray(manifest == null ? void 0 : manifest.setup) || !manifest.setup.length) {
849
1033
  throw new Error(manifest.slug + " needs a setup guide \u2014 an array of steps for its page");
850
1034
  }
@@ -994,6 +1178,9 @@ var publicConnectionKeys = Object.freeze([
994
1178
  "group",
995
1179
  "id",
996
1180
  "image",
1181
+ // The reason a connected vendor still is not usable — a Klaviyo grant with no
1182
+ // list chosen. Public because the card that shows Pending has to say why.
1183
+ "incomplete",
997
1184
  "label",
998
1185
  "setup",
999
1186
  "settings",
@@ -1036,6 +1223,7 @@ var resolveConnection = (item, data) => {
1036
1223
  INPUTS,
1037
1224
  OAUTH_FIELDS,
1038
1225
  OUTCOMES,
1226
+ accessToken,
1039
1227
  availableConnections,
1040
1228
  build,
1041
1229
  connectFields,
@@ -1044,6 +1232,7 @@ var resolveConnection = (item, data) => {
1044
1232
  consentUrl,
1045
1233
  exchange,
1046
1234
  hookSupport,
1235
+ isStale,
1047
1236
  mergeSettings,
1048
1237
  pkcePair,
1049
1238
  projectConnection,
@@ -1054,5 +1243,6 @@ var resolveConnection = (item, data) => {
1054
1243
  resolveConnection,
1055
1244
  runHook,
1056
1245
  scopesMessage,
1057
- stepQueues
1246
+ stepQueues,
1247
+ tokenSettings
1058
1248
  });