@drawbridge/drawbridge-utils 0.0.42 → 0.0.44

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.
@@ -0,0 +1,387 @@
1
+ import OAuth2Server from '@node-oauth/oauth2-server';
2
+ import { developer, generateToken, hashToken, intersect } from './index.js';
3
+ import { compare } from '../token.js';
4
+ import 'crypto';
5
+
6
+ // Server-side OAuth 2.1 provider helpers. Server-only — pulls in
7
+ // `@node-oauth/oauth2-server`, which has no business in a browser bundle.
8
+ // Keep imports from this entry behind server-side code paths only.
9
+ //
10
+ // Exports:
11
+ // - createOAuthModel({ controller })
12
+ // Returns the @node-oauth/oauth2-server model adapter. The controller
13
+ // is duck-typed: any object with { get, create, update } accepting
14
+ // { collection, query, data } works. drawbridge-api passes its base
15
+ // controller; tests can pass an in-memory mock.
16
+ //
17
+ // - createOAuthServer({ controller })
18
+ // Convenience: creates the model + wraps it in an OAuth2Server with
19
+ // the standard Drawbridge lifetimes (1h access / 30d refresh) and
20
+ // client-authentication requirements.
21
+ //
22
+ // - createClient({ base, allowedScopes, name, organization, ... })
23
+ // Inserts a new oauth client row. Validates scopes against the
24
+ // developer set; throws 400 on invalid. Returns
25
+ // { client, rawSecret } — secret is plaintext, return ONCE.
26
+
27
+
28
+ const ACCESS_TOKEN_LIFETIME_SECONDS = 60 * 60; // 1 hour
29
+ const REFRESH_TOKEN_LIFETIME_SECONDS = 60 * 60 * 24 * 30; // 30 days
30
+ const AUTHORIZATION_CODE_LIFETIME_MS = 10 * 60 * 1000; // 10 minutes
31
+
32
+ const createOAuthModel = ({ controller }) => ({
33
+
34
+ getClient : async ( clientId, clientSecret ) => {
35
+
36
+ const client = await controller.get({
37
+ collection : 'oauth',
38
+ query : {
39
+ clientId,
40
+ status : 'active'
41
+ }
42
+ });
43
+
44
+ if( ! client ) return false;
45
+
46
+ if( clientSecret ){
47
+
48
+ const validSecret = client.clientSecretHashes?.some( ( entry ) => {
49
+
50
+ if( entry.retiredAt ) return false;
51
+
52
+ return compare( hashToken( clientSecret ), entry.hash );
53
+
54
+ });
55
+
56
+ if( ! validSecret ) return false;
57
+
58
+ }
59
+ return {
60
+ clientId : client.clientId,
61
+ grants : [ 'authorization_code', 'client_credentials', 'refresh_token' ],
62
+ id : client.id,
63
+ redirectUris : client.redirectUris ?? [],
64
+ scopes : client.allowedScopes ?? []
65
+ };
66
+
67
+ },
68
+
69
+ saveAuthorizationCode : async ( code, client, user ) => {
70
+
71
+ const rawCode = code.authorizationCode;
72
+ const tokenHash = hashToken( rawCode );
73
+ const expiresAt = new Date( Date.now() + AUTHORIZATION_CODE_LIFETIME_MS );
74
+
75
+ await controller.create({
76
+ collection : 'otc',
77
+ data : {
78
+ client : client.clientId,
79
+ codeChallenge : code.codeChallenge ?? null,
80
+ codeChallengeMethod : code.codeChallengeMethod ?? null,
81
+ consumedAt : null,
82
+ context : 'oauth.authorize',
83
+ expiresAt,
84
+ redirectUri : code.redirectUri ?? null,
85
+ scopes : code.scope ?? [],
86
+ tokenHash,
87
+ user : user.id
88
+ }
89
+ });
90
+
91
+ return {
92
+ authorizationCode : rawCode,
93
+ client : { id : client.id },
94
+ expiresAt,
95
+ redirectUri : code.redirectUri,
96
+ scope : code.scope,
97
+ user : { id : user.id }
98
+ };
99
+
100
+ },
101
+
102
+ getAuthorizationCode : async ( authorizationCode ) => {
103
+
104
+ const tokenHash = hashToken( authorizationCode );
105
+ const now = new Date();
106
+
107
+ const record = await controller.get({
108
+ collection : 'otc',
109
+ query : {
110
+ consumedAt : null,
111
+ context : 'oauth.authorize',
112
+ expiresAt : { $gt : now },
113
+ tokenHash
114
+ }
115
+ });
116
+
117
+ if( ! record ) return false;
118
+
119
+ return {
120
+ authorizationCode,
121
+ client : { id : record.client },
122
+ codeChallenge : record.codeChallenge,
123
+ codeChallengeMethod : record.codeChallengeMethod,
124
+ expiresAt : record.expiresAt,
125
+ redirectUri : record.redirectUri,
126
+ scope : record.scopes,
127
+ user : { id : record.user }
128
+ };
129
+
130
+ },
131
+
132
+ revokeAuthorizationCode : async ( code ) => {
133
+
134
+ const tokenHash = hashToken( code.authorizationCode );
135
+
136
+ await controller.update({
137
+ collection : 'otc',
138
+ data : {
139
+ $set : {
140
+ consumedAt : new Date()
141
+ }
142
+ },
143
+ query : {
144
+ context : 'oauth.authorize',
145
+ tokenHash
146
+ }
147
+ });
148
+
149
+ return true;
150
+
151
+ },
152
+
153
+ saveToken : async ( token, client, user ) => {
154
+
155
+ const now = new Date();
156
+ const accessRaw = token.accessToken;
157
+ const accessHash = hashToken( accessRaw );
158
+ const accessExpiresAt = token.accessTokenExpiresAt ?? new Date( now.getTime() + ACCESS_TOKEN_LIFETIME_SECONDS * 1000 );
159
+
160
+ await controller.create({
161
+ collection : 'token',
162
+ data : {
163
+ client : client.clientId,
164
+ consumedAt : null,
165
+ data : {},
166
+ email : null,
167
+ expiresAt : accessExpiresAt,
168
+ lastUsedAt : null,
169
+ name : null,
170
+ revoked : false,
171
+ revokedAt : null,
172
+ rotatedFrom : null,
173
+ scopes : token.scope ?? [],
174
+ tokenHash : accessHash,
175
+ type : 'access',
176
+ user : user?.id ?? null
177
+ }
178
+ });
179
+
180
+ const result = {
181
+ accessToken : accessRaw,
182
+ accessTokenExpiresAt : accessExpiresAt,
183
+ client : { id : client.id },
184
+ scope : token.scope,
185
+ user : { id : user?.id ?? null }
186
+ };
187
+
188
+ if( token.refreshToken ){
189
+
190
+ const refreshRaw = token.refreshToken;
191
+ const refreshHash = hashToken( refreshRaw );
192
+ const refreshExpiresAt = token.refreshTokenExpiresAt ?? new Date( now.getTime() + REFRESH_TOKEN_LIFETIME_SECONDS * 1000 );
193
+
194
+ await controller.create({
195
+ collection : 'token',
196
+ data : {
197
+ client : client.clientId,
198
+ consumedAt : null,
199
+ data : {},
200
+ email : null,
201
+ expiresAt : refreshExpiresAt,
202
+ lastUsedAt : null,
203
+ name : null,
204
+ revoked : false,
205
+ revokedAt : null,
206
+ rotatedFrom : null,
207
+ scopes : token.scope ?? [],
208
+ tokenHash : refreshHash,
209
+ type : 'refresh',
210
+ user : user?.id ?? null
211
+ }
212
+ });
213
+
214
+ result.refreshToken = refreshRaw;
215
+ result.refreshTokenExpiresAt = refreshExpiresAt;
216
+
217
+ }
218
+ return result;
219
+
220
+ },
221
+
222
+ getAccessToken : async ( accessToken ) => {
223
+
224
+ const tokenHash = hashToken( accessToken );
225
+ const now = new Date();
226
+
227
+ const record = await controller.get({
228
+ collection : 'token',
229
+ query : {
230
+ expiresAt : { $gt : now },
231
+ revoked : false,
232
+ tokenHash,
233
+ type : 'access'
234
+ }
235
+ });
236
+
237
+ if( ! record ) return false;
238
+
239
+ return {
240
+ accessToken,
241
+ accessTokenExpiresAt : record.expiresAt,
242
+ client : { id : record.client },
243
+ scope : record.scopes,
244
+ user : { id : record.user }
245
+ };
246
+
247
+ },
248
+
249
+ getRefreshToken : async ( refreshToken ) => {
250
+
251
+ const tokenHash = hashToken( refreshToken );
252
+
253
+ const record = await controller.get({
254
+ collection : 'token',
255
+ query : {
256
+ revoked : false,
257
+ tokenHash,
258
+ type : 'refresh'
259
+ }
260
+ });
261
+
262
+ if( ! record ) return false;
263
+
264
+ return {
265
+ client : { id : record.client },
266
+ refreshToken,
267
+ refreshTokenExpiresAt : record.expiresAt,
268
+ scope : record.scopes,
269
+ user : { id : record.user }
270
+ };
271
+
272
+ },
273
+
274
+ revokeToken : async ( token ) => {
275
+
276
+ const rawToken = token.refreshToken ?? token.accessToken;
277
+ const tokenHash = hashToken( rawToken );
278
+
279
+ await controller.update({
280
+ collection : 'token',
281
+ data : {
282
+ $set : {
283
+ revoked : true,
284
+ revokedAt : new Date()
285
+ }
286
+ },
287
+ query : { tokenHash }
288
+ });
289
+
290
+ return true;
291
+
292
+ },
293
+
294
+ verifyScope : ( token, scope ) => {
295
+
296
+ const granted = intersect( scope, token.scope ?? [] );
297
+
298
+ return granted.length > 0;
299
+
300
+ },
301
+
302
+ // client_credentials grant: treat the client as the resource owner.
303
+ getUserFromClient : ( client ) => ({ id : client.id, type : 'client' })
304
+
305
+ });
306
+
307
+ const createOAuthServer = ({ controller }) => new OAuth2Server({
308
+ accessTokenLifetime : ACCESS_TOKEN_LIFETIME_SECONDS,
309
+ allowBearerTokensInQueryString : false,
310
+ model : createOAuthModel({ controller }),
311
+ refreshTokenLifetime : REFRESH_TOKEN_LIFETIME_SECONDS,
312
+ requireClientAuthentication : {
313
+ authorization_code : true,
314
+ client_credentials : true,
315
+ refresh_token : true
316
+ }
317
+ });
318
+
319
+ // Inserts a new oauth client row. Validates allowedScopes against the
320
+ // developer-allowed subset; throws a 400-flagged error on invalid scopes.
321
+ // Returns { client: <inserted-doc>, rawSecret: <plaintext> }. The raw
322
+ // secret is only available here — store immediately.
323
+ const createClient = async ({
324
+ allowedScopes = [],
325
+ controller,
326
+ createdBy = null,
327
+ description = null,
328
+ grantTypes = [ 'authorization_code' ],
329
+ name,
330
+ organization = null,
331
+ redirectUris = [],
332
+ webOrigins = []
333
+ }) => {
334
+
335
+ const invalid = allowedScopes.filter( ( scope ) => ! developer.includes( scope ) );
336
+
337
+ if( invalid.length > 0 ){
338
+
339
+ const error = new Error( 'Scopes not permitted for developer apps: ' + invalid.join( ', ' ) );
340
+
341
+ error.status = 400;
342
+
343
+ throw error;
344
+
345
+ }
346
+ const rawClientId = generateToken();
347
+ const clientId = 'drawbridge.' + rawClientId;
348
+
349
+ const rawSecret = generateToken();
350
+ const secretHash = hashToken( rawSecret );
351
+
352
+ const now = new Date();
353
+
354
+ const doc = await controller.insert({
355
+ collection : 'oauth',
356
+ data : {
357
+ allowedScopes,
358
+ clientId,
359
+ clientSecretHashes : [
360
+ {
361
+ createdAt : now,
362
+ hash : secretHash,
363
+ retiredAt : null
364
+ }
365
+ ],
366
+ clientType : 'confidential',
367
+ createdBy,
368
+ description,
369
+ grantTypes,
370
+ name,
371
+ organization,
372
+ rateLimitOverrides : null,
373
+ redirectUris,
374
+ status : 'active',
375
+ tokenEndpointAuthMethod : 'client_secret_basic',
376
+ webOrigins
377
+ }
378
+ });
379
+
380
+ return {
381
+ client : doc,
382
+ rawSecret
383
+ };
384
+
385
+ };
386
+
387
+ export { createClient, createOAuthModel, createOAuthServer };