update dependencies and devDependencies, address lint issues
[squeep-indie-auther] / src / db / abstract.js
1 /* eslint-disable no-unused-vars */
2 'use strict';
3
4 const common = require('../common');
5 const DatabaseErrors = require('./errors');
6 const svh = require('./schema-version-helper');
7 const uuid = require('uuid');
8
9 const _fileScope = common.fileScope(__filename);
10
11 class Database {
12 constructor(logger, options) {
13 this.logger = logger;
14 this.options = options;
15 }
16
17
18 /**
19 * Perform tasks needed to prepare database for use. Ensure this is called
20 * after construction, and before any other database activity.
21 * At the minimum, this will validate a compatible schema is present and usable.
22 * Some engines will also perform other initializations or async actions which
23 * are easier handled outside the constructor.
24 */
25 async initialize() {
26 const _scope = _fileScope('initialize');
27
28 const currentSchema = await this._currentSchema();
29 const current = svh.schemaVersionObjectToNumber(currentSchema);
30 const min = svh.schemaVersionObjectToNumber(this.schemaVersionsSupported.min);
31 const max = svh.schemaVersionObjectToNumber(this.schemaVersionsSupported.max);
32 if (current >= min && current <= max) {
33 this.logger.debug(_scope, 'schema supported', { currentSchema, schemaVersionsSupported: this.schemaVersionsSupported });
34 } else {
35 this.logger.error(_scope, 'schema not supported', { currentSchema, schemaVersionsSupported: this.schemaVersionsSupported });
36 throw new DatabaseErrors.MigrationNeeded();
37 }
38 }
39
40
41 /**
42 * @typedef {object} SchemaVersionObject
43 * @property {number} major major
44 * @property {number} minor minor
45 * @property {number} patch patch
46 */
47 /**
48 * Query the current schema version.
49 * This is a standalone query function, as it is called before statements are loaded.
50 * @returns {Promise<SchemaVersionObject>} schema version
51 */
52 async _currentSchema() {
53 this._notImplemented('_currentSchema', arguments);
54 }
55
56
57 /**
58 * Perform db connection health-check, if applicable.
59 * Throw something if a database situation should pull us out of a load-balancer.
60 */
61 async healthCheck() {
62 this._notImplemented('healthCheck', arguments);
63 }
64
65
66 /**
67 * Wrap a function call in a database context.
68 * @param {Function} fn fn(ctx)
69 */
70 async context(fn) {
71 this._notImplemented('context', arguments);
72 }
73
74 /**
75 * Wrap a function call in a transaction context.
76 * @param {*} dbCtx db context
77 * @param {Function} fn fn(txCtx)
78 */
79 async transaction(dbCtx, fn) {
80 this._notImplemented('transaction', arguments);
81 }
82
83
84 /**
85 * Basic type checking of object properties.
86 *
87 * Types may be any of the built-in types:
88 * - boolean
89 * - bigint (also allowed with 'number')
90 * - function
91 * - number (this will also allow 'bigint')
92 * - object
93 * - string
94 * - symbol
95 * - undefined
96 *
97 * Types may also be any of the following:
98 * - array
99 * - buffer
100 * - date
101 * - infinites
102 * - null
103 * - uuid
104 * @param {object} object object
105 * @param {string[]} properties properties
106 * @param {string[]} types types
107 */
108 _ensureTypes(object, properties, types) {
109 const _scope = _fileScope('_ensureTypes');
110
111 if (!(object && properties && types)) {
112 this.logger.error(_scope, 'undefined argument', { object, properties, types });
113 throw new DatabaseErrors.DataValidation();
114 }
115
116 const supportedTypes = [
117 'array',
118 'bigint',
119 'boolean',
120 'buffer',
121 'date',
122 'function',
123 'infinites',
124 'null',
125 'number',
126 'object',
127 'string',
128 'symbol',
129 'undefined',
130 'uuid',
131 ];
132 types.forEach((t) => {
133 if (!supportedTypes.includes(t)) {
134 this.logger.error(_scope, 'unsupported type', { object, properties, types, unsupportedType: t });
135 throw new DatabaseErrors.DataValidation();
136 }
137 });
138
139 properties.forEach((p) => {
140 // eslint-disable-next-line security/detect-object-injection
141 const pObj = object[p];
142 const pType = typeof pObj;
143 if (!types.includes(pType)
144 && !(types.includes('array') && Array.isArray(pObj))
145 && !(types.includes('buffer') && pObj instanceof Buffer)
146 && !(types.includes('date') && pObj instanceof Date)
147 && !(types.includes('infinites') && Math.abs(pObj) === Infinity)
148 && !(types.includes('null') && pObj === null)
149 && !(types.includes('number') && pType === 'bigint')
150 && !(types.includes('uuid') && uuid.validate(pObj))) {
151 const reason = `'${p}' is '${pType}', but must be ${types.length > 1 ? 'one of ' : ''}'${types}'`;
152 this.logger.error(_scope, reason, {});
153 throw new DatabaseErrors.DataValidation(reason);
154 }
155 });
156 }
157
158
159 /**
160 * @typedef {object} Authentication
161 * @property {string} identifier identifier
162 * @property {string=} credential credential
163 * @property {Date} created created
164 * @property {Date=} lastAuthentication last authentication
165 */
166 /**
167 * @param {Authentication} authentication authentication
168 */
169 _validateAuthentication(authentication) {
170 [
171 [['identifier'], ['string']],
172 [['credential'], ['string', 'null']],
173 [['created'], ['date']],
174 [['lastAuthentication'], ['date', 'infinites']],
175 ].forEach(([properties, types]) => this._ensureTypes(authentication, properties, types));
176 }
177
178
179 /**
180 * @typedef {object} Resource
181 * @property {string} resourceId uuid
182 * @property {string} secret secret
183 * @property {string} description description
184 * @property {Date} created created at
185 */
186 /**
187 * @param {Resource} resource resource
188 */
189 _validateResource(resource) {
190 [
191 [['resourceId', 'secret', 'description'], ['string']],
192 [['resourceId'], ['uuid']],
193 [['created'], ['date']],
194 ].forEach(([properties, types]) => this._ensureTypes(resource, properties, types));
195 }
196
197
198 /**
199 * @typedef {object} Token
200 * @property {string} codeId uuid
201 * @property {string} profile profile
202 * @property {Date} created created at
203 * @property {Date=} expires expires at
204 * @property {Date=} refreshExpires refresh expires at
205 * @property {Date=} refreshed refreshed at
206 * @property {*=} duration duration
207 * @property {*=} refreshDuration refresh duration
208 * @property {number | bigint=} refresh_count refresh count
209 * @property {boolean} is_revoked is revoked
210 * @property {boolean} is_token is token
211 * @property {string} client_id client id
212 * @property {string[]} scopes scopes
213 * @property {object=} profileData profile data
214 */
215 /**
216 * @param {Token} token token
217 */
218 _validateToken(token) {
219 [
220 [['codeId', 'profile', 'clientId'], ['string']],
221 [['codeId'], ['uuid']],
222 [['created'], ['date']],
223 [['expires', 'refreshExpires', 'refreshed'], ['date', 'null']],
224 [['isToken', 'isRevoked'], ['boolean']],
225 [['scopes'], ['array']],
226 [['profileData'], ['object', 'null']],
227 ].forEach(([properties, types]) => this._ensureTypes(token, properties, types));
228 this._ensureTypes(token.scopes, Object.keys(token.scopes), ['string']);
229 }
230
231
232 /**
233 * Interface methods need implementations. Ensure the db-interaction
234 * methods on the base class call this, so they may be overridden by
235 * implementation classes.
236 * @param {string} method method
237 * @param {arguments} args args
238 */
239 _notImplemented(method, args) {
240 this.logger.error(_fileScope(method), 'abstract method called', Array.from(args));
241 throw new DatabaseErrors.NotImplemented(method);
242 }
243
244
245 /**
246 * Get all the almanac entries.
247 * @param {*} dbCtx db context
248 */
249 async almanacGetAll(dbCtx) {
250 this._notImplemented('almanacGetAll', arguments);
251 }
252
253
254 /**
255 * Insert or update an almanac entry.
256 * @param {*} dbCtx db context
257 * @param {string} event event
258 * @param {Date=} date date
259 */
260 async almanacUpsert(dbCtx, event, date) {
261 this._notImplemented('almanacUpsert', arguments);
262 }
263
264
265 /**
266 * Fetch the authentication record for an identifier.
267 * @param {*} dbCtx db context
268 * @param {string} identifier identifier
269 * @returns {Promise<Authentication>} authentication
270 */
271 async authenticationGet(dbCtx, identifier) {
272 this._notImplemented('authenticationGet', arguments);
273 }
274
275
276 /**
277 * Update the authentication record for the identifier that
278 * correct credentials have been supplied.
279 * @param {*} dbCtx db context
280 * @param {string} identifier identifier
281 * @returns {Promise<void>}
282 */
283 async authenticationSuccess(dbCtx, identifier) {
284 this._notImplemented('authenticationSuccess', arguments);
285 }
286
287
288 /**
289 * Insert or update the credential for an identifier.
290 * @param {*} dbCtx db context
291 * @param {string} identifier identifier
292 * @param {string} credential credential
293 * @param {string=} otpKey otp key
294 * @returns {Promise<void>}
295 */
296 async authenticationUpsert(dbCtx, identifier, credential, otpKey) {
297 this._notImplemented('authenticationUpsert', arguments);
298 }
299
300
301 /**
302 * Update the otpKey for an identifier.
303 * @param {*} dbCtx db context
304 * @param {string} identifier identifier
305 * @param {string=} otpKey otp key
306 * @returns {Promise<void>}
307 */
308 async authenticationUpdateOTPKey(dbCtx, identifier, otpKey) {
309 this._notImplemented('authenticationUpdateOTPKey', arguments);
310 }
311
312
313 /**
314 * Update the credential for an identifier.
315 * @param {*} dbCtx db context
316 * @param {string} identifier identifier
317 * @param {string} credential credential
318 * @returns {Promise<void>}
319 */
320 async authenticationUpdateCredential(dbCtx, identifier, credential) {
321 this._notImplemented('authenticationUpdateCredentials', arguments);
322 }
323
324
325 /**
326 * Determine if profile url is known to this service.
327 * @param {*} dbCtx db context
328 * @param {string} profile profile
329 * @returns {Promise<boolean>} is valid
330 */
331 async profileIsValid(dbCtx, profile) {
332 this._notImplemented('profileGet', arguments);
333 }
334
335
336 /**
337 * Insert a new relationship between a profile endpoint and
338 * an authenticated identifier.
339 * @param {*} dbCtx db context
340 * @param {string} profile profile
341 * @param {string} identifier identifier
342 * @returns {Promise<void>}
343 */
344 async profileIdentifierInsert(dbCtx, profile, identifier) {
345 this._notImplemented('profileIdentifierInsert', arguments);
346 }
347
348
349 /**
350 * Adds a scope to be available for a profile to include on any authorization request.
351 * @param {*} dbCtx db context
352 * @param {string} profile profile
353 * @param {string} scope scope
354 * @returns {Promise<void>}
355 */
356 async profileScopeInsert(dbCtx, profile, scope) {
357 this._notImplemented('profileScopeInsert', arguments);
358 }
359
360
361 /**
362 * @typedef {object} ScopeDetails
363 * @property {string} description description
364 * @property {string[]=} profiles profiles
365 */
366 /**
367 * @typedef {object} Profile
368 * @property {ScopeDetails} scope scope
369 */
370 /**
371 * @typedef {{[profile: string]: Profile}} ProfileScopes
372 */
373 /**
374 * @typedef {{[scope: string]: ScopeDetails}} ScopeIndex
375 * @property {ScopeDetails} scope scope details
376 */
377 /**
378 * @typedef {object} ProfilesScopesReturn
379 * @property {ProfileScopes} profileScopes profile scopes
380 * @property {ScopeIndex} scopeIndex scope index
381 * @property {string[]} profiles profiles
382 */
383 /**
384 * Returns an object containing:
385 * - an object with profiles as keys to objects with scopes as keys to scope objects,
386 * which each contain a description of the scope and a list of profiles offering it
387 * - an object with scopes as keys to the same scope objects
388 * - a list of profiles
389 * @param {*} dbCtx db context
390 * @param {string} identifier identifier
391 * @returns {Promise<ProfilesScopesReturn>} profiles scopes
392 */
393 async profilesScopesByIdentifier(dbCtx, identifier) {
394 this._notImplemented('profilesScopesByIdentifier', arguments);
395 }
396
397
398 /**
399 * @typedef ProfileScopesRow
400 * @property {string} profile profile
401 * @property {string} scope scope
402 * @property {string} description description
403 * @property {string} application application
404 * @property {boolean} isPermanent avoid cleanup
405 * @property {boolean} isManuallyAdded avoid cleanup
406 */
407 /**
408 * Convert db row data into associative structures.
409 * Same behavior is shared by multiple engines.
410 * @param {ProfileScopesRow[]} profileScopesRows profile scopes row
411 * @returns {ProfilesScopesReturn} profiles scopes
412 */
413 static _profilesScopesBuilder(profileScopesRows) {
414 const scopeIndex = {};
415 const profileScopes = {};
416 const profileSet = new Set();
417
418 (profileScopesRows || []).forEach(({ profile, scope, description, application, isPermanent, isManuallyAdded }) => {
419 if (scope && !(scope in scopeIndex)) {
420 scopeIndex[scope] = { // eslint-disable-line security/detect-object-injection
421 description,
422 application,
423 isPermanent,
424 isManuallyAdded,
425 profiles: [],
426 };
427 }
428 if (profile) {
429 profileSet.add(profile);
430 if (!(profile in profileScopes)) {
431 profileScopes[profile] = {}; // eslint-disable-line security/detect-object-injection
432 }
433 }
434 if (profile && scope) {
435 scopeIndex[scope].profiles.push(profile); // eslint-disable-line security/detect-object-injection
436 profileScopes[profile][scope] = scopeIndex[scope]; // eslint-disable-line security/detect-object-injection
437 }
438 });
439
440 return {
441 profiles: [...profileSet],
442 profileScopes,
443 scopeIndex,
444 };
445 }
446
447
448 /**
449 * Sets list of additional scopes available to profile.
450 * @param {*} dbCtx db context
451 * @param {string} profile profile
452 * @param {string[]} scopes scopes
453 * @returns {Promise<void>}
454 */
455 async profileScopesSetAll(dbCtx, profile, scopes) {
456 this._notImplemented('profileScopesSetAll', arguments);
457 }
458
459
460 /**
461 * Create (or revoke a duplicate) code as a token entry.
462 * @param {*} dbCtx db context
463 * @param {object} data data
464 * @param {string} data.codeId code id
465 * @param {Date} data.created created at
466 * @param {boolean} data.isToken is token
467 * @param {string} data.clientId client id
468 * @param {string} data.profile profile uri
469 * @param {string} data.identifier identifier
470 * @param {string[]} data.scopes scopesx
471 * @param {number | null} data.lifespanSeconds null sets expiration to Infinity
472 * @param {number | null} data.refreshLifespanSeconds null sets refresh to none
473 * @param {object | null} data.profileData profile data from profile uri
474 * @returns {Promise<boolean>} whether redemption was successful
475 */
476 async redeemCode(dbCtx, { codeId, created, isToken, clientId, profile, identifier, scopes, lifespanSeconds, refreshLifespanSeconds, profileData } = {}) {
477 this._notImplemented('redeemCode', arguments);
478 }
479
480
481 /**
482 * @typedef {object} RefreshedToken
483 * @property {Date} expires expires at
484 * @property {Date} refreshExpires refresh expires at
485 * @property {string[]=} scopes if scopes were reduced
486 */
487 /**
488 * Redeem a refresh token to renew token codeId.
489 * @param {*} dbCtx db context
490 * @param {string} codeId code id
491 * @param {Date} refreshed refreshed at
492 * @param {string[]} removeScopes remove scopes
493 * @returns {Promise<RefreshedToken>} refreshed token
494 */
495 async refreshCode(dbCtx, codeId, refreshed, removeScopes) {
496 this._notImplemented('refreshCode', arguments);
497 }
498
499
500 /**
501 * Fetch a resource server record.
502 * @param {*} dbCtx db context
503 * @param {string} resourceId uuid
504 * @returns {Promise<Resource>} resource
505 */
506 async resourceGet(dbCtx, resourceId) {
507 this._notImplemented('resourceGet', arguments);
508 }
509
510
511 /**
512 * Create, or update description of, a resourceId.
513 * @param {*} dbCtx db context
514 * @param {string=} resourceId uuid
515 * @param {string=} secret secret
516 * @param {string=} description description
517 * @returns {Promise<void>}
518 */
519 async resourceUpsert(dbCtx, resourceId, secret, description) {
520 this._notImplemented('resourceUpsert', arguments);
521 }
522
523
524 /**
525 * Register a scope and its description.
526 * @param {*} dbCtx db context
527 * @param {string} scope scope
528 * @param {string} application application
529 * @param {string} description description
530 * @param {boolean} manuallyAdded is manually added
531 * @returns {Promise<void>}
532 */
533 async scopeUpsert(dbCtx, scope, application, description, manuallyAdded = false) {
534 this._notImplemented('scopeUpsert', arguments);
535 }
536
537
538 /**
539 * Remove a non-permanent scope if it is not currently in use.
540 * @param {*} dbCtx db context
541 * @param {string} scope scope
542 * @returns {Promise<boolean>} deleted
543 */
544 async scopeDelete(dbCtx, scope) {
545 this._notImplemented('scopeDelete', arguments);
546 }
547
548
549 /**
550 * @typedef {number | bigint} CleanupResult
551 */
552 /**
553 * @alias {object} CleanupResult
554 */
555 /**
556 * Remove any non-permanent and non-manually-created scopes not currently in use.
557 * @param {*} dbCtx db context
558 * @param {number} atLeastMsSinceLast skip cleanup if already executed this recently
559 * @returns {Promise<CleanupResult>} cleanup result
560 */
561 async scopeCleanup(dbCtx, atLeastMsSinceLast) {
562 this._notImplemented('scopeClean', arguments);
563 }
564
565
566 /**
567 * Forget tokens after they have expired, and redeemed codes after they have expired.
568 * @param {*} dbCtx db context
569 * @param {number} codeLifespanSeconds code lifespan seconds
570 * @param {number} atLeastMsSinceLast skip cleanup if already executed this recently
571 * @returns {Promise<CleanupResult>} cleanup result
572 */
573 async tokenCleanup(dbCtx, codeLifespanSeconds, atLeastMsSinceLast) {
574 this._notImplemented('tokenCleanup', arguments);
575 }
576
577
578 /**
579 * Look up a redeemed token by code_id.
580 * @param {*} dbCtx db context
581 * @param {string} codeId code id
582 * @returns {Promise<Token>} token
583 */
584 async tokenGetByCodeId(dbCtx, codeId) {
585 this._notImplemented('tokenGetByCodeId', arguments);
586 }
587
588
589 /**
590 * Sets a redeemed token as revoked.
591 * @param {*} dbCtx db context
592 * @param {string} codeId - uuid
593 * @returns {Promise<void>}
594 */
595 async tokenRevokeByCodeId(dbCtx, codeId) {
596 this._notImplemented('tokenRevokeByCodeId', arguments);
597 }
598
599
600 /**
601 * Revoke the refreshability of a codeId.
602 * @param {*} dbCtx db context
603 * @param {string} codeId - uuid
604 * @returns {Promise<void>}
605 */
606 async tokenRefreshRevokeByCodeId(dbCtx, codeId) {
607 this._notImplemented('tokenRefreshRevokeByCodeId', arguments);
608 }
609
610
611 /**
612 * Get all tokens assigned to identifier.
613 * @param {*} dbCtx db context
614 * @param {string} identifier identifier
615 * @returns {Promise<Token[]>} token
616 */
617 async tokensGetByIdentifier(dbCtx, identifier) {
618 this._notImplemented('tokensGetByIdentifier', arguments);
619 }
620
621
622 /**
623 * @typedef {object} RedeemedTicketData
624 * @property {string} subject subject
625 * @property {string} resource resource
626 * @property {string=} iss issuer
627 * @property {string} ticket ticket
628 * @property {string} token token
629 */
630 /**
631 * Persist details of a redeemed ticket.
632 * @param {*} dbCtx db context
633 * @param {RedeemedTicketData} redeemedData redeemed data
634 * @returns {Promise<void>}
635 */
636 async ticketRedeemed(dbCtx, redeemedData) {
637 this._notImplemented('ticketRedeemed', arguments);
638 }
639
640
641 /**
642 * Update details of a redeemed ticket that it has been published.
643 * @param {*} dbCtx db context
644 * @param {RedeemedTicketData} redeemedData redeemed data
645 * @returns {Promise<void>}
646 */
647 async ticketTokenPublished(dbCtx, redeemedData) {
648 this._notImplemented('ticketTokenPublished', arguments);
649 }
650
651
652 /**
653 * Retrieve redeemed tokens which have not yet been published to queue.
654 * @param {*} dbCtx db context
655 * @param {number} limit limit
656 * @returns {Promise<RedeemedTicketData[]>} redeemed but not published
657 */
658 async ticketTokenGetUnpublished(dbCtx, limit) {
659 this._notImplemented('ticketTokenGetUnpublished', arguments);
660 }
661
662 }
663
664 module.exports = Database;