@drawbridge/drawbridge-utils 0.0.66 → 0.0.68

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/dist/usage.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- // Usage helpers — the per-org `usage` doc totals and the append-only `action`
2
- // ledger. These are the low-level usage primitives; billing.action.* (lib/
3
- // billing.js) is the public surface. Kept separate from billing so the generic
4
- // usage-totals $inc (used for non-billing totals like revenue/submissions/
5
- // entries too) doesn't live under the billing namespace. Re-exported from
6
- // index.js for backward compatibility with existing import sites.
1
+ // Usage helpers — the per-org `usage` doc totals $inc and a duplicate-key guard.
2
+ // Generic, non-billing primitives (incrementUsageTotals is used for revenue /
3
+ // submissions / entries totals too), so they live here rather than under the
4
+ // billing namespace; billing.action.record (lib/billing.js) uses both to write
5
+ // the action ledger. Re-exported from index.js for existing import sites.
7
6
 
8
7
  // Centralized $inc helper for the per-org usage doc. Replaces inline
9
8
  // $inc-with-bypass-validation patterns in drawbridge-api + drawbridge-sync.
@@ -49,81 +48,4 @@ const isDuplicateKey = ( error ) =>
49
48
  || error?.code === '11000'
50
49
  || /E11000|duplicate key/i.test( error?.message || '' );
51
50
 
52
- // Record a billable action as a row in the append-only `action` ledger — the
53
- // source of truth for usage billing (summed per period at changeover).
54
- //
55
- // Idempotent via an UPSERT on the unique { usage, key }: a duplicate event (the
56
- // segment realtime path AND the sweep firing for the same membership, or a retry)
57
- // matches the existing row and no-ops — no duplicate-key error — so this is safe
58
- // to call INSIDE a caller's transaction (a thrown E11000 would abort the whole
59
- // transaction). The display cache `usage.totals.actions` is bumped ONLY when the
60
- // upsert actually inserts a new row, so a duplicate never double-counts.
61
- //
62
- // Pass `session` to make the ledger row + cache bump atomic with the caller's own
63
- // writes (e.g. the membership writes in a segment-sweep chunk, or the submission
64
- // docs) — all-or-nothing. Without a session it runs standalone.
65
- // key deterministic per source event, e.g. 'segment.join:<contact>:<segment>'
66
- // units billable units (default 1; N for batch, e.g. accepted entries)
67
- // meta attribution ids { campaign, page, submission, segment, workflow, step, ... }
68
- const recordAction = async ({ controller, organization, usageId, type, units = 1, key, meta = {}, traceId, session }) => {
69
-
70
- if( ! controller || ! organization || ! usageId || ! type || ! key ) return;
71
-
72
- const amount = Number( units );
73
-
74
- if( ! Number.isFinite( amount ) || amount === 0 ) return;
75
-
76
- let inserted = false;
77
-
78
- try {
79
-
80
- const { lastErrorObject } = await controller.update({
81
- collection : 'action',
82
- data : {
83
- $setOnInsert : {
84
- organization,
85
- usage : usageId,
86
- type,
87
- units : amount,
88
- key,
89
- meta,
90
- ...( traceId && { traceId })
91
- }
92
- },
93
- options : {
94
- bypassDocumentValidation : true,
95
- includeResultMetadata : true,
96
- upsert : true,
97
- ...( session && { session })
98
- },
99
- query : {
100
- key,
101
- usage : usageId
102
- }
103
- });
104
-
105
- inserted = Boolean( lastErrorObject?.upserted );
106
-
107
- } catch ( error ) {
108
-
109
- // A concurrent upsert of the same { usage, key } can still race to E11000.
110
- // Standalone: the other writer recorded it — skip. Inside a transaction:
111
- // the txn is already aborted, so re-throw to let the caller retry the whole
112
- // unit (which then sees the row and no-ops).
113
- if( isDuplicateKey( error ) && ! session ) return;
114
-
115
- throw error;
116
-
117
- }
118
-
119
- // Only a genuinely new row bumps the display cache (a matched duplicate must
120
- // not double-count). Joined to the caller's transaction when a session is given.
121
- if( inserted ){
122
-
123
- await incrementUsageTotals({ controller, usageId, $inc : { 'totals.actions' : amount }, session });
124
-
125
- }
126
-
127
- };
128
-
129
- export { incrementUsageTotals, isDuplicateKey, recordAction };
51
+ export { incrementUsageTotals, isDuplicateKey };
package/dist/usage.js CHANGED
@@ -19,47 +19,7 @@ var incrementUsageTotals = async ({ controller, usageId, $inc, session }) => {
19
19
  });
