@drawbridge/drawbridge-utils 0.0.40 → 0.0.42

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  generate
3
- } from "./chunk-HOA2JHXC.js";
3
+ } from "./chunk-OS2AHUWX.js";
4
4
 
5
5
  // encrypt.js
6
6
  import crypto from "crypto";
@@ -0,0 +1,27 @@
1
+ // 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
+ export {
24
+ generate,
25
+ hash,
26
+ compare
27
+ };
package/dist/encrypt.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  decrypt,
3
3
  encrypt
4
- } from "./chunk-N5EMSZLI.js";
5
- import "./chunk-HOA2JHXC.js";
4
+ } from "./chunk-2DRAIKGZ.js";
5
+ import "./chunk-OS2AHUWX.js";
6
6
  export {
7
7
  decrypt,
8
8
  encrypt
package/dist/oauth.cjs ADDED
@@ -0,0 +1,196 @@
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
+ // oauth.js
30
+ var oauth_exports = {};
31
+ __export(oauth_exports, {
32
+ DEVELOPER_ALLOWED_SCOPES: () => DEVELOPER_ALLOWED_SCOPES,
33
+ SCOPES: () => SCOPES,
34
+ compare: () => compare,
35
+ createOAuthClient: () => createOAuthClient,
36
+ generateToken: () => generateToken,
37
+ hashToken: () => hashToken,
38
+ intersect: () => intersect,
39
+ isDeveloperAllowed: () => isDeveloperAllowed,
40
+ parse: () => parse,
41
+ validate: () => validate
42
+ });
43
+ module.exports = __toCommonJS(oauth_exports);
44
+
45
+ // token.js
46
+ var import_crypto = __toESM(require("crypto"), 1);
47
+ var generate = (bytes = 32, encoding = "base64url") => {
48
+ const buf = import_crypto.default.randomBytes(bytes);
49
+ return encoding ? buf.toString(encoding) : buf;
50
+ };
51
+ var hash = (value, key) => {
52
+ if (!value) return null;
53
+ if (key) {
54
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
55
+ }
56
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
57
+ };
58
+ var compare = (a, b) => {
59
+ if (typeof a !== "string" || typeof b !== "string") return false;
60
+ if (a.length !== b.length) return false;
61
+ return import_crypto.default.timingSafeEqual(
62
+ Buffer.from(a),
63
+ Buffer.from(b)
64
+ );
65
+ };
66
+
67
+ // oauth.js
68
+ var SCOPES = [
69
+ "profile:read",
70
+ "profile:write",
71
+ "organization:read",
72
+ "organization:write",
73
+ "campaigns:read",
74
+ "campaigns:write",
75
+ "contacts:read",
76
+ "contacts:write",
77
+ "workflows:read",
78
+ "workflows:write",
79
+ "connections:read",
80
+ "connections:write",
81
+ "billing:read",
82
+ "billing:write",
83
+ "admin"
84
+ ];
85
+ var DEVELOPER_ALLOWED_SCOPES = [
86
+ "profile:read",
87
+ "organization:read",
88
+ "campaigns:read",
89
+ "campaigns:write",
90
+ "contacts:read",
91
+ "contacts:write",
92
+ "workflows:read",
93
+ "workflows:write",
94
+ "connections:read",
95
+ "connections:write"
96
+ ];
97
+ var parse = (raw) => {
98
+ if (!raw) return [];
99
+ if (Array.isArray(raw)) return raw;
100
+ return String(raw).split(/\s+/).filter(Boolean);
101
+ };
102
+ var validate = (scopes) => {
103
+ const parsed = parse(scopes);
104
+ const invalid = parsed.filter((scope) => !SCOPES.includes(scope));
105
+ return {
106
+ invalid,
107
+ valid: invalid.length === 0
108
+ };
109
+ };
110
+ var intersect = (requested, allowed) => {
111
+ const r = parse(requested);
112
+ const a = parse(allowed);
113
+ return r.filter((scope) => a.includes(scope));
114
+ };
115
+ var isDeveloperAllowed = (scope) => DEVELOPER_ALLOWED_SCOPES.includes(scope);
116
+ var hashToken = (raw) => hash(raw, process.env.OAUTH_TOKEN_HMAC_KEY);
117
+ var generateToken = () => generate(32, "base64url");
118
+ var REFRESH_LEAD_SECONDS = 60;
119
+ var createOAuthClient = ({
120
+ clientId,
121
+ clientSecret,
122
+ scopes = [],
123
+ tokenUri
124
+ }) => {
125
+ if (!clientId) throw new Error("createOAuthClient: clientId required");
126
+ if (!clientSecret) throw new Error("createOAuthClient: clientSecret required");
127
+ if (!tokenUri) throw new Error("createOAuthClient: tokenUri required");
128
+ let cached = null;
129
+ let pending = null;
130
+ const isFresh = () => {
131
+ if (!cached) return false;
132
+ const now = Math.floor(Date.now() / 1e3);
133
+ return cached.expiresAt - REFRESH_LEAD_SECONDS > now;
134
+ };
135
+ const fetchToken = async () => {
136
+ const params = new URLSearchParams();
137
+ params.set("grant_type", "client_credentials");
138
+ if (scopes.length > 0) {
139
+ params.set("scope", scopes.join(" "));
140
+ }
141
+ const basic = Buffer.from(clientId + ":" + clientSecret).toString("base64");
142
+ const response = await fetch(
143
+ tokenUri,
144
+ {
145
+ body: params.toString(),
146
+ headers: {
147
+ "authorization": "Basic " + basic,
148
+ "content-type": "application/x-www-form-urlencoded"
149
+ },
150
+ method: "POST"
151
+ }
152
+ );
153
+ if (!response.ok) {
154
+ const text = await response.text();
155
+ throw new Error("createOAuthClient: token fetch failed (" + response.status + "): " + text);
156
+ }
157
+ const body = await response.json();
158
+ cached = {
159
+ accessToken: body.access_token,
160
+ expiresAt: Math.floor(Date.now() / 1e3) + Number(body.expires_in || 3600),
161
+ scope: body.scope
162
+ };
163
+ return cached.accessToken;
164
+ };
165
+ const refresh = () => {
166
+ if (pending) return pending;
167
+ pending = fetchToken().finally(() => {
168
+ pending = null;
169
+ });
170
+ return pending;
171
+ };
172
+ return {
173
+ token: async () => {
174
+ if (isFresh()) return cached.accessToken;
175
+ return refresh();
176
+ },
177
+ // Force a refresh on the next call. Use this when a request returns 401
178
+ // before the cached token's expiry — the server may have revoked it.
179
+ invalidate: () => {
180
+ cached = null;
181
+ }
182
+ };
183
+ };
184
+ // Annotate the CommonJS export names for ESM import in node:
185
+ 0 && (module.exports = {
186
+ DEVELOPER_ALLOWED_SCOPES,
187
+ SCOPES,
188
+ compare,
189
+ createOAuthClient,
190
+ generateToken,
191
+ hashToken,
192
+ intersect,
193
+ isDeveloperAllowed,
194
+ parse,
195
+ validate
196
+ });
@@ -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_ALLOWED_SCOPES: 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_ALLOWED_SCOPES = [
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_ALLOWED_SCOPES.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 { DEVELOPER_ALLOWED_SCOPES, SCOPES, createOAuthClient, generateToken, hashToken, intersect, isDeveloperAllowed, parse, 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_ALLOWED_SCOPES: 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_ALLOWED_SCOPES = [
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_ALLOWED_SCOPES.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 { DEVELOPER_ALLOWED_SCOPES, SCOPES, createOAuthClient, generateToken, hashToken, intersect, isDeveloperAllowed, parse, validate };
package/dist/oauth.js ADDED
@@ -0,0 +1,135 @@
1
+ import {
2
+ compare,
3
+ generate,
4
+ hash
5
+ } from "./chunk-OS2AHUWX.js";
6
+
7
+ // oauth.js
8
+ var SCOPES = [
9
+ "profile:read",
10
+ "profile:write",
11
+ "organization:read",
12
+ "organization:write",
13
+ "campaigns:read",
14
+ "campaigns:write",
15
+ "contacts:read",
16
+ "contacts:write",
17
+ "workflows:read",
18
+ "workflows:write",
19
+ "connections:read",
20
+ "connections:write",
21
+ "billing:read",
22
+ "billing:write",
23
+ "admin"
24
+ ];
25
+ var DEVELOPER_ALLOWED_SCOPES = [
26
+ "profile:read",
27
+ "organization:read",
28
+ "campaigns:read",
29
+ "campaigns:write",
30
+ "contacts:read",
31
+ "contacts:write",
32
+ "workflows:read",
33
+ "workflows:write",
34
+ "connections:read",
35
+ "connections:write"
36
+ ];
37
+ var parse = (raw) => {
38
+ if (!raw) return [];
39
+ if (Array.isArray(raw)) return raw;
40
+ return String(raw).split(/\s+/).filter(Boolean);
41
+ };
42
+ var validate = (scopes) => {
43
+ const parsed = parse(scopes);
44
+ const invalid = parsed.filter((scope) => !SCOPES.includes(scope));
45
+ return {
46
+ invalid,
47
+ valid: invalid.length === 0
48
+ };
49
+ };
50
+ var intersect = (requested, allowed) => {
51
+ const r = parse(requested);
52
+ const a = parse(allowed);
53
+ return r.filter((scope) => a.includes(scope));
54
+ };
55
+ var isDeveloperAllowed = (scope) => DEVELOPER_ALLOWED_SCOPES.includes(scope);
56
+ var hashToken = (raw) => hash(raw, process.env.OAUTH_TOKEN_HMAC_KEY);
57
+ var generateToken = () => generate(32, "base64url");
58
+ var REFRESH_LEAD_SECONDS = 60;
59
+ var createOAuthClient = ({
60
+ clientId,
61
+ clientSecret,
62
+ scopes = [],
63
+ tokenUri
64
+ }) => {
65
+ if (!clientId) throw new Error("createOAuthClient: clientId required");
66
+ if (!clientSecret) throw new Error("createOAuthClient: clientSecret required");
67
+ if (!tokenUri) throw new Error("createOAuthClient: tokenUri required");
68
+ let cached = null;
69
+ let pending = null;
70
+ const isFresh = () => {
71
+ if (!cached) return false;
72
+ const now = Math.floor(Date.now() / 1e3);
73
+ return cached.expiresAt - REFRESH_LEAD_SECONDS > now;
74
+ };
75
+ const fetchToken = async () => {
76
+ const params = new URLSearchParams();
77
+ params.set("grant_type", "client_credentials");
78
+ if (scopes.length > 0) {
79
+ params.set("scope", scopes.join(" "));
80
+ }
81
+ const basic = Buffer.from(clientId + ":" + clientSecret).toString("base64");
82
+ const response = await fetch(
83
+ tokenUri,
84
+ {
85
+ body: params.toString(),
86
+ headers: {
87
+ "authorization": "Basic " + basic,
88
+ "content-type": "application/x-www-form-urlencoded"
89
+ },
90
+ method: "POST"
91
+ }
92
+ );
93
+ if (!response.ok) {
94
+ const text = await response.text();
95
+ throw new Error("createOAuthClient: token fetch failed (" + response.status + "): " + text);
96
+ }
97
+ const body = await response.json();
98
+ cached = {
99
+ accessToken: body.access_token,
100
+ expiresAt: Math.floor(Date.now() / 1e3) + Number(body.expires_in || 3600),
101
+ scope: body.scope
102
+ };
103
+ return cached.accessToken;
104
+ };
105
+ const refresh = () => {
106
+ if (pending) return pending;
107
+ pending = fetchToken().finally(() => {
108
+ pending = null;
109
+ });
110
+ return pending;
111
+ };
112
+ return {
113
+ token: async () => {
114
+ if (isFresh()) return cached.accessToken;
115
+ return refresh();
116
+ },
117
+ // Force a refresh on the next call. Use this when a request returns 401
118
+ // before the cached token's expiry — the server may have revoked it.
119
+ invalidate: () => {
120
+ cached = null;
121
+ }
122
+ };
123
+ };
124
+ export {
125
+ DEVELOPER_ALLOWED_SCOPES,
126
+ SCOPES,
127
+ compare,
128
+ createOAuthClient,
129
+ generateToken,
130
+ hashToken,
131
+ intersect,
132
+ isDeveloperAllowed,
133
+ parse,
134
+ validate
135
+ };
package/dist/shopify.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  decrypt,
3
3
  encrypt
4
- } from "./chunk-N5EMSZLI.js";
5
- import "./chunk-HOA2JHXC.js";
4
+ } from "./chunk-2DRAIKGZ.js";
5
+ import "./chunk-OS2AHUWX.js";
6
6
 
7
7
  // shopify.js
8
8
  import crypto from "crypto";
package/dist/token.cjs CHANGED
@@ -29,7 +29,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  // token.js
30
30
  var token_exports = {};
31
31
  __export(token_exports, {
32
- generate: () => generate
32
+ compare: () => compare,
33
+ generate: () => generate,
34
+ hash: () => hash
33
35
  });
34
36
  module.exports = __toCommonJS(token_exports);
35
37
  var import_crypto = __toESM(require("crypto"), 1);
@@ -37,7 +39,24 @@ var generate = (bytes = 32, encoding = "base64url") => {
37
39
  const buf = import_crypto.default.randomBytes(bytes);
38
40
  return encoding ? buf.toString(encoding) : buf;
39
41
  };
42
+ var hash = (value, key) => {
43
+ if (!value) return null;
44
+ if (key) {
45
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
46
+ }
47
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
48
+ };
49
+ var compare = (a, b) => {
50
+ if (typeof a !== "string" || typeof b !== "string") return false;
51
+ if (a.length !== b.length) return false;
52
+ return import_crypto.default.timingSafeEqual(
53
+ Buffer.from(a),
54
+ Buffer.from(b)
55
+ );
56
+ };
40
57
  // Annotate the CommonJS export names for ESM import in node:
41
58
  0 && (module.exports = {
42
- generate
59
+ compare,
60
+ generate,
61
+ hash
43
62
  });
package/dist/token.d.cts CHANGED
@@ -19,4 +19,43 @@ const generate = ( bytes = 32, encoding = 'base64url' ) => {
19
19
 
20
20
  };
21
21
 
22
- export { generate };
22
+ // Hash a token value for storage. When `key` is provided, uses HMAC-SHA256
23
+ // so DB compromise alone doesn't allow forgery via reverse lookup. Without
24
+ // a key, falls back to plain SHA256 (matches the legacy session pattern
25
+ // during transition).
26
+ const hash = ( value, key ) => {
27
+
28
+ if( ! value ) return null;
29
+
30
+ if( key ){
31
+
32
+ return crypto
33
+ .createHmac( 'sha256', key )
34
+ .update( String( value ) )
35
+ .digest( 'base64url' );
36
+
37
+ }
38
+
39
+ return crypto
40
+ .createHash( 'sha256' )
41
+ .update( String( value ) )
42
+ .digest( 'base64url' );
43
+
44
+ };
45
+
46
+ // Constant-time comparison. Returns false for length mismatches without
47
+ // timing leak. Use whenever comparing user-supplied input against stored
48
+ // hashes / secrets.
49
+ const compare = ( a, b ) => {
50
+
51
+ if( typeof a !== 'string' || typeof b !== 'string' ) return false;
52
+ if( a.length !== b.length ) return false;
53
+
54
+ return crypto.timingSafeEqual(
55
+ Buffer.from( a ),
56
+ Buffer.from( b )
57
+ );
58
+
59
+ };
60
+
61
+ export { compare, generate, hash };
package/dist/token.d.ts CHANGED
@@ -19,4 +19,43 @@ const generate = ( bytes = 32, encoding = 'base64url' ) => {
19
19
 
20
20
  };
21
21
 
22
- export { generate };
22
+ // Hash a token value for storage. When `key` is provided, uses HMAC-SHA256
23
+ // so DB compromise alone doesn't allow forgery via reverse lookup. Without
24
+ // a key, falls back to plain SHA256 (matches the legacy session pattern
25
+ // during transition).
26
+ const hash = ( value, key ) => {
27
+
28
+ if( ! value ) return null;
29
+
30
+ if( key ){
31
+
32
+ return crypto
33
+ .createHmac( 'sha256', key )
34
+ .update( String( value ) )
35
+ .digest( 'base64url' );
36
+
37
+ }
38
+
39
+ return crypto
40
+ .createHash( 'sha256' )
41
+ .update( String( value ) )
42
+ .digest( 'base64url' );
43
+
44
+ };
45
+
46
+ // Constant-time comparison. Returns false for length mismatches without
47
+ // timing leak. Use whenever comparing user-supplied input against stored
48
+ // hashes / secrets.
49
+ const compare = ( a, b ) => {
50
+
51
+ if( typeof a !== 'string' || typeof b !== 'string' ) return false;
52
+ if( a.length !== b.length ) return false;
53
+
54
+ return crypto.timingSafeEqual(
55
+ Buffer.from( a ),
56
+ Buffer.from( b )
57
+ );
58
+
59
+ };
60
+
61
+ export { compare, generate, hash };
package/dist/token.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import {
2
- generate
3
- } from "./chunk-HOA2JHXC.js";
2
+ compare,
3
+ generate,
4
+ hash
5
+ } from "./chunk-OS2AHUWX.js";
4
6
  export {
5
- generate
7
+ compare,
8
+ generate,
9
+ hash
6
10
  };
package/package.json CHANGED
@@ -48,6 +48,11 @@
48
48
  "import": "./dist/nanoid.js",
49
49
  "require": "./dist/nanoid.cjs"
50
50
  },
51
+ "./oauth": {
52
+ "types": "./dist/oauth.d.ts",
53
+ "import": "./dist/oauth.js",
54
+ "require": "./dist/oauth.cjs"
55
+ },
51
56
  "./orders": {
52
57
  "types": "./dist/orders.d.ts",
53
58
  "import": "./dist/orders.js",
@@ -109,5 +114,5 @@
109
114
  "build": "tsup && npm publish"
110
115
  },
111
116
  "types": "dist/index.d.ts",
112
- "version": "0.0.40"
117
+ "version": "0.0.42"
113
118
  }
@@ -1,10 +0,0 @@
1
- // 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
-
8
- export {
9
- generate
10
- };