@drawbridge/drawbridge-utils 0.0.67 → 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/shopify.d.ts DELETED
@@ -1,259 +0,0 @@
1
- import crypto from 'crypto';
2
- import { decrypt, encrypt } from './encrypt.js';
3
- import './token.js';
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 };
package/dist/shopify.js DELETED
@@ -1,213 +0,0 @@
1
- // lib/shopify.js
2
- import crypto3 from "crypto";
3
-
4
- // lib/encrypt.js
5
- import crypto2 from "crypto";
6
-
7
- // lib/token.js
8
- import crypto from "crypto";
9
- var generate = (bytes = 32, encoding = "base64url") => {
10
- const buf = crypto.randomBytes(bytes);
11
- return encoding ? buf.toString(encoding) : buf;
12
- };
13
-
14
- // lib/encrypt.js
15
- var ALGORITHM = "aes-256-gcm";
16
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
17
- var encrypt = (value) => {
18
- const iv = generate(12, null);
19
- const cipher = crypto2.createCipheriv(ALGORITHM, getKey(), iv);
20
- const data = Buffer.concat([
21
- cipher.update(JSON.stringify(value), "utf8"),
22
- cipher.final()
23
- ]);
24
- const tag = cipher.getAuthTag();
25
- return [iv, tag, data].map((b) => b.toString("hex")).join(":");
26
- };
27
- var decrypt = (value) => {
28
- if (typeof value !== "string") return value;
29
- const [ivHex, tagHex, dataHex] = value.split(":");
30
- const decipher = crypto2.createDecipheriv(
31
- ALGORITHM,
32
- getKey(),
33
- Buffer.from(ivHex, "hex")
34
- );
35
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
36
- const result = Buffer.concat([
37
- decipher.update(Buffer.from(dataHex, "hex")),
38
- decipher.final()
39
- ]);
40
- return JSON.parse(result.toString("utf8"));
41
- };
42
-
43
- // lib/shopify.js
44
- var SHOPIFY_ADMIN_API_VERSION = "2025-01";
45
- var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
46
- var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
47
- var OAUTH_STATE_TTL_MS = 5 * 60 * 1e3;
48
- var signOAuthState = ({ organizationId, shop }) => {
49
- const payload = Buffer.from(JSON.stringify({
50
- exp: Date.now() + OAUTH_STATE_TTL_MS,
51
- organizationId,
52
- shop
53
- })).toString("base64url");
54
- const signature = crypto3.createHmac("sha256", process.env.SHOPIFY_API_SECRET).update(payload).digest("base64url");
55
- return payload + "." + signature;
56
- };
57
- var verifyOAuthState = (raw) => {
58
- if (!raw) return null;
59
- const [payload, signature] = raw.split(".");
60
- if (!payload || !signature) return null;
61
- const expected = crypto3.createHmac("sha256", process.env.SHOPIFY_API_SECRET).update(payload).digest("base64url");
62
- if (signature.length !== expected.length) return null;
63
- const valid = crypto3.timingSafeEqual(
64
- Buffer.from(signature),
65
- Buffer.from(expected)
66
- );
67
- if (!valid) return null;
68
- let parsed;
69
- try {
70
- parsed = JSON.parse(Buffer.from(payload, "base64url").toString());
71
- } catch {
72
- return null;
73
- }
74
- ;
75
- if (!(parsed == null ? void 0 : parsed.exp) || parsed.exp < Date.now()) return null;
76
- return parsed;
77
- };
78
- var verifyOAuthCallbackHmac = ({ hmac, rawQuery }) => {
79
- const message = (rawQuery || "").split("&").filter((pair) => !pair.startsWith("hmac=")).sort((a, b) => {
80
- const nameA = a.split("=")[0];
81
- const nameB = b.split("=")[0];
82
- return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
83
- }).join("&");
84
- const digest = crypto3.createHmac("sha256", process.env.SHOPIFY_API_SECRET).update(message).digest("hex");
85
- const digestBuf = Buffer.from(digest);
86
- const hmacBuf = Buffer.from(hmac || "");
87
- return digestBuf.length === hmacBuf.length && crypto3.timingSafeEqual(digestBuf, hmacBuf);
88
- };
89
- var shopifyOAuthFetch = async (url, body) => {
90
- const response = await fetch(url, {
91
- method: "POST",
92
- headers: {
93
- "Content-Type": "application/json"
94
- },
95
- body: JSON.stringify(body)
96
- });
97
- if (!response.ok) {
98
- const text = await response.text().catch(() => "");
99
- const error = new Error(response.status + ": " + text);
100
- error.status = response.status;
101
- throw error;
102
- }
103
- return response.json();
104
- };
105
- var ping = async ({ adminAccessToken, domain }) => {
106
- const response = await fetch(
107
- `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/shop.json`,
108
- {
109
- headers: {
110
- "X-Shopify-Access-Token": adminAccessToken
111
- }
112
- }
113
- );
114
- if (!response.ok) {
115
- const text = await response.text().catch(() => "");
116
- const error = new Error(response.status + ": " + text);
117
- error.status = response.status;
118
- throw error;
119
- }
120
- };
121
- var resolveConnectionSettings = async ({ connection, controller }) => {
122
- const connectionSettings = (connection == null ? void 0 : connection.settings) ? decrypt(connection.settings) : {};
123
- if (!(connection == null ? void 0 : connection.credential)) {
124
- return connectionSettings;
125
- }
126
- const credential = await controller.get({
127
- collection: "credential",
128
- query: {
129
- id: connection.credential
130
- }
131
- });
132
- const credentialSettings = (credential == null ? void 0 : credential.settings) ? decrypt(credential.settings) : {};
133
- return {
134
- ...credentialSettings,
135
- ...connectionSettings
136
- };
137
- };
138
- var refreshAdminToken = async ({ connection, controller }) => {
139
- var _a;
140
- const credential = await controller.get({
141
- collection: "credential",
142
- query: {
143
- id: connection.credential
144
- }
145
- });
146
- if (!credential) {
147
- throw new Error("refreshAdminToken: credential not found for connection " + connection.id);
148
- }
149
- ;
150
- const settings = decrypt(credential.settings);
151
- const domain = (_a = credential.provider) == null ? void 0 : _a.id;
152
- const { refreshToken } = settings;
153
- const data = await shopifyOAuthFetch(
154
- `https://${domain}/admin/oauth/access_token`,
155
- {
156
- grant_type: "refresh_token",
157
- client_id: process.env.SHOPIFY_API_KEY,
158
- client_secret: process.env.SHOPIFY_API_SECRET,
159
- refresh_token: refreshToken
160
- }
161
- );
162
- const adminAccessToken = data.access_token;
163
- const newRefreshToken = data.refresh_token;
164
- const expiresIn = data.expires_in;
165
- const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
166
- const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
167
- await ping({ adminAccessToken, domain });
168
- await controller.update({
169
- collection: "credential",
170
- data: {
171
- $set: {
172
- settings: encrypt({
173
- ...settings,
174
- adminAccessToken,
175
- refreshToken: newRefreshToken,
176
- refreshTokenExpiresAt,
177
- tokenExpiresAt
178
- })
179
- }
180
- },
181
- query: {
182
- id: credential.id
183
- }
184
- });
185
- return adminAccessToken;
186
- };
187
- var getAdminToken = async ({ connection, controller }) => {
188
- if (!(connection == null ? void 0 : connection.credential)) {
189
- return null;
190
- }
191
- ;
192
- const settings = await resolveConnectionSettings({ connection, controller });
193
- const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
194
- if (!refreshToken) {
195
- return adminAccessToken;
196
- }
197
- ;
198
- const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
199
- if (needsRefresh) {
200
- return refreshAdminToken({ connection, controller });
201
- }
202
- ;
203
- return adminAccessToken;
204
- };
205
- export {
206
- getAdminToken,
207
- ping,
208
- refreshAdminToken,
209
- resolveConnectionSettings,
210
- signOAuthState,
211
- verifyOAuthCallbackHmac,
212
- verifyOAuthState
213
- };