@drawbridge/drawbridge-utils 0.0.42 → 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.
@@ -1,11 +1,27 @@
1
- import {
2
- compare,
3
- generate,
4
- hash
5
- } from "./chunk-OS2AHUWX.js";
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
+ };
6
22
 
7
- // oauth.js
8
- var SCOPES = [
23
+ // lib/oauth/index.js
24
+ var scopes = [
9
25
  "profile:read",
10
26
  "profile:write",
11
27
  "organization:read",
@@ -22,7 +38,7 @@ var SCOPES = [
22
38
  "billing:write",
23
39
  "admin"
24
40
  ];
25
- var DEVELOPER_ALLOWED_SCOPES = [
41
+ var developer = [
26
42
  "profile:read",
27
43
  "organization:read",
28
44
  "campaigns:read",
@@ -39,9 +55,9 @@ var parse = (raw) => {
39
55
  if (Array.isArray(raw)) return raw;
40
56
  return String(raw).split(/\s+/).filter(Boolean);
41
57
  };
42
- var validate = (scopes) => {
43
- const parsed = parse(scopes);
44
- const invalid = parsed.filter((scope) => !SCOPES.includes(scope));
58
+ var validate = (scopes2) => {
59
+ const parsed = parse(scopes2);
60
+ const invalid = parsed.filter((scope) => !scopes2.includes(scope));
45
61
  return {
46
62
  invalid,
47
63
  valid: invalid.length === 0
@@ -52,14 +68,14 @@ var intersect = (requested, allowed) => {
52
68
  const a = parse(allowed);
53
69
  return r.filter((scope) => a.includes(scope));
54
70
  };
55
- var isDeveloperAllowed = (scope) => DEVELOPER_ALLOWED_SCOPES.includes(scope);
71
+ var isDeveloperAllowed = (scope) => developer.includes(scope);
56
72
  var hashToken = (raw) => hash(raw, process.env.OAUTH_TOKEN_HMAC_KEY);
57
73
  var generateToken = () => generate(32, "base64url");
58
74
  var REFRESH_LEAD_SECONDS = 60;
59
75
  var createOAuthClient = ({
60
76
  clientId,
61
77
  clientSecret,
62
- scopes = [],
78
+ scopes: scopes2 = [],
63
79
  tokenUri
64
80
  }) => {
65
81
  if (!clientId) throw new Error("createOAuthClient: clientId required");
@@ -75,8 +91,8 @@ var createOAuthClient = ({
75
91
  const fetchToken = async () => {
76
92
  const params = new URLSearchParams();
77
93
  params.set("grant_type", "client_credentials");
78
- if (scopes.length > 0) {
79
- params.set("scope", scopes.join(" "));
94
+ if (scopes2.length > 0) {
95
+ params.set("scope", scopes2.join(" "));
80
96
  }
81
97
  const basic = Buffer.from(clientId + ":" + clientSecret).toString("base64");
82
98
  const response = await fetch(
@@ -122,14 +138,14 @@ var createOAuthClient = ({
122
138
  };
123
139
  };
124
140
  export {
125
- DEVELOPER_ALLOWED_SCOPES,
126
- SCOPES,
127
141
  compare,
128
142
  createOAuthClient,
143
+ developer,
129
144
  generateToken,
130
145
  hashToken,
131
146
  intersect,
132
147
  isDeveloperAllowed,
133
148
  parse,
149
+ scopes,
134
150
  validate
135
151
  };
@@ -0,0 +1,377 @@
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/oauth/server.js
30
+ var server_exports = {};
31
+ __export(server_exports, {
32
+ createClient: () => createClient,
33
+ createOAuthModel: () => createOAuthModel,
34
+ createOAuthServer: () => createOAuthServer
35
+ });
36
+ module.exports = __toCommonJS(server_exports);
37
+ var import_oauth2_server = __toESM(require("@node-oauth/oauth2-server"), 1);
38
+
39
+ // lib/token.js
40
+ var import_crypto = __toESM(require("crypto"), 1);
41
+ var generate = (bytes = 32, encoding = "base64url") => {
42
+ const buf = import_crypto.default.randomBytes(bytes);
43
+ return encoding ? buf.toString(encoding) : buf;
44
+ };
45
+ var hash = (value, key) => {
46
+ if (!value) return null;
47
+ if (key) {
48
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
49
+ }
50
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
51
+ };
52
+ var compare = (a, b) => {
53
+ if (typeof a !== "string" || typeof b !== "string") return false;
54
+ if (a.length !== b.length) return false;
55
+ return import_crypto.default.timingSafeEqual(
56
+ Buffer.from(a),
57
+ Buffer.from(b)
58
+ );
59
+ };
60
+
61
+ // lib/oauth/index.js
62
+ var developer = [
63
+ "profile:read",
64
+ "organization:read",
65
+ "campaigns:read",
66
+ "campaigns:write",
67
+ "contacts:read",
68
+ "contacts:write",
69
+ "workflows:read",
70
+ "workflows:write",
71
+ "connections:read",
72
+ "connections:write"
73
+ ];
74
+ var parse = (raw) => {
75
+ if (!raw) return [];
76
+ if (Array.isArray(raw)) return raw;
77
+ return String(raw).split(/\s+/).filter(Boolean);
78
+ };
79
+ var intersect = (requested, allowed) => {
80
+ const r = parse(requested);
81
+ const a = parse(allowed);
82
+ return r.filter((scope) => a.includes(scope));
83
+ };
84
+ var hashToken = (raw) => hash(raw, process.env.OAUTH_TOKEN_HMAC_KEY);
85
+ var generateToken = () => generate(32, "base64url");
86
+
87
+ // lib/oauth/server.js
88
+ var ACCESS_TOKEN_LIFETIME_SECONDS = 60 * 60;
89
+ var REFRESH_TOKEN_LIFETIME_SECONDS = 60 * 60 * 24 * 30;
90
+ var AUTHORIZATION_CODE_LIFETIME_MS = 10 * 60 * 1e3;
91
+ var createOAuthModel = ({ controller }) => ({
92
+ getClient: async (clientId, clientSecret) => {
93
+ var _a;
94
+ const client = await controller.get({
95
+ collection: "oauth",
96
+ query: {
97
+ clientId,
98
+ status: "active"
99
+ }
100
+ });
101
+ if (!client) return false;
102
+ if (clientSecret) {
103
+ const validSecret = (_a = client.clientSecretHashes) == null ? void 0 : _a.some((entry) => {
104
+ if (entry.retiredAt) return false;
105
+ return compare(hashToken(clientSecret), entry.hash);
106
+ });
107
+ if (!validSecret) return false;
108
+ }
109
+ ;
110
+ return {
111
+ clientId: client.clientId,
112
+ grants: ["authorization_code", "client_credentials", "refresh_token"],
113
+ id: client.id,
114
+ redirectUris: client.redirectUris ?? [],
115
+ scopes: client.allowedScopes ?? []
116
+ };
117
+ },
118
+ saveAuthorizationCode: async (code, client, user) => {
119
+ const rawCode = code.authorizationCode;
120
+ const tokenHash = hashToken(rawCode);
121
+ const expiresAt = new Date(Date.now() + AUTHORIZATION_CODE_LIFETIME_MS);
122
+ await controller.create({
123
+ collection: "otc",
124
+ data: {
125
+ client: client.clientId,
126
+ codeChallenge: code.codeChallenge ?? null,
127
+ codeChallengeMethod: code.codeChallengeMethod ?? null,
128
+ consumedAt: null,
129
+ context: "oauth.authorize",
130
+ expiresAt,
131
+ redirectUri: code.redirectUri ?? null,
132
+ scopes: code.scope ?? [],
133
+ tokenHash,
134
+ user: user.id
135
+ }
136
+ });
137
+ return {
138
+ authorizationCode: rawCode,
139
+ client: { id: client.id },
140
+ expiresAt,
141
+ redirectUri: code.redirectUri,
142
+ scope: code.scope,
143
+ user: { id: user.id }
144
+ };
145
+ },
146
+ getAuthorizationCode: async (authorizationCode) => {
147
+ const tokenHash = hashToken(authorizationCode);
148
+ const now = /* @__PURE__ */ new Date();
149
+ const record = await controller.get({
150
+ collection: "otc",
151
+ query: {
152
+ consumedAt: null,
153
+ context: "oauth.authorize",
154
+ expiresAt: { $gt: now },
155
+ tokenHash
156
+ }
157
+ });
158
+ if (!record) return false;
159
+ return {
160
+ authorizationCode,
161
+ client: { id: record.client },
162
+ codeChallenge: record.codeChallenge,
163
+ codeChallengeMethod: record.codeChallengeMethod,
164
+ expiresAt: record.expiresAt,
165
+ redirectUri: record.redirectUri,
166
+ scope: record.scopes,
167
+ user: { id: record.user }
168
+ };
169
+ },
170
+ revokeAuthorizationCode: async (code) => {
171
+ const tokenHash = hashToken(code.authorizationCode);
172
+ await controller.update({
173
+ collection: "otc",
174
+ data: {
175
+ $set: {
176
+ consumedAt: /* @__PURE__ */ new Date()
177
+ }
178
+ },
179
+ query: {
180
+ context: "oauth.authorize",
181
+ tokenHash
182
+ }
183
+ });
184
+ return true;
185
+ },
186
+ saveToken: async (token, client, user) => {
187
+ const now = /* @__PURE__ */ new Date();
188
+ const accessRaw = token.accessToken;
189
+ const accessHash = hashToken(accessRaw);
190
+ const accessExpiresAt = token.accessTokenExpiresAt ?? new Date(now.getTime() + ACCESS_TOKEN_LIFETIME_SECONDS * 1e3);
191
+ await controller.create({
192
+ collection: "token",
193
+ data: {
194
+ client: client.clientId,
195
+ consumedAt: null,
196
+ data: {},
197
+ email: null,
198
+ expiresAt: accessExpiresAt,
199
+ lastUsedAt: null,
200
+ name: null,
201
+ revoked: false,
202
+ revokedAt: null,
203
+ rotatedFrom: null,
204
+ scopes: token.scope ?? [],
205
+ tokenHash: accessHash,
206
+ type: "access",
207
+ user: (user == null ? void 0 : user.id) ?? null
208
+ }
209
+ });
210
+ const result = {
211
+ accessToken: accessRaw,
212
+ accessTokenExpiresAt: accessExpiresAt,
213
+ client: { id: client.id },
214
+ scope: token.scope,
215
+ user: { id: (user == null ? void 0 : user.id) ?? null }
216
+ };
217
+ if (token.refreshToken) {
218
+ const refreshRaw = token.refreshToken;
219
+ const refreshHash = hashToken(refreshRaw);
220
+ const refreshExpiresAt = token.refreshTokenExpiresAt ?? new Date(now.getTime() + REFRESH_TOKEN_LIFETIME_SECONDS * 1e3);
221
+ await controller.create({
222
+ collection: "token",
223
+ data: {
224
+ client: client.clientId,
225
+ consumedAt: null,
226
+ data: {},
227
+ email: null,
228
+ expiresAt: refreshExpiresAt,
229
+ lastUsedAt: null,
230
+ name: null,
231
+ revoked: false,
232
+ revokedAt: null,
233
+ rotatedFrom: null,
234
+ scopes: token.scope ?? [],
235
+ tokenHash: refreshHash,
236
+ type: "refresh",
237
+ user: (user == null ? void 0 : user.id) ?? null
238
+ }
239
+ });
240
+ result.refreshToken = refreshRaw;
241
+ result.refreshTokenExpiresAt = refreshExpiresAt;
242
+ }
243
+ ;
244
+ return result;
245
+ },
246
+ getAccessToken: async (accessToken) => {
247
+ const tokenHash = hashToken(accessToken);
248
+ const now = /* @__PURE__ */ new Date();
249
+ const record = await controller.get({
250
+ collection: "token",
251
+ query: {
252
+ expiresAt: { $gt: now },
253
+ revoked: false,
254
+ tokenHash,
255
+ type: "access"
256
+ }
257
+ });
258
+ if (!record) return false;
259
+ return {
260
+ accessToken,
261
+ accessTokenExpiresAt: record.expiresAt,
262
+ client: { id: record.client },
263
+ scope: record.scopes,
264
+ user: { id: record.user }
265
+ };
266
+ },
267
+ getRefreshToken: async (refreshToken) => {
268
+ const tokenHash = hashToken(refreshToken);
269
+ const record = await controller.get({
270
+ collection: "token",
271
+ query: {
272
+ revoked: false,
273
+ tokenHash,
274
+ type: "refresh"
275
+ }
276
+ });
277
+ if (!record) return false;
278
+ return {
279
+ client: { id: record.client },
280
+ refreshToken,
281
+ refreshTokenExpiresAt: record.expiresAt,
282
+ scope: record.scopes,
283
+ user: { id: record.user }
284
+ };
285
+ },
286
+ revokeToken: async (token) => {
287
+ const rawToken = token.refreshToken ?? token.accessToken;
288
+ const tokenHash = hashToken(rawToken);
289
+ await controller.update({
290
+ collection: "token",
291
+ data: {
292
+ $set: {
293
+ revoked: true,
294
+ revokedAt: /* @__PURE__ */ new Date()
295
+ }
296
+ },
297
+ query: { tokenHash }
298
+ });
299
+ return true;
300
+ },
301
+ verifyScope: (token, scope) => {
302
+ const granted = intersect(scope, token.scope ?? []);
303
+ return granted.length > 0;
304
+ },
305
+ // client_credentials grant: treat the client as the resource owner.
306
+ getUserFromClient: (client) => ({ id: client.id, type: "client" })
307
+ });
308
+ var createOAuthServer = ({ controller }) => new import_oauth2_server.default({
309
+ accessTokenLifetime: ACCESS_TOKEN_LIFETIME_SECONDS,
310
+ allowBearerTokensInQueryString: false,
311
+ model: createOAuthModel({ controller }),
312
+ refreshTokenLifetime: REFRESH_TOKEN_LIFETIME_SECONDS,
313
+ requireClientAuthentication: {
314
+ authorization_code: true,
315
+ client_credentials: true,
316
+ refresh_token: true
317
+ }
318
+ });
319
+ var createClient = async ({
320
+ allowedScopes = [],
321
+ controller,
322
+ createdBy = null,
323
+ description = null,
324
+ grantTypes = ["authorization_code"],
325
+ name,
326
+ organization = null,
327
+ redirectUris = [],
328
+ webOrigins = []
329
+ }) => {
330
+ const invalid = allowedScopes.filter((scope) => !developer.includes(scope));
331
+ if (invalid.length > 0) {
332
+ const error = new Error("Scopes not permitted for developer apps: " + invalid.join(", "));
333
+ error.status = 400;
334
+ throw error;
335
+ }
336
+ ;
337
+ const rawClientId = generateToken();
338
+ const clientId = "drawbridge." + rawClientId;
339
+ const rawSecret = generateToken();
340
+ const secretHash = hashToken(rawSecret);
341
+ const now = /* @__PURE__ */ new Date();
342
+ const doc = await controller.insert({
343
+ collection: "oauth",
344
+ data: {
345
+ allowedScopes,
346
+ clientId,
347
+ clientSecretHashes: [
348
+ {
349
+ createdAt: now,
350
+ hash: secretHash,
351
+ retiredAt: null
352
+ }
353
+ ],
354
+ clientType: "confidential",
355
+ createdBy,
356
+ description,
357
+ grantTypes,
358
+ name,
359
+ organization,
360
+ rateLimitOverrides: null,
361
+ redirectUris,
362
+ status: "active",
363
+ tokenEndpointAuthMethod: "client_secret_basic",
364
+ webOrigins
365
+ }
366
+ });
367
+ return {
368
+ client: doc,
369
+ rawSecret
370
+ };
371
+ };
372
+ // Annotate the CommonJS export names for ESM import in node:
373
+ 0 && (module.exports = {
374
+ createClient,
375
+ createOAuthModel,
376
+ createOAuthServer
377
+ });