20
20
  };
21
21
  var isDuplicateKey = (error) => (error == null ? void 0 : error.code) === 11e3 || (error == null ? void 0 : error.code) === "11000" || /E11000|duplicate key/i.test((error == null ? void 0 : error.message) || "");
22
- var recordAction = async ({ controller, organization, usageId, type, units = 1, key, meta = {}, traceId, session }) => {
23
- if (!controller || !organization || !usageId || !type || !key) return;
24
- const amount = Number(units);
25
- if (!Number.isFinite(amount) || amount === 0) return;
26
- let inserted = false;
27
- try {
28
- const { lastErrorObject } = await controller.update({
29
- collection: "action",
30
- data: {
31
- $setOnInsert: {
32
- organization,
33
- usage: usageId,
34
- type,
35
- units: amount,
36
- key,
37
- meta,
38
- ...traceId && { traceId }
39
- }
40
- },
41
- options: {
42
- bypassDocumentValidation: true,
43
- includeResultMetadata: true,
44
- upsert: true,
45
- ...session && { session }
46
- },
47
- query: {
48
- key,
49
- usage: usageId
50
- }
51
- });
52
- inserted = Boolean(lastErrorObject == null ? void 0 : lastErrorObject.upserted);
53
- } catch (error) {
54
- if (isDuplicateKey(error) && !session) return;
55
- throw error;
56
- }
57
- if (inserted) {
58
- await incrementUsageTotals({ controller, usageId, $inc: { "totals.actions": amount }, session });
59
- }
60
- };
61
22
  export {
62
23
  incrementUsageTotals,
63
- isDuplicateKey,
64
- recordAction
24
+ isDuplicateKey
65
25
  };
package/package.json CHANGED
@@ -122,11 +122,6 @@
122
122
  "import": "./dist/http.js",
123
123
  "require": "./dist/http.cjs"
124
124
  },
125
- "./shopify": {
126
- "types": "./dist/shopify.d.ts",
127
- "import": "./dist/shopify.js",
128
- "require": "./dist/shopify.cjs"
129
- },
130
125
  "./slugify": {
131
126
  "types": "./dist/slugify.d.ts",
132
127
  "import": "./dist/slugify.js",
@@ -137,11 +132,6 @@
137
132
  "import": "./dist/token.js",
138
133
  "require": "./dist/token.cjs"
139
134
  },
140
- "./transactions": {
141
- "types": "./dist/transactions.d.ts",
142
- "import": "./dist/transactions.js",
143
- "require": "./dist/transactions.cjs"
144
- },
145
135
  "./features": {
146
136
  "types": "./dist/features.d.ts",
147
137
  "import": "./dist/features.js",
@@ -168,5 +158,5 @@
168
158
  "build": "tsup && npm publish"
169
159
  },
170
160
  "types": "dist/index.d.ts",
171
- "version": "0.0.66"
161
+ "version": "0.0.68"
172
162
  }
package/dist/shopify.cjs DELETED
@@ -1,253 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // lib/shopify.js
30
- var shopify_exports = {};
31
- __export(shopify_exports, {
32
- getAdminToken: () => getAdminToken,
33
- ping: () => ping,
34
- refreshAdminToken: () => refreshAdminToken,
35
- resolveConnectionSettings: () => resolveConnectionSettings,
36
- signOAuthState: () => signOAuthState,
37
- verifyOAuthCallbackHmac: () => verifyOAuthCallbackHmac,
38
- verifyOAuthState: () => verifyOAuthState
39
- });
40
- module.exports = __toCommonJS(shopify_exports);
41
- var import_crypto3 = __toESM(require("crypto"), 1);
42
-
43
- // lib/encrypt.js
44
- var import_crypto2 = __toESM(require("crypto"), 1);
45
-
46
- // lib/token.js
47
- var import_crypto = __toESM(require("crypto"), 1);
48
- var generate = (bytes = 32, encoding = "base64url") => {
49
- const buf = import_crypto.default.randomBytes(bytes);
50
- return encoding ? buf.toString(encoding) : buf;
51
- };
52
-
53
- // lib/encrypt.js
54
- var ALGORITHM = "aes-256-gcm";
55
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
56
- var encrypt = (value) => {
57
- const iv = generate(12, null);
58
- const cipher = import_crypto2.default.createCipheriv(ALGORITHM, getKey(), iv);
59
- const data = Buffer.concat([
60
- cipher.update(JSON.stringify(value), "utf8"),
61
- cipher.final()
62
- ]);
63
- const tag = cipher.getAuthTag();
64
- return [iv, tag, data].map((b) => b.toString("hex")).join(":");
65
- };
66
- var decrypt = (value) => {
67
- if (typeof value !== "string") return value;
68
- const [ivHex, tagHex, dataHex] = value.split(":");
69
- const decipher = import_crypto2.default.createDecipheriv(
70
- ALGORITHM,
71
- getKey(),
72
- Buffer.from(ivHex, "hex")
73
- );
74
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
75
- const result = Buffer.concat([
76
- decipher.update(Buffer.from(dataHex, "hex")),
77
- decipher.final()
78
- ]);
79
- return JSON.parse(result.toString("utf8"));
80
- };
81
-
82
- // lib/shopify.js
83
- var SHOPIFY_ADMIN_API_VERSION = "2025-01";
84
- var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
85
- var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
86
- var OAUTH_STATE_TTL_MS = 5 * 60 * 1e3;
87
- var signOAuthState = ({ organizationId, shop }) => {
88
- const payload = Buffer.from(JSON.stringify({
89
- exp: Date.now() + OAUTH_STATE_TTL_MS,
90
- organizationId,
91
- shop
92
- })).toString("base64url");
93
- const signature = import_crypto3.default.createHmac("sha256", process.env.SHOPIFY_API_SECRET).update(payload).digest("base64url");
94
- return payload + "." + signature;
95
- };
96
- var verifyOAuthState = (raw) => {
97
- if (!raw) return null;
98
- const [payload, signature] = raw.split(".");
99
- if (!payload || !signature) return null;
100
- const expected = import_crypto3.default.createHmac("sha256", process.env.SHOPIFY_API_SECRET).update(payload).digest("base64url");
101
- if (signature.length !== expected.length) return null;
102
- const valid = import_crypto3.default.timingSafeEqual(
103
- Buffer.from(signature),
104
- Buffer.from(expected)
105
- );
106
- if (!valid) return null;
107
- let parsed;
108
- try {
109
- parsed = JSON.parse(Buffer.from(payload, "base64url").toString());
110
- } catch {
111
- return null;
112
- }
113
- ;
114
- if (!(parsed == null ? void 0 : parsed.exp) || parsed.exp < Date.now()) return null;
115
- return parsed;
116
- };
117
- var verifyOAuthCallbackHmac = ({ hmac, rawQuery }) => {
118
- const message = (rawQuery || "").split("&").filter((pair) => !pair.startsWith("hmac=")).sort((a, b) => {
119
- const nameA = a.split("=")[0];
120
- const nameB = b.split("=")[0];
121
- return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
122
- }).join("&");
123
- const digest = import_crypto3.default.createHmac("sha256", process.env.SHOPIFY_API_SECRET).update(message).digest("hex");
124
- const digestBuf = Buffer.from(digest);
125
- const hmacBuf = Buffer.from(hmac || "");
126
- return digestBuf.length === hmacBuf.length && import_crypto3.default.timingSafeEqual(digestBuf, hmacBuf);
127
- };
128
- var shopifyOAuthFetch = async (url, body) => {
129
- const response = await fetch(url, {
130
- method: "POST",
131
- headers: {
132
- "Content-Type": "application/json"
133
- },
134
- body: JSON.stringify(body)
135
- });
136
- if (!response.ok) {
137
- const text = await response.text().catch(() => "");
138
- const error = new Error(response.status + ": " + text);
139
- error.status = response.status;
140
- throw error;
141
- }
142
- return response.json();
143
- };
144
- var ping = async ({ adminAccessToken, domain }) => {
145
- const response = await fetch(
146
- `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/shop.json`,
147
- {
148
- headers: {
149
- "X-Shopify-Access-Token": adminAccessToken
150
- }
151
- }
152
- );
153
- if (!response.ok) {
154
- const text = await response.text().catch(() => "");
155
- const error = new Error(response.status + ": " + text);
156
- error.status = response.status;
157
- throw error;
158
- }
159
- };
160
- var resolveConnectionSettings = async ({ connection, controller }) => {
161
- const connectionSettings = (connection == null ? void 0 : connection.settings) ? decrypt(connection.settings) : {};
162
- if (!(connection == null ? void 0 : connection.credential)) {
163
- return connectionSettings;
164
- }
165
- const credential = await controller.get({
166
- collection: "credential",
167
- query: {
168
- id: connection.credential
169
- }
170
- });
171
- const credentialSettings = (credential == null ? void 0 : credential.settings) ? decrypt(credential.settings) : {};
172
- return {
173
- ...credentialSettings,
174
- ...connectionSettings
175
- };
176
- };
177
- var refreshAdminToken = async ({ connection, controller }) => {
178
- var _a;
179
- const credential = await controller.get({
180
- collection: "credential",
181
- query: {
182
- id: connection.credential
183
- }
184
- });
185
- if (!credential) {
186
- throw new Error("refreshAdminToken: credential not found for connection " + connection.id);
187
- }
188
- ;
189
- const settings = decrypt(credential.settings);
190
- const domain = (_a = credential.provider) == null ? void 0 : _a.id;
191
- const { refreshToken } = settings;
192
- const data = await shopifyOAuthFetch(
193
- `https://${domain}/admin/oauth/access_token`,
194
- {
195
- grant_type: "refresh_token",
196
- client_id: process.env.SHOPIFY_API_KEY,
197
- client_secret: process.env.SHOPIFY_API_SECRET,
198
- refresh_token: refreshToken
199
- }
200
- );
201
- const adminAccessToken = data.access_token;
202
- const newRefreshToken = data.refresh_token;
203
- const expiresIn = data.expires_in;
204
- const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
205
- const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
206
- await ping({ adminAccessToken, domain });
207
- await controller.update({
208
- collection: "credential",
209
- data: {
210
- $set: {
211
- settings: encrypt({
212
- ...settings,
213
- adminAccessToken,
214
- refreshToken: newRefreshToken,
215
- refreshTokenExpiresAt,
216
- tokenExpiresAt
217
- })
218
- }
219
- },
220
- query: {
221
- id: credential.id
222
- }
223
- });
224
- return adminAccessToken;
225
- };
226
- var getAdminToken = async ({ connection, controller }) => {
227
- if (!(connection == null ? void 0 : connection.credential)) {
228
- return null;
229
- }
230
- ;
231
- const settings = await resolveConnectionSettings({ connection, controller });
232
- const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
233
- if (!refreshToken) {
234
- return adminAccessToken;
235
- }
236
- ;
237
- const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
238
- if (needsRefresh) {
239
- return refreshAdminToken({ connection, controller });
240
- }
241
- ;
242
- return adminAccessToken;
243
- };
244
- // Annotate the CommonJS export names for ESM import in node:
245
- 0 && (module.exports = {
246
- getAdminToken,
247
- ping,
248
- refreshAdminToken,
249
- resolveConnectionSettings,
250
- signOAuthState,
251
- verifyOAuthCallbackHmac,
252
- verifyOAuthState
253
- });
@@ -1,259 +0,0 @@
1
- import crypto from 'crypto';
2
- import { decrypt, encrypt } from './encrypt.cjs';
3
- import './token.cjs';
4
-
5
- const SHOPIFY_ADMIN_API_VERSION = '2025-01';
6
- const REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1000;
7
- const ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1000;
8
- const OAUTH_STATE_TTL_MS = 5 * 60 * 1000;
9
-
10
- const signOAuthState = ({ organizationId, shop }) => {
11
-
12
- const payload = Buffer.from( JSON.stringify({
13
- exp : Date.now() + OAUTH_STATE_TTL_MS,
14
- organizationId,
15
- shop
16
- }) ).toString( 'base64url' );
17
-
18
- const signature = crypto
19
- .createHmac( 'sha256', process.env.SHOPIFY_API_SECRET )
20
- .update( payload )
21
- .digest( 'base64url' );
22
-
23
- return payload + '.' + signature;
24
-
25
- };
26
-
27
- const verifyOAuthState = ( raw ) => {
28
-
29
- if( ! raw ) return null;
30
-
31
- const [ payload, signature ] = raw.split( '.' );
32
-
33
- if( ! payload || ! signature ) return null;
34
-
35
- const expected = crypto
36
- .createHmac( 'sha256', process.env.SHOPIFY_API_SECRET )
37
- .update( payload )
38
- .digest( 'base64url' );
39
-
40
- if( signature.length !== expected.length ) return null;
41
-
42
- const valid = crypto.timingSafeEqual(
43
- Buffer.from( signature ),
44
- Buffer.from( expected )
45
- );
46
-
47
- if( ! valid ) return null;
48
-
49
- let parsed;
50
-
51
- try {
52
-
53
- parsed = JSON.parse( Buffer.from( payload, 'base64url' ).toString() );
54
-
55
- } catch {
56
-
57
- return null;
58
-
59
- }
60
- if( ! parsed?.exp || parsed.exp < Date.now() ) return null;
61
-
62
- return parsed;
63
-
64
- };
65
-
66
- // Verifies the HMAC Shopify includes on OAuth callback query strings. Sort by
67
- // parameter NAME (not full key=value pair) per Shopify spec — matches the
68
- // official @shopify/shopify-api SDK. A plain .sort() compares whole strings,
69
- // which would diverge when one name is a prefix of another and the next char
70
- // sorts before '=' in ASCII (e.g. `state` vs `state2`).
71
- const verifyOAuthCallbackHmac = ({ hmac, rawQuery }) => {
72
-
73
- const message = ( rawQuery || '' )
74
- .split( '&' )
75
- .filter( pair => ! pair.startsWith( 'hmac=' ) )
76
- .sort( ( a, b ) => {
77
-
78
- const nameA = a.split( '=' )[ 0 ];
79
- const nameB = b.split( '=' )[ 0 ];
80
-
81
- return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
82
-
83
- })
84
- .join( '&' );
85
-
86
- const digest = crypto
87
- .createHmac( 'sha256', process.env.SHOPIFY_API_SECRET )
88
- .update( message )
89
- .digest( 'hex' );
90
-
91
- const digestBuf = Buffer.from( digest );
92
- const hmacBuf = Buffer.from( hmac || '' );
93
-
94
- return digestBuf.length === hmacBuf.length
95
- && crypto.timingSafeEqual( digestBuf, hmacBuf );
96
-
97
- };
98
-
99
- const shopifyOAuthFetch = async ( url, body ) => {
100
-
101
- const response = await fetch( url, {
102
- method : 'POST',
103
- headers : {
104
- 'Content-Type' : 'application/json'
105
- },
106
- body : JSON.stringify( body )
107
- });
108
-
109
- if( ! response.ok ){
110
-
111
- const text = await response.text().catch( () => '' );
112
- const error = new Error( response.status + ': ' + text );
113
-
114
- error.status = response.status;
115
-
116
- throw error;
117
-
118
- }
119
-
120
- return response.json();
121
-
122
- };
123
-
124
- const ping = async ({ adminAccessToken, domain }) => {
125
-
126
- const response = await fetch(
127
- `https://${ domain }/admin/api/${ SHOPIFY_ADMIN_API_VERSION }/shop.json`,
128
- {
129
- headers : {
130
- 'X-Shopify-Access-Token' : adminAccessToken
131
- }
132
- }
133
- );
134
-
135
- if( ! response.ok ){
136
-
137
- const text = await response.text().catch( () => '' );
138
- const error = new Error( response.status + ': ' + text );
139
-
140
- error.status = response.status;
141
-
142
- throw error;
143
-
144
- }
145
-
146
- };
147
-
148
- const resolveConnectionSettings = async ({ connection, controller }) => {
149
-
150
- const connectionSettings = connection?.settings ? decrypt( connection.settings ) : {};
151
-
152
- if( ! connection?.credential ){
153
-
154
- return connectionSettings;
155
-
156
- }
157
-
158
- const credential = await controller.get({
159
- collection : 'credential',
160
- query : {
161
- id : connection.credential
162
- }
163
- });
164
-
165
- const credentialSettings = credential?.settings ? decrypt( credential.settings ) : {};
166
-
167
- return {
168
- ...credentialSettings,
169
- ...connectionSettings
170
- };
171
-
172
- };
173
-
174
- const refreshAdminToken = async ({ connection, controller }) => {
175
-
176
- const credential = await controller.get({
177
- collection : 'credential',
178
- query : {
179
- id : connection.credential
180
- }
181
- });
182
-
183
- if( ! credential ){
184
-
185
- throw new Error( 'refreshAdminToken: credential not found for connection ' + connection.id );
186
-
187
- }
188
- const settings = decrypt( credential.settings );
189
- const domain = credential.provider?.id;
190
- const { refreshToken } = settings;
191
-
192
- const data = await shopifyOAuthFetch(
193
- `https://${ domain }/admin/oauth/access_token`,
194
- {
195
- grant_type : 'refresh_token',
196
- client_id : process.env.SHOPIFY_API_KEY,
197
- client_secret : process.env.SHOPIFY_API_SECRET,
198
- refresh_token : refreshToken
199
- }
200
- );
201
-
202
- const adminAccessToken = data.access_token;
203
- const newRefreshToken = data.refresh_token;
204
- const expiresIn = data.expires_in;
205
- const tokenExpiresAt = expiresIn ? new Date( Date.now() + ( expiresIn * 1000 ) ) : null;
206
- const refreshTokenExpiresAt = new Date( Date.now() + REFRESH_TOKEN_LIFETIME_MS );
207
-
208
- await ping({ adminAccessToken, domain });
209
-
210
- await controller.update({
211
- collection : 'credential',
212
- data : {
213
- $set : {
214
- settings : encrypt({
215
- ...settings,
216
- adminAccessToken,
217
- refreshToken : newRefreshToken,
218
- refreshTokenExpiresAt,
219
- tokenExpiresAt
220
- })
221
- }
222
- },
223
- query : {
224
- id : credential.id
225
- }
226
- });
227
-
228
- return adminAccessToken;
229
-
230
- };
231
-
232
- const getAdminToken = async ({ connection, controller }) => {
233
-
234
- if( ! connection?.credential ){
235
-
236
- return null;
237
-
238
- }
239
- const settings = await resolveConnectionSettings({ connection, controller });
240
- const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
241
-
242
- if( ! refreshToken ){
243
-
244
- return adminAccessToken;
245
-
246
- }
247
- const needsRefresh = ! tokenExpiresAt ||
248
- new Date( tokenExpiresAt ) < new Date( Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS );
249
-
250
- if( needsRefresh ){
251
-
252
- return refreshAdminToken({ connection, controller });
253
-
254
- }
255
- return adminAccessToken;
256
-
257
- };
258
-
259
- export { getAdminToken, ping, refreshAdminToken, resolveConnectionSettings, signOAuthState, verifyOAuthCallbackHmac, verifyOAuthState };