@drawbridge/drawbridge-utils 0.0.41 → 0.0.43

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.
Files changed (47) hide show
  1. package/dist/ai.cjs +4 -4
  2. package/dist/ai.js +127 -8
  3. package/dist/axios.cjs +1 -1
  4. package/dist/axios.js +1 -1
  5. package/dist/cdn.cjs +1 -1
  6. package/dist/cdn.js +1 -1
  7. package/dist/circuit.cjs +1 -1
  8. package/dist/circuit.js +50 -3
  9. package/dist/encrypt.cjs +3 -3
  10. package/dist/encrypt.js +38 -5
  11. package/dist/fetch.cjs +1 -1
  12. package/dist/fetch.js +1 -1
  13. package/dist/http.cjs +1 -1
  14. package/dist/http.js +1 -1
  15. package/dist/nanoid.cjs +1 -1
  16. package/dist/nanoid.js +1 -1
  17. package/dist/oauth/index.cjs +196 -0
  18. package/dist/oauth/index.d.cts +231 -0
  19. package/dist/oauth/index.d.ts +231 -0
  20. package/dist/oauth/index.js +151 -0
  21. package/dist/oauth/server.cjs +377 -0
  22. package/dist/oauth/server.d.cts +387 -0
  23. package/dist/oauth/server.d.ts +387 -0
  24. package/dist/oauth/server.js +341 -0
  25. package/dist/orders.cjs +1 -1
  26. package/dist/orders.js +1 -1
  27. package/dist/redirect.cjs +1 -1
  28. package/dist/redirect.js +1 -1
  29. package/dist/shopify.cjs +5 -5
  30. package/dist/shopify.js +46 -11
  31. package/dist/slugify.cjs +1 -1
  32. package/dist/slugify.js +1 -1
  33. package/dist/token.cjs +1 -1
  34. package/dist/token.js +21 -5
  35. package/dist/transactions.cjs +1 -1
  36. package/dist/transactions.js +108 -4
  37. package/dist/upload.cjs +1 -1
  38. package/dist/upload.js +1 -1
  39. package/package.json +20 -4
  40. package/dist/chunk-2DRAIKGZ.js +0 -38
  41. package/dist/chunk-6HH36OK6.js +0 -54
  42. package/dist/chunk-JT2PAZAZ.js +0 -113
  43. package/dist/chunk-OS2AHUWX.js +0 -27
  44. package/dist/oauth.cjs +0 -94
  45. package/dist/oauth.d.cts +0 -129
  46. package/dist/oauth.d.ts +0 -129
  47. package/dist/oauth.js +0 -70
@@ -0,0 +1,231 @@
1
+ import { generate, hash } from '../token.cjs';
2
+ export { compare } from '../token.cjs';
3
+ import 'crypto';
4
+
5
+ // Shared OAuth helpers used across drawbridge-api, drawbridge-sync,
6
+ // drawbridge-app-web, and any first-party app that needs to participate
7
+ // in the OAuth 2.1 provider:
8
+ //
9
+ // - scopes, developer: the locked scope vocabulary
10
+ // - parse, validate, intersect, isDeveloperAllowed: scope set operations
11
+ // - hashToken, generateToken, compare: opaque-token primitives
12
+ // - createOAuthClient: cached client_credentials access token getter
13
+
14
+
15
+ // ─────────────────────────────────────────────────────────────────────────
16
+ // Scope vocabulary (locked — 15 scopes, 10 in the developer-allowed subset)
17
+ // ─────────────────────────────────────────────────────────────────────────
18
+
19
+ const scopes = [
20
+ 'profile:read',
21
+ 'profile:write',
22
+ 'organization:read',
23
+ 'organization:write',
24
+ 'campaigns:read',
25
+ 'campaigns:write',
26
+ 'contacts:read',
27
+ 'contacts:write',
28
+ 'workflows:read',
29
+ 'workflows:write',
30
+ 'connections:read',
31
+ 'connections:write',
32
+ 'billing:read',
33
+ 'billing:write',
34
+ 'admin'
35
+ ];
36
+
37
+ // Subset granted to third-party developer apps via /oauth/clients self-service
38
+ // registration. Excludes profile:write (account-level), organization:write
39
+ // (org admin only), billing:* (financial), admin (privileged).
40
+ const developer = [
41
+ 'profile:read',
42
+ 'organization:read',
43
+ 'campaigns:read',
44
+ 'campaigns:write',
45
+ 'contacts:read',
46
+ 'contacts:write',
47
+ 'workflows:read',
48
+ 'workflows:write',
49
+ 'connections:read',
50
+ 'connections:write'
51
+ ];
52
+
53
+ const parse = ( raw ) => {
54
+
55
+ if( ! raw ) return [];
56
+
57
+ if( Array.isArray( raw ) ) return raw;
58
+
59
+ return String( raw ).split( /\s+/ ).filter( Boolean );
60
+
61
+ };
62
+
63
+ const validate = ( scopes ) => {
64
+
65
+ const parsed = parse( scopes );
66
+ const invalid = parsed.filter( ( scope ) => ! scopes.includes( scope ) );
67
+
68
+ return {
69
+ invalid,
70
+ valid : invalid.length === 0
71
+ };
72
+
73
+ };
74
+
75
+ const intersect = ( requested, allowed ) => {
76
+
77
+ const r = parse( requested );
78
+ const a = parse( allowed );
79
+
80
+ return r.filter( ( scope ) => a.includes( scope ) );
81
+
82
+ };
83
+
84
+ const isDeveloperAllowed = ( scope ) => developer.includes( scope );
85
+
86
+ // ─────────────────────────────────────────────────────────────────────────
87
+ // Token primitives — convenience wrappers over drawbridge-utils/token that
88
+ // fix the OAuth-specific conventions (32 bytes base64url, env-keyed HMAC)
89
+ // ─────────────────────────────────────────────────────────────────────────
90
+
91
+ // Hash an OAuth token with the deployment's HMAC key (OAUTH_TOKEN_HMAC_KEY).
92
+ // Falls back to plain SHA256 if the env var is unset — fine for local dev,
93
+ // not for production (DB compromise would then allow token forgery).
94
+ const hashToken = ( raw ) => hash( raw, process.env.OAUTH_TOKEN_HMAC_KEY );
95
+
96
+ // 32 cryptographically random bytes encoded as a 43-char base64url string —
97
+ // the shape used for access tokens, refresh tokens, PATs, and authorization
98
+ // codes.
99
+ const generateToken = () => generate( 32, 'base64url' );
100
+
101
+ // ─────────────────────────────────────────────────────────────────────────
102
+ // Client_credentials token caching for first-party apps that call
103
+ // drawbridge-api as themselves (drawbridge-share, drawbridge-emails,
104
+ // drawbridge-webhooks, etc.).
105
+ //
106
+ // Caches the access token in process memory; refreshes when nearing expiry
107
+ // or after a 401. Single-flight refresh prevents thundering herd when many
108
+ // concurrent requests arrive while the token is being rotated.
109
+ //
110
+ // Usage:
111
+ // import { createOAuthClient } from '@drawbridge/drawbridge-utils/oauth';
112
+ //
113
+ // const client = createOAuthClient({
114
+ // clientId : process.env.OAUTH_CLIENT_ID,
115
+ // clientSecret : process.env.OAUTH_CLIENT_SECRET,
116
+ // tokenUri : process.env.NEXT_PUBLIC_API_URI + '/oauth/token',
117
+ // scopes : [ 'campaigns:read' ]
118
+ // });
119
+ //
120
+ // await request({ endpoint : '/page/abc', token : await client.token() });
121
+ // ─────────────────────────────────────────────────────────────────────────
122
+
123
+ const REFRESH_LEAD_SECONDS = 60;
124
+
125
+ const createOAuthClient = ({
126
+ clientId,
127
+ clientSecret,
128
+ scopes = [],
129
+ tokenUri
130
+ }) => {
131
+
132
+ if( ! clientId ) throw new Error( 'createOAuthClient: clientId required' );
133
+ if( ! clientSecret ) throw new Error( 'createOAuthClient: clientSecret required' );
134
+ if( ! tokenUri ) throw new Error( 'createOAuthClient: tokenUri required' );
135
+
136
+ let cached = null;
137
+ let pending = null;
138
+
139
+ const isFresh = () => {
140
+
141
+ if( ! cached ) return false;
142
+
143
+ const now = Math.floor( Date.now() / 1000 );
144
+
145
+ return cached.expiresAt - REFRESH_LEAD_SECONDS > now;
146
+
147
+ };
148
+
149
+ const fetchToken = async () => {
150
+
151
+ const params = new URLSearchParams();
152
+
153
+ params.set( 'grant_type', 'client_credentials' );
154
+
155
+ if( scopes.length > 0 ){
156
+
157
+ params.set( 'scope', scopes.join( ' ' ) );
158
+
159
+ }
160
+
161
+ const basic = Buffer
162
+ .from( clientId + ':' + clientSecret )
163
+ .toString( 'base64' );
164
+
165
+ const response = await fetch(
166
+ tokenUri,
167
+ {
168
+ body : params.toString(),
169
+ headers : {
170
+ 'authorization' : 'Basic ' + basic,
171
+ 'content-type' : 'application/x-www-form-urlencoded'
172
+ },
173
+ method : 'POST'
174
+ }
175
+ );
176
+
177
+ if( ! response.ok ){
178
+
179
+ const text = await response.text();
180
+
181
+ throw new Error( 'createOAuthClient: token fetch failed (' + response.status + '): ' + text );
182
+
183
+ }
184
+
185
+ const body = await response.json();
186
+
187
+ cached = {
188
+ accessToken : body.access_token,
189
+ expiresAt : Math.floor( Date.now() / 1000 ) + Number( body.expires_in || 3600 ),
190
+ scope : body.scope
191
+ };
192
+
193
+ return cached.accessToken;
194
+
195
+ };
196
+
197
+ // Single-flight: collapse concurrent token fetches into one network call.
198
+ const refresh = () => {
199
+
200
+ if( pending ) return pending;
201
+
202
+ pending = fetchToken().finally( () => {
203
+
204
+ pending = null;
205
+
206
+ });
207
+
208
+ return pending;
209
+
210
+ };
211
+
212
+ return {
213
+ token : async () => {
214
+
215
+ if( isFresh() ) return cached.accessToken;
216
+
217
+ return refresh();
218
+
219
+ },
220
+ // Force a refresh on the next call. Use this when a request returns 401
221
+ // before the cached token's expiry — the server may have revoked it.
222
+ invalidate : () => {
223
+
224
+ cached = null;
225
+
226
+ }
227
+ };
228
+
229
+ };
230
+
231
+ export { createOAuthClient, developer, generateToken, hashToken, intersect, isDeveloperAllowed, parse, scopes, validate };
@@ -0,0 +1,231 @@
1
+ import { generate, hash } from '../token.js';
2
+ export { compare } from '../token.js';
3
+ import 'crypto';
4
+
5
+ // Shared OAuth helpers used across drawbridge-api, drawbridge-sync,
6
+ // drawbridge-app-web, and any first-party app that needs to participate
7
+ // in the OAuth 2.1 provider:
8
+ //
9
+ // - scopes, developer: the locked scope vocabulary
10
+ // - parse, validate, intersect, isDeveloperAllowed: scope set operations
11
+ // - hashToken, generateToken, compare: opaque-token primitives
12
+ // - createOAuthClient: cached client_credentials access token getter
13
+
14
+
15
+ // ─────────────────────────────────────────────────────────────────────────
16
+ // Scope vocabulary (locked — 15 scopes, 10 in the developer-allowed subset)
17
+ // ─────────────────────────────────────────────────────────────────────────
18
+
19
+ const scopes = [
20
+ 'profile:read',
21
+ 'profile:write',
22
+ 'organization:read',
23
+ 'organization:write',
24
+ 'campaigns:read',
25
+ 'campaigns:write',
26
+ 'contacts:read',
27
+ 'contacts:write',
28
+ 'workflows:read',
29
+ 'workflows:write',
30
+ 'connections:read',
31
+ 'connections:write',
32
+ 'billing:read',
33
+ 'billing:write',
34
+ 'admin'
35
+ ];
36
+
37
+ // Subset granted to third-party developer apps via /oauth/clients self-service
38
+ // registration. Excludes profile:write (account-level), organization:write
39
+ // (org admin only), billing:* (financial), admin (privileged).
40
+ const developer = [
41
+ 'profile:read',
42
+ 'organization:read',
43
+ 'campaigns:read',
44
+ 'campaigns:write',
45
+ 'contacts:read',
46
+ 'contacts:write',
47
+ 'workflows:read',
48
+ 'workflows:write',
49
+ 'connections:read',
50
+ 'connections:write'
51
+ ];
52
+
53
+ const parse = ( raw ) => {
54
+
55
+ if( ! raw ) return [];
56
+
57
+ if( Array.isArray( raw ) ) return raw;
58
+
59
+ return String( raw ).split( /\s+/ ).filter( Boolean );
60
+
61
+ };
62
+
63
+ const validate = ( scopes ) => {
64
+
65
+ const parsed = parse( scopes );
66
+ const invalid = parsed.filter( ( scope ) => ! scopes.includes( scope ) );
67
+
68
+ return {
69
+ invalid,
70
+ valid : invalid.length === 0
71
+ };
72
+
73
+ };
74
+
75
+ const intersect = ( requested, allowed ) => {
76
+
77
+ const r = parse( requested );
78
+ const a = parse( allowed );
79
+
80
+ return r.filter( ( scope ) => a.includes( scope ) );
81
+
82
+ };
83
+
84
+ const isDeveloperAllowed = ( scope ) => developer.includes( scope );
85
+
86
+ // ─────────────────────────────────────────────────────────────────────────
87
+ // Token primitives — convenience wrappers over drawbridge-utils/token that
88
+ // fix the OAuth-specific conventions (32 bytes base64url, env-keyed HMAC)
89
+ // ─────────────────────────────────────────────────────────────────────────
90
+
91
+ // Hash an OAuth token with the deployment's HMAC key (OAUTH_TOKEN_HMAC_KEY).
92
+ // Falls back to plain SHA256 if the env var is unset — fine for local dev,
93
+ // not for production (DB compromise would then allow token forgery).
94
+ const hashToken = ( raw ) => hash( raw, process.env.OAUTH_TOKEN_HMAC_KEY );
95
+
96
+ // 32 cryptographically random bytes encoded as a 43-char base64url string —
97
+ // the shape used for access tokens, refresh tokens, PATs, and authorization
98
+ // codes.
99
+ const generateToken = () => generate( 32, 'base64url' );
100
+
101
+ // ─────────────────────────────────────────────────────────────────────────
102
+ // Client_credentials token caching for first-party apps that call
103
+ // drawbridge-api as themselves (drawbridge-share, drawbridge-emails,
104
+ // drawbridge-webhooks, etc.).
105
+ //
106
+ // Caches the access token in process memory; refreshes when nearing expiry
107
+ // or after a 401. Single-flight refresh prevents thundering herd when many
108
+ // concurrent requests arrive while the token is being rotated.
109
+ //
110
+ // Usage:
111
+ // import { createOAuthClient } from '@drawbridge/drawbridge-utils/oauth';
112
+ //
113
+ // const client = createOAuthClient({
114
+ // clientId : process.env.OAUTH_CLIENT_ID,
115
+ // clientSecret : process.env.OAUTH_CLIENT_SECRET,
116
+ // tokenUri : process.env.NEXT_PUBLIC_API_URI + '/oauth/token',
117
+ // scopes : [ 'campaigns:read' ]
118
+ // });
119
+ //
120
+ // await request({ endpoint : '/page/abc', token : await client.token() });
121
+ // ─────────────────────────────────────────────────────────────────────────
122
+
123
+ const REFRESH_LEAD_SECONDS = 60;
124
+
125
+ const createOAuthClient = ({
126
+ clientId,
127
+ clientSecret,
128
+ scopes = [],
129
+ tokenUri
130
+ }) => {
131
+
132
+ if( ! clientId ) throw new Error( 'createOAuthClient: clientId required' );
133
+ if( ! clientSecret ) throw new Error( 'createOAuthClient: clientSecret required' );
134
+ if( ! tokenUri ) throw new Error( 'createOAuthClient: tokenUri required' );
135
+
136
+ let cached = null;
137
+ let pending = null;
138
+
139
+ const isFresh = () => {
140
+
141
+ if( ! cached ) return false;
142
+
143
+ const now = Math.floor( Date.now() / 1000 );
144
+
145
+ return cached.expiresAt - REFRESH_LEAD_SECONDS > now;
146
+
147
+ };
148
+
149
+ const fetchToken = async () => {
150
+
151
+ const params = new URLSearchParams();
152
+
153
+ params.set( 'grant_type', 'client_credentials' );
154
+
155
+ if( scopes.length > 0 ){
156
+
157
+ params.set( 'scope', scopes.join( ' ' ) );
158
+
159
+ }
160
+
161
+ const basic = Buffer
162
+ .from( clientId + ':' + clientSecret )
163
+ .toString( 'base64' );
164
+
165
+ const response = await fetch(
166
+ tokenUri,
167
+ {
168
+ body : params.toString(),
169
+ headers : {
170
+ 'authorization' : 'Basic ' + basic,
171
+ 'content-type' : 'application/x-www-form-urlencoded'
172
+ },
173
+ method : 'POST'
174
+ }
175
+ );
176
+
177
+ if( ! response.ok ){
178
+
179
+ const text = await response.text();
180
+
181
+ throw new Error( 'createOAuthClient: token fetch failed (' + response.status + '): ' + text );
182
+
183
+ }
184
+
185
+ const body = await response.json();
186
+
187
+ cached = {
188
+ accessToken : body.access_token,
189
+ expiresAt : Math.floor( Date.now() / 1000 ) + Number( body.expires_in || 3600 ),
190
+ scope : body.scope
191
+ };
192
+
193
+ return cached.accessToken;
194
+
195
+ };
196
+
197
+ // Single-flight: collapse concurrent token fetches into one network call.
198
+ const refresh = () => {
199
+
200
+ if( pending ) return pending;
201
+
202
+ pending = fetchToken().finally( () => {
203
+
204
+ pending = null;
205
+
206
+ });
207
+
208
+ return pending;
209
+
210
+ };
211
+
212
+ return {
213
+ token : async () => {
214
+
215
+ if( isFresh() ) return cached.accessToken;
216
+
217
+ return refresh();
218
+
219
+ },
220
+ // Force a refresh on the next call. Use this when a request returns 401
221
+ // before the cached token's expiry — the server may have revoked it.
222
+ invalidate : () => {
223
+
224
+ cached = null;
225
+
226
+ }
227
+ };
228
+
229
+ };
230
+
231
+ export { createOAuthClient, developer, generateToken, hashToken, intersect, isDeveloperAllowed, parse, scopes, validate };
@@ -0,0 +1,151 @@
1
+ // lib/token.js
2
+ import crypto from "crypto";
3
+ var generate = (bytes = 32, encoding = "base64url") => {
4
+ const buf = crypto.randomBytes(bytes);
5
+ return encoding ? buf.toString(encoding) : buf;
6
+ };
7
+ var hash = (value, key) => {
8
+ if (!value) return null;
9
+ if (key) {
10
+ return crypto.createHmac("sha256", key).update(String(value)).digest("base64url");
11
+ }
12
+ return crypto.createHash("sha256").update(String(value)).digest("base64url");
13
+ };
14
+ var compare = (a, b) => {
15
+ if (typeof a !== "string" || typeof b !== "string") return false;
16
+ if (a.length !== b.length) return false;
17
+ return crypto.timingSafeEqual(
18
+ Buffer.from(a),
19
+ Buffer.from(b)
20
+ );
21
+ };
22
+
23
+ // lib/oauth/index.js
24
+ var scopes = [
25
+ "profile:read",
26
+ "profile:write",
27
+ "organization:read",
28
+ "organization:write",
29
+ "campaigns:read",
30
+ "campaigns:write",
31
+ "contacts:read",
32
+ "contacts:write",
33
+ "workflows:read",
34
+ "workflows:write",
35
+ "connections:read",
36
+ "connections:write",
37
+ "billing:read",
38
+ "billing:write",
39
+ "admin"
40
+ ];
41
+ var developer = [
42
+ "profile:read",
43
+ "organization:read",
44
+ "campaigns:read",
45
+ "campaigns:write",
46
+ "contacts:read",
47
+ "contacts:write",
48
+ "workflows:read",
49
+ "workflows:write",
50
+ "connections:read",
51
+ "connections:write"
52
+ ];
53
+ var parse = (raw) => {
54
+ if (!raw) return [];
55
+ if (Array.isArray(raw)) return raw;
56
+ return String(raw).split(/\s+/).filter(Boolean);
57
+ };
58
+ var validate = (scopes2) => {
59
+ const parsed = parse(scopes2);
60
+ const invalid = parsed.filter((scope) => !scopes2.includes(scope));
61
+ return {
62
+ invalid,
63
+ valid: invalid.length === 0
64
+ };
65
+ };
66
+ var intersect = (requested, allowed) => {
67
+ const r = parse(requested);
68
+ const a = parse(allowed);
69
+ return r.filter((scope) => a.includes(scope));
70
+ };
71
+ var isDeveloperAllowed = (scope) => developer.includes(scope);
72
+ var hashToken = (raw) => hash(raw, process.env.OAUTH_TOKEN_HMAC_KEY);
73
+ var generateToken = () => generate(32, "base64url");
74
+ var REFRESH_LEAD_SECONDS = 60;
75
+ var createOAuthClient = ({
76
+ clientId,
77
+ clientSecret,
78
+ scopes: scopes2 = [],
79
+ tokenUri
80
+ }) => {
81
+ if (!clientId) throw new Error("createOAuthClient: clientId required");
82
+ if (!clientSecret) throw new Error("createOAuthClient: clientSecret required");
83
+ if (!tokenUri) throw new Error("createOAuthClient: tokenUri required");
84
+ let cached = null;
85
+ let pending = null;
86
+ const isFresh = () => {
87
+ if (!cached) return false;
88
+ const now = Math.floor(Date.now() / 1e3);
89
+ return cached.expiresAt - REFRESH_LEAD_SECONDS > now;
90
+ };
91
+ const fetchToken = async () => {
92
+ const params = new URLSearchParams();
93
+ params.set("grant_type", "client_credentials");
94
+ if (scopes2.length > 0) {
95
+ params.set("scope", scopes2.join(" "));
96
+ }
97
+ const basic = Buffer.from(clientId + ":" + clientSecret).toString("base64");
98
+ const response = await fetch(
99
+ tokenUri,
100
+ {
101
+ body: params.toString(),
102
+ headers: {
103
+ "authorization": "Basic " + basic,
104
+ "content-type": "application/x-www-form-urlencoded"
105
+ },
106
+ method: "POST"
107
+ }
108
+ );
109
+ if (!response.ok) {
110
+ const text = await response.text();
111
+ throw new Error("createOAuthClient: token fetch failed (" + response.status + "): " + text);
112
+ }
113
+ const body = await response.json();
114
+ cached = {
115
+ accessToken: body.access_token,
116
+ expiresAt: Math.floor(Date.now() / 1e3) + Number(body.expires_in || 3600),
117
+ scope: body.scope
118
+ };
119
+ return cached.accessToken;
120
+ };
121
+ const refresh = () => {
122
+ if (pending) return pending;
123
+ pending = fetchToken().finally(() => {
124
+ pending = null;
125
+ });
126
+ return pending;
127
+ };
128
+ return {
129
+ token: async () => {
130
+ if (isFresh()) return cached.accessToken;
131
+ return refresh();
132
+ },
133
+ // Force a refresh on the next call. Use this when a request returns 401
134
+ // before the cached token's expiry — the server may have revoked it.
135
+ invalidate: () => {
136
+ cached = null;
137
+ }
138
+ };
139
+ };
140
+ export {
141
+ compare,
142
+ createOAuthClient,
143
+ developer,
144
+ generateToken,
145
+ hashToken,
146
+ intersect,
147
+ isDeveloperAllowed,
148
+ parse,
149
+ scopes,
150
+ validate
151
+ };