repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/toidentifier/index.js
aws/lti-middleware/node_modules/toidentifier/index.js
/*! * toidentifier * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = toIdentifier /** * Trasform the given string into a JavaScript identifier * * @param {string} str * @returns {string} * @public */ function toIdentifier (str) { return str .split(' ') .map(function (token) { return token.slice(0, 1).toUpperCase() + token.slice(1) }) .join('') .replace(/[^ _0-9a-z]/gi, '') }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/depd/index.js
aws/lti-middleware/node_modules/depd/index.js
/*! * depd * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. */ var callSiteToString = require('./lib/compat').callSiteToString var eventListenerCount = require('./lib/compat').eventListenerCount var relative = require('path').relative /** * Module exports. */ module.exports = depd /** * Get the path to base files on. */ var basePath = process.cwd() /** * Determine if namespace is contained in the string. */ function containsNamespace (str, namespace) { var vals = str.split(/[ ,]+/) var ns = String(namespace).toLowerCase() for (var i = 0; i < vals.length; i++) { var val = vals[i] // namespace contained if (val && (val === '*' || val.toLowerCase() === ns)) { return true } } return false } /** * Convert a data descriptor to accessor descriptor. */ function convertDataDescriptorToAccessor (obj, prop, message) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop) var value = descriptor.value descriptor.get = function getter () { return value } if (descriptor.writable) { descriptor.set = function setter (val) { return (value = val) } } delete descriptor.value delete descriptor.writable Object.defineProperty(obj, prop, descriptor) return descriptor } /** * Create arguments string to keep arity. */ function createArgumentsString (arity) { var str = '' for (var i = 0; i < arity; i++) { str += ', arg' + i } return str.substr(2) } /** * Create stack string from stack. */ function createStackString (stack) { var str = this.name + ': ' + this.namespace if (this.message) { str += ' deprecated ' + this.message } for (var i = 0; i < stack.length; i++) { str += '\n at ' + callSiteToString(stack[i]) } return str } /** * Create deprecate for namespace in caller. */ function depd (namespace) { if (!namespace) { throw new TypeError('argument namespace is required') } var stack = getStack() var site = callSiteLocation(stack[1]) var file = site[0] function deprecate (message) { // call to self as log log.call(deprecate, message) } deprecate._file = file deprecate._ignored = isignored(namespace) deprecate._namespace = namespace deprecate._traced = istraced(namespace) deprecate._warned = Object.create(null) deprecate.function = wrapfunction deprecate.property = wrapproperty return deprecate } /** * Determine if namespace is ignored. */ function isignored (namespace) { /* istanbul ignore next: tested in a child processs */ if (process.noDeprecation) { // --no-deprecation support return true } var str = process.env.NO_DEPRECATION || '' // namespace ignored return containsNamespace(str, namespace) } /** * Determine if namespace is traced. */ function istraced (namespace) { /* istanbul ignore next: tested in a child processs */ if (process.traceDeprecation) { // --trace-deprecation support return true } var str = process.env.TRACE_DEPRECATION || '' // namespace traced return containsNamespace(str, namespace) } /** * Display deprecation message. */ function log (message, site) { var haslisteners = eventListenerCount(process, 'deprecation') !== 0 // abort early if no destination if (!haslisteners && this._ignored) { return } var caller var callFile var callSite var depSite var i = 0 var seen = false var stack = getStack() var file = this._file if (site) { // provided site depSite = site callSite = callSiteLocation(stack[1]) callSite.name = depSite.name file = callSite[0] } else { // get call site i = 2 depSite = callSiteLocation(stack[i]) callSite = depSite } // get caller of deprecated thing in relation to file for (; i < stack.length; i++) { caller = callSiteLocation(stack[i]) callFile = caller[0] if (callFile === file) { seen = true } else if (callFile === this._file) { file = this._file } else if (seen) { break } } var key = caller ? depSite.join(':') + '__' + caller.join(':') : undefined if (key !== undefined && key in this._warned) { // already warned return } this._warned[key] = true // generate automatic message from call site var msg = message if (!msg) { msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite) } // emit deprecation if listeners exist if (haslisteners) { var err = DeprecationError(this._namespace, msg, stack.slice(i)) process.emit('deprecation', err) return } // format and write message var format = process.stderr.isTTY ? formatColor : formatPlain var output = format.call(this, msg, caller, stack.slice(i)) process.stderr.write(output + '\n', 'utf8') } /** * Get call site location as array. */ function callSiteLocation (callSite) { var file = callSite.getFileName() || '<anonymous>' var line = callSite.getLineNumber() var colm = callSite.getColumnNumber() if (callSite.isEval()) { file = callSite.getEvalOrigin() + ', ' + file } var site = [file, line, colm] site.callSite = callSite site.name = callSite.getFunctionName() return site } /** * Generate a default message from the site. */ function defaultMessage (site) { var callSite = site.callSite var funcName = site.name // make useful anonymous name if (!funcName) { funcName = '<anonymous@' + formatLocation(site) + '>' } var context = callSite.getThis() var typeName = context && callSite.getTypeName() // ignore useless type name if (typeName === 'Object') { typeName = undefined } // make useful type name if (typeName === 'Function') { typeName = context.name || typeName } return typeName && callSite.getMethodName() ? typeName + '.' + funcName : funcName } /** * Format deprecation message without color. */ function formatPlain (msg, caller, stack) { var timestamp = new Date().toUTCString() var formatted = timestamp + ' ' + this._namespace + ' deprecated ' + msg // add stack trace if (this._traced) { for (var i = 0; i < stack.length; i++) { formatted += '\n at ' + callSiteToString(stack[i]) } return formatted } if (caller) { formatted += ' at ' + formatLocation(caller) } return formatted } /** * Format deprecation message with color. */ function formatColor (msg, caller, stack) { var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow ' \x1b[0m' + msg + '\x1b[39m' // reset // add stack trace if (this._traced) { for (var i = 0; i < stack.length; i++) { formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan } return formatted } if (caller) { formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan } return formatted } /** * Format call site location. */ function formatLocation (callSite) { return relative(basePath, callSite[0]) + ':' + callSite[1] + ':' + callSite[2] } /** * Get the stack as array of call sites. */ function getStack () { var limit = Error.stackTraceLimit var obj = {} var prep = Error.prepareStackTrace Error.prepareStackTrace = prepareObjectStackTrace Error.stackTraceLimit = Math.max(10, limit) // capture the stack Error.captureStackTrace(obj) // slice this function off the top var stack = obj.stack.slice(1) Error.prepareStackTrace = prep Error.stackTraceLimit = limit return stack } /** * Capture call site stack from v8. */ function prepareObjectStackTrace (obj, stack) { return stack } /** * Return a wrapped function in a deprecation message. */ function wrapfunction (fn, message) { if (typeof fn !== 'function') { throw new TypeError('argument fn must be a function') } var args = createArgumentsString(fn.length) var deprecate = this // eslint-disable-line no-unused-vars var stack = getStack() var site = callSiteLocation(stack[1]) site.name = fn.name // eslint-disable-next-line no-eval var deprecatedfn = eval('(function (' + args + ') {\n' + '"use strict"\n' + 'log.call(deprecate, message, site)\n' + 'return fn.apply(this, arguments)\n' + '})') return deprecatedfn } /** * Wrap property in a deprecation message. */ function wrapproperty (obj, prop, message) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new TypeError('argument obj must be object') } var descriptor = Object.getOwnPropertyDescriptor(obj, prop) if (!descriptor) { throw new TypeError('must call property on owner object') } if (!descriptor.configurable) { throw new TypeError('property must be configurable') } var deprecate = this var stack = getStack() var site = callSiteLocation(stack[1]) // set site name site.name = prop // convert data descriptor if ('value' in descriptor) { descriptor = convertDataDescriptorToAccessor(obj, prop, message) } var get = descriptor.get var set = descriptor.set // wrap getter if (typeof get === 'function') { descriptor.get = function getter () { log.call(deprecate, message, site) return get.apply(this, arguments) } } // wrap setter if (typeof set === 'function') { descriptor.set = function setter () { log.call(deprecate, message, site) return set.apply(this, arguments) } } Object.defineProperty(obj, prop, descriptor) } /** * Create DeprecationError for deprecation */ function DeprecationError (namespace, message, stack) { var error = new Error() var stackString Object.defineProperty(error, 'constructor', { value: DeprecationError }) Object.defineProperty(error, 'message', { configurable: true, enumerable: false, value: message, writable: true }) Object.defineProperty(error, 'name', { enumerable: false, configurable: true, value: 'DeprecationError', writable: true }) Object.defineProperty(error, 'namespace', { configurable: true, enumerable: false, value: namespace, writable: true }) Object.defineProperty(error, 'stack', { configurable: true, enumerable: false, get: function () { if (stackString !== undefined) { return stackString } // prepare stack trace return (stackString = createStackString.call(this, stack)) }, set: function setter (val) { stackString = val } }) return error }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/depd/lib/compat/event-listener-count.js
aws/lti-middleware/node_modules/depd/lib/compat/event-listener-count.js
/*! * depd * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = eventListenerCount /** * Get the count of listeners on an event emitter of a specific type. */ function eventListenerCount (emitter, type) { return emitter.listeners(type).length }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/depd/lib/compat/index.js
aws/lti-middleware/node_modules/depd/lib/compat/index.js
/*! * depd * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var EventEmitter = require('events').EventEmitter /** * Module exports. * @public */ lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { var limit = Error.stackTraceLimit var obj = {} var prep = Error.prepareStackTrace function prepareObjectStackTrace (obj, stack) { return stack } Error.prepareStackTrace = prepareObjectStackTrace Error.stackTraceLimit = 2 // capture the stack Error.captureStackTrace(obj) // slice the stack var stack = obj.stack.slice() Error.prepareStackTrace = prep Error.stackTraceLimit = limit return stack[0].toString ? toString : require('./callsite-tostring') }) lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { return EventEmitter.listenerCount || require('./event-listener-count') }) /** * Define a lazy property. */ function lazyProperty (obj, prop, getter) { function get () { var val = getter() Object.defineProperty(obj, prop, { configurable: true, enumerable: true, value: val }) return val } Object.defineProperty(obj, prop, { configurable: true, enumerable: true, get: get }) } /** * Call toString() on the obj */ function toString (obj) { return obj.toString() }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/depd/lib/compat/callsite-tostring.js
aws/lti-middleware/node_modules/depd/lib/compat/callsite-tostring.js
/*! * depd * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. */ module.exports = callSiteToString /** * Format a CallSite file location to a string. */ function callSiteFileLocation (callSite) { var fileName var fileLocation = '' if (callSite.isNative()) { fileLocation = 'native' } else if (callSite.isEval()) { fileName = callSite.getScriptNameOrSourceURL() if (!fileName) { fileLocation = callSite.getEvalOrigin() } } else { fileName = callSite.getFileName() } if (fileName) { fileLocation += fileName var lineNumber = callSite.getLineNumber() if (lineNumber != null) { fileLocation += ':' + lineNumber var columnNumber = callSite.getColumnNumber() if (columnNumber) { fileLocation += ':' + columnNumber } } } return fileLocation || 'unknown source' } /** * Format a CallSite to a string. */ function callSiteToString (callSite) { var addSuffix = true var fileLocation = callSiteFileLocation(callSite) var functionName = callSite.getFunctionName() var isConstructor = callSite.isConstructor() var isMethodCall = !(callSite.isToplevel() || isConstructor) var line = '' if (isMethodCall) { var methodName = callSite.getMethodName() var typeName = getConstructorName(callSite) if (functionName) { if (typeName && functionName.indexOf(typeName) !== 0) { line += typeName + '.' } line += functionName if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { line += ' [as ' + methodName + ']' } } else { line += typeName + '.' + (methodName || '<anonymous>') } } else if (isConstructor) { line += 'new ' + (functionName || '<anonymous>') } else if (functionName) { line += functionName } else { addSuffix = false line += fileLocation } if (addSuffix) { line += ' (' + fileLocation + ')' } return line } /** * Get constructor name of reviver. */ function getConstructorName (obj) { var receiver = obj.receiver return (receiver.constructor && receiver.constructor.name) || null }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/depd/lib/browser/index.js
aws/lti-middleware/node_modules/depd/lib/browser/index.js
/*! * depd * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = depd /** * Create deprecate for namespace in caller. */ function depd (namespace) { if (!namespace) { throw new TypeError('argument namespace is required') } function deprecate (message) { // no-op in browser } deprecate._file = undefined deprecate._ignored = true deprecate._namespace = namespace deprecate._traced = false deprecate._warned = Object.create(null) deprecate.function = wrapfunction deprecate.property = wrapproperty return deprecate } /** * Return a wrapped function in a deprecation message. * * This is a no-op version of the wrapper, which does nothing but call * validation. */ function wrapfunction (fn, message) { if (typeof fn !== 'function') { throw new TypeError('argument fn must be a function') } return fn } /** * Wrap property in a deprecation message. * * This is a no-op version of the wrapper, which does nothing but call * validation. */ function wrapproperty (obj, prop, message) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new TypeError('argument obj must be object') } var descriptor = Object.getOwnPropertyDescriptor(obj, prop) if (!descriptor) { throw new TypeError('must call property on owner object') } if (!descriptor.configurable) { throw new TypeError('property must be configurable') } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const firebase = require("./default-namespace"); // Only Node.js has a process variable that is of [[Class]] process const processGlobal = typeof process !== 'undefined' ? process : 0; if (Object.prototype.toString.call(processGlobal) !== '[object process]') { const message = ` ======== WARNING! ======== firebase-admin appears to have been installed in an unsupported environment. This package should only be used in server-side or backend Node.js environments, and should not be used in web browsers or other client-side environments. Use the Firebase JS SDK for client-side Firebase integrations: https://firebase.google.com/docs/web/setup `; // tslint:disable-next-line:no-console console.error(message); } module.exports = firebase;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/default-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/default-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const firebase_namespace_1 = require("./app/firebase-namespace"); // Inject a circular default export to allow users to use both: // // import firebaseAdmin from 'firebase-admin'; // which becomes: var firebaseAdmin = require('firebase-admin').default; // // as well as the more correct: // // import * as firebaseAdmin from 'firebase-admin'; // which becomes: var firebaseAdmin = require('firebase-admin'); firebase_namespace_1.defaultNamespace.default = firebase_namespace_1.defaultNamespace; module.exports = firebase_namespace_1.defaultNamespace;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/firebase-namespace-api.js
aws/lti-middleware/node_modules/firebase-admin/lib/firebase-namespace-api.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.storage = exports.securityRules = exports.remoteConfig = exports.projectManagement = exports.messaging = exports.machineLearning = exports.installations = exports.instanceId = exports.firestore = exports.database = exports.auth = exports.appCheck = void 0; __exportStar(require("./credential/index"), exports); var app_check_namespace_1 = require("./app-check/app-check-namespace"); Object.defineProperty(exports, "appCheck", { enumerable: true, get: function () { return app_check_namespace_1.appCheck; } }); var auth_namespace_1 = require("./auth/auth-namespace"); Object.defineProperty(exports, "auth", { enumerable: true, get: function () { return auth_namespace_1.auth; } }); var database_namespace_1 = require("./database/database-namespace"); Object.defineProperty(exports, "database", { enumerable: true, get: function () { return database_namespace_1.database; } }); var firestore_namespace_1 = require("./firestore/firestore-namespace"); Object.defineProperty(exports, "firestore", { enumerable: true, get: function () { return firestore_namespace_1.firestore; } }); var instance_id_namespace_1 = require("./instance-id/instance-id-namespace"); Object.defineProperty(exports, "instanceId", { enumerable: true, get: function () { return instance_id_namespace_1.instanceId; } }); var installations_namespace_1 = require("./installations/installations-namespace"); Object.defineProperty(exports, "installations", { enumerable: true, get: function () { return installations_namespace_1.installations; } }); var machine_learning_namespace_1 = require("./machine-learning/machine-learning-namespace"); Object.defineProperty(exports, "machineLearning", { enumerable: true, get: function () { return machine_learning_namespace_1.machineLearning; } }); var messaging_namespace_1 = require("./messaging/messaging-namespace"); Object.defineProperty(exports, "messaging", { enumerable: true, get: function () { return messaging_namespace_1.messaging; } }); var project_management_namespace_1 = require("./project-management/project-management-namespace"); Object.defineProperty(exports, "projectManagement", { enumerable: true, get: function () { return project_management_namespace_1.projectManagement; } }); var remote_config_namespace_1 = require("./remote-config/remote-config-namespace"); Object.defineProperty(exports, "remoteConfig", { enumerable: true, get: function () { return remote_config_namespace_1.remoteConfig; } }); var security_rules_namespace_1 = require("./security-rules/security-rules-namespace"); Object.defineProperty(exports, "securityRules", { enumerable: true, get: function () { return security_rules_namespace_1.securityRules; } }); var storage_namespace_1 = require("./storage/storage-namespace"); Object.defineProperty(exports, "storage", { enumerable: true, get: function () { return storage_namespace_1.storage; } });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/storage/storage.js
aws/lti-middleware/node_modules/firebase-admin/lib/storage/storage.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Storage = void 0; const error_1 = require("../utils/error"); const credential_internal_1 = require("../app/credential-internal"); const utils = require("../utils/index"); const validator = require("../utils/validator"); /** * The default `Storage` service if no * app is provided or the `Storage` service associated with the provided * app. */ class Storage { /** * @param app - The app for this Storage service. * @constructor * @internal */ constructor(app) { if (!validator.isNonNullObject(app) || !('options' in app)) { throw new error_1.FirebaseError({ code: 'storage/invalid-argument', message: 'First argument passed to admin.storage() must be a valid Firebase app instance.', }); } if (!process.env.STORAGE_EMULATOR_HOST && process.env.FIREBASE_STORAGE_EMULATOR_HOST) { const firebaseStorageEmulatorHost = process.env.FIREBASE_STORAGE_EMULATOR_HOST; if (firebaseStorageEmulatorHost.match(/https?:\/\//)) { throw new error_1.FirebaseError({ code: 'storage/invalid-emulator-host', message: 'FIREBASE_STORAGE_EMULATOR_HOST should not contain a protocol (http or https).', }); } process.env.STORAGE_EMULATOR_HOST = `http://${process.env.FIREBASE_STORAGE_EMULATOR_HOST}`; } let storage; try { storage = require('@google-cloud/storage').Storage; } catch (err) { throw new error_1.FirebaseError({ code: 'storage/missing-dependencies', message: 'Failed to import the Cloud Storage client library for Node.js. ' + 'Make sure to install the "@google-cloud/storage" npm package. ' + `Original error: ${err}`, }); } const projectId = utils.getExplicitProjectId(app); const credential = app.options.credential; if (credential instanceof credential_internal_1.ServiceAccountCredential) { this.storageClient = new storage({ // When the SDK is initialized with ServiceAccountCredentials an explicit projectId is // guaranteed to be available. projectId: projectId, credentials: { private_key: credential.privateKey, client_email: credential.clientEmail, }, }); } else if ((0, credential_internal_1.isApplicationDefault)(app.options.credential)) { // Try to use the Google application default credentials. this.storageClient = new storage(); } else { throw new error_1.FirebaseError({ code: 'storage/invalid-credential', message: 'Failed to initialize Google Cloud Storage client with the available credential. ' + 'Must initialize the SDK with a certificate credential or application default credentials ' + 'to use Cloud Storage API.', }); } this.appInternal = app; } /** * Gets a reference to a Cloud Storage bucket. * * @param name - Optional name of the bucket to be retrieved. If name is not specified, * retrieves a reference to the default bucket. * @returns A {@link https://cloud.google.com/nodejs/docs/reference/storage/latest/Bucket | Bucket} * instance as defined in the `@google-cloud/storage` package. */ bucket(name) { const bucketName = (typeof name !== 'undefined') ? name : this.appInternal.options.storageBucket; if (validator.isNonEmptyString(bucketName)) { return this.storageClient.bucket(bucketName); } throw new error_1.FirebaseError({ code: 'storage/invalid-argument', message: 'Bucket name not specified or invalid. Specify a valid bucket name via the ' + 'storageBucket option when initializing the app, or specify the bucket name ' + 'explicitly when calling the getBucket() method.', }); } /** * Optional app whose `Storage` service to * return. If not provided, the default `Storage` service will be returned. */ get app() { return this.appInternal; } } exports.Storage = Storage;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/storage/storage-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/storage/storage-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/storage/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/storage/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getStorage = exports.Storage = void 0; /** * Cloud Storage for Firebase. * * @packageDocumentation */ const app_1 = require("../app"); const storage_1 = require("./storage"); var storage_2 = require("./storage"); Object.defineProperty(exports, "Storage", { enumerable: true, get: function () { return storage_2.Storage; } }); /** * Gets the {@link Storage} service for the default app or a given app. * * `getStorage()` can be called with no arguments to access the default * app's `Storage` service or as `getStorage(app)` to access the * `Storage` service associated with a specific app. * * @example * ```javascript * // Get the Storage service for the default app * const defaultStorage = getStorage(); * ``` * * @example * ```javascript * // Get the Storage service for a given app * const otherStorage = getStorage(otherApp); * ``` */ function getStorage(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('storage', (app) => new storage_1.Storage(app)); } exports.getStorage = getStorage;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/token-verifier.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/token-verifier.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.createSessionCookieVerifier = exports.createAuthBlockingTokenVerifier = exports.createIdTokenVerifier = exports.FirebaseTokenVerifier = exports.SESSION_COOKIE_INFO = exports.AUTH_BLOCKING_TOKEN_INFO = exports.ID_TOKEN_INFO = void 0; const error_1 = require("../utils/error"); const util = require("../utils/index"); const validator = require("../utils/validator"); const jwt_1 = require("../utils/jwt"); // Audience to use for Firebase Auth Custom tokens const FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit'; // URL containing the public keys for the Google certs (whose private keys are used to sign Firebase // Auth ID tokens) const CLIENT_CERT_URL = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'; // URL containing the public keys for Firebase session cookies. This will be updated to a different URL soon. const SESSION_COOKIE_CERT_URL = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys'; const EMULATOR_VERIFIER = new jwt_1.EmulatorSignatureVerifier(); /** * User facing token information related to the Firebase ID token. * * @internal */ exports.ID_TOKEN_INFO = { url: 'https://firebase.google.com/docs/auth/admin/verify-id-tokens', verifyApiName: 'verifyIdToken()', jwtName: 'Firebase ID token', shortName: 'ID token', expiredErrorCode: error_1.AuthClientErrorCode.ID_TOKEN_EXPIRED, }; /** * User facing token information related to the Firebase Auth Blocking token. * * @internal */ exports.AUTH_BLOCKING_TOKEN_INFO = { url: 'https://cloud.google.com/identity-platform/docs/blocking-functions', verifyApiName: '_verifyAuthBlockingToken()', jwtName: 'Firebase Auth Blocking token', shortName: 'Auth Blocking token', expiredErrorCode: error_1.AuthClientErrorCode.AUTH_BLOCKING_TOKEN_EXPIRED, }; /** * User facing token information related to the Firebase session cookie. * * @internal */ exports.SESSION_COOKIE_INFO = { url: 'https://firebase.google.com/docs/auth/admin/manage-cookies', verifyApiName: 'verifySessionCookie()', jwtName: 'Firebase session cookie', shortName: 'session cookie', expiredErrorCode: error_1.AuthClientErrorCode.SESSION_COOKIE_EXPIRED, }; /** * Class for verifying general purpose Firebase JWTs. This verifies ID tokens and session cookies. * * @internal */ class FirebaseTokenVerifier { constructor(clientCertUrl, issuer, tokenInfo, app) { this.issuer = issuer; this.tokenInfo = tokenInfo; this.app = app; if (!validator.isURL(clientCertUrl)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided public client certificate URL is an invalid URL.'); } else if (!validator.isURL(issuer)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT issuer is an invalid URL.'); } else if (!validator.isNonNullObject(tokenInfo)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT information is not an object or null.'); } else if (!validator.isURL(tokenInfo.url)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT verification documentation URL is invalid.'); } else if (!validator.isNonEmptyString(tokenInfo.verifyApiName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT verify API name must be a non-empty string.'); } else if (!validator.isNonEmptyString(tokenInfo.jwtName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT public full name must be a non-empty string.'); } else if (!validator.isNonEmptyString(tokenInfo.shortName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT public short name must be a non-empty string.'); } else if (!validator.isNonNullObject(tokenInfo.expiredErrorCode) || !('code' in tokenInfo.expiredErrorCode)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT expiration error code must be a non-null ErrorInfo object.'); } this.shortNameArticle = tokenInfo.shortName.charAt(0).match(/[aeiou]/i) ? 'an' : 'a'; this.signatureVerifier = jwt_1.PublicKeySignatureVerifier.withCertificateUrl(clientCertUrl, app.options.httpAgent); // For backward compatibility, the project ID is validated in the verification call. } /** * Verifies the format and signature of a Firebase Auth JWT token. * * @param jwtToken - The Firebase Auth JWT token to verify. * @param isEmulator - Whether to accept Auth Emulator tokens. * @returns A promise fulfilled with the decoded claims of the Firebase Auth ID token. */ verifyJWT(jwtToken, isEmulator = false) { if (!validator.isString(jwtToken)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `First argument to ${this.tokenInfo.verifyApiName} must be a ${this.tokenInfo.jwtName} string.`); } return this.ensureProjectId() .then((projectId) => { return this.decodeAndVerify(jwtToken, projectId, isEmulator); }) .then((decoded) => { const decodedIdToken = decoded.payload; decodedIdToken.uid = decodedIdToken.sub; return decodedIdToken; }); } /** @alpha */ // eslint-disable-next-line @typescript-eslint/naming-convention _verifyAuthBlockingToken(jwtToken, isEmulator, audience) { if (!validator.isString(jwtToken)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `First argument to ${this.tokenInfo.verifyApiName} must be a ${this.tokenInfo.jwtName} string.`); } return this.ensureProjectId() .then((projectId) => { if (typeof audience === 'undefined') { audience = `${projectId}.cloudfunctions.net/`; } return this.decodeAndVerify(jwtToken, projectId, isEmulator, audience); }) .then((decoded) => { const decodedAuthBlockingToken = decoded.payload; decodedAuthBlockingToken.uid = decodedAuthBlockingToken.sub; return decodedAuthBlockingToken; }); } ensureProjectId() { return util.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'Must initialize app with a cert credential or set your Firebase project ID as the ' + `GOOGLE_CLOUD_PROJECT environment variable to call ${this.tokenInfo.verifyApiName}.`); } return Promise.resolve(projectId); }); } decodeAndVerify(token, projectId, isEmulator, audience) { return this.safeDecode(token) .then((decodedToken) => { this.verifyContent(decodedToken, projectId, isEmulator, audience); return this.verifySignature(token, isEmulator) .then(() => decodedToken); }); } safeDecode(jwtToken) { return (0, jwt_1.decodeJwt)(jwtToken) .catch((err) => { if (err.code == jwt_1.JwtErrorCode.INVALID_ARGUMENT) { const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; const errorMessage = `Decoding ${this.tokenInfo.jwtName} failed. Make sure you passed ` + `the entire string JWT which represents ${this.shortNameArticle} ` + `${this.tokenInfo.shortName}.` + verifyJwtTokenDocsMessage; throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, err.message); }); } /** * Verifies the content of a Firebase Auth JWT. * * @param fullDecodedToken - The decoded JWT. * @param projectId - The Firebase Project Id. * @param isEmulator - Whether the token is an Emulator token. */ verifyContent(fullDecodedToken, projectId, isEmulator, audience) { const header = fullDecodedToken && fullDecodedToken.header; const payload = fullDecodedToken && fullDecodedToken.payload; const projectIdMatchMessage = ` Make sure the ${this.tokenInfo.shortName} comes from the same ` + 'Firebase project as the service account used to authenticate this SDK.'; const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; let errorMessage; if (!isEmulator && typeof header.kid === 'undefined') { const isCustomToken = (payload.aud === FIREBASE_AUDIENCE); const isLegacyCustomToken = (header.alg === 'HS256' && payload.v === 0 && 'd' in payload && 'uid' in payload.d); if (isCustomToken) { errorMessage = `${this.tokenInfo.verifyApiName} expects ${this.shortNameArticle} ` + `${this.tokenInfo.shortName}, but was given a custom token.`; } else if (isLegacyCustomToken) { errorMessage = `${this.tokenInfo.verifyApiName} expects ${this.shortNameArticle} ` + `${this.tokenInfo.shortName}, but was given a legacy custom token.`; } else { errorMessage = `${this.tokenInfo.jwtName} has no "kid" claim.`; } errorMessage += verifyJwtTokenDocsMessage; } else if (!isEmulator && header.alg !== jwt_1.ALGORITHM_RS256) { errorMessage = `${this.tokenInfo.jwtName} has incorrect algorithm. Expected "` + jwt_1.ALGORITHM_RS256 + '" but got ' + '"' + header.alg + '".' + verifyJwtTokenDocsMessage; } else if (typeof audience !== 'undefined' && !payload.aud.includes(audience)) { errorMessage = `${this.tokenInfo.jwtName} has incorrect "aud" (audience) claim. Expected "` + audience + '" but got "' + payload.aud + '".' + verifyJwtTokenDocsMessage; } else if (typeof audience === 'undefined' && payload.aud !== projectId) { errorMessage = `${this.tokenInfo.jwtName} has incorrect "aud" (audience) claim. Expected "` + projectId + '" but got "' + payload.aud + '".' + projectIdMatchMessage + verifyJwtTokenDocsMessage; } else if (payload.iss !== this.issuer + projectId) { errorMessage = `${this.tokenInfo.jwtName} has incorrect "iss" (issuer) claim. Expected ` + `"${this.issuer}` + projectId + '" but got "' + payload.iss + '".' + projectIdMatchMessage + verifyJwtTokenDocsMessage; } else if (typeof payload.sub !== 'string') { errorMessage = `${this.tokenInfo.jwtName} has no "sub" (subject) claim.` + verifyJwtTokenDocsMessage; } else if (payload.sub === '') { errorMessage = `${this.tokenInfo.jwtName} has an empty string "sub" (subject) claim.` + verifyJwtTokenDocsMessage; } else if (payload.sub.length > 128) { errorMessage = `${this.tokenInfo.jwtName} has "sub" (subject) claim longer than 128 characters.` + verifyJwtTokenDocsMessage; } if (errorMessage) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } } verifySignature(jwtToken, isEmulator) { const verifier = isEmulator ? EMULATOR_VERIFIER : this.signatureVerifier; return verifier.verify(jwtToken) .catch((error) => { throw this.mapJwtErrorToAuthError(error); }); } /** * Maps JwtError to FirebaseAuthError * * @param error - JwtError to be mapped. * @returns FirebaseAuthError or Error instance. */ mapJwtErrorToAuthError(error) { const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; if (error.code === jwt_1.JwtErrorCode.TOKEN_EXPIRED) { const errorMessage = `${this.tokenInfo.jwtName} has expired. Get a fresh ${this.tokenInfo.shortName}` + ` from your client app and try again (auth/${this.tokenInfo.expiredErrorCode.code}).` + verifyJwtTokenDocsMessage; return new error_1.FirebaseAuthError(this.tokenInfo.expiredErrorCode, errorMessage); } else if (error.code === jwt_1.JwtErrorCode.INVALID_SIGNATURE) { const errorMessage = `${this.tokenInfo.jwtName} has invalid signature.` + verifyJwtTokenDocsMessage; return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } else if (error.code === jwt_1.JwtErrorCode.NO_MATCHING_KID) { const errorMessage = `${this.tokenInfo.jwtName} has "kid" claim which does not ` + `correspond to a known public key. Most likely the ${this.tokenInfo.shortName} ` + 'is expired, so get a fresh token from your client app and try again.'; return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, error.message); } } exports.FirebaseTokenVerifier = FirebaseTokenVerifier; /** * Creates a new FirebaseTokenVerifier to verify Firebase ID tokens. * * @internal * @param app - Firebase app instance. * @returns FirebaseTokenVerifier */ function createIdTokenVerifier(app) { return new FirebaseTokenVerifier(CLIENT_CERT_URL, 'https://securetoken.google.com/', exports.ID_TOKEN_INFO, app); } exports.createIdTokenVerifier = createIdTokenVerifier; /** * Creates a new FirebaseTokenVerifier to verify Firebase Auth Blocking tokens. * * @internal * @param app - Firebase app instance. * @returns FirebaseTokenVerifier */ function createAuthBlockingTokenVerifier(app) { return new FirebaseTokenVerifier(CLIENT_CERT_URL, 'https://securetoken.google.com/', exports.AUTH_BLOCKING_TOKEN_INFO, app); } exports.createAuthBlockingTokenVerifier = createAuthBlockingTokenVerifier; /** * Creates a new FirebaseTokenVerifier to verify Firebase session cookies. * * @internal * @param app - Firebase app instance. * @returns FirebaseTokenVerifier */ function createSessionCookieVerifier(app) { return new FirebaseTokenVerifier(SESSION_COOKIE_CERT_URL, 'https://session.firebase.google.com/', exports.SESSION_COOKIE_INFO, app); } exports.createSessionCookieVerifier = createSessionCookieVerifier;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.UserRecord = exports.UserMetadata = exports.UserInfo = exports.PhoneMultiFactorInfo = exports.MultiFactorSettings = exports.MultiFactorInfo = exports.TenantManager = exports.TenantAwareAuth = exports.Tenant = exports.BaseAuth = exports.Auth = exports.getAuth = void 0; /** * Firebase Authentication. * * @packageDocumentation */ const index_1 = require("../app/index"); const auth_1 = require("./auth"); /** * Gets the {@link Auth} service for the default app or a * given app. * * `getAuth()` can be called with no arguments to access the default app's * {@link Auth} service or as `getAuth(app)` to access the * {@link Auth} service associated with a specific app. * * @example * ```javascript * // Get the Auth service for the default app * const defaultAuth = getAuth(); * ``` * * @example * ```javascript * // Get the Auth service for a given app * const otherAuth = getAuth(otherApp); * ``` * */ function getAuth(app) { if (typeof app === 'undefined') { app = (0, index_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('auth', (app) => new auth_1.Auth(app)); } exports.getAuth = getAuth; var auth_2 = require("./auth"); Object.defineProperty(exports, "Auth", { enumerable: true, get: function () { return auth_2.Auth; } }); var base_auth_1 = require("./base-auth"); Object.defineProperty(exports, "BaseAuth", { enumerable: true, get: function () { return base_auth_1.BaseAuth; } }); var tenant_1 = require("./tenant"); Object.defineProperty(exports, "Tenant", { enumerable: true, get: function () { return tenant_1.Tenant; } }); var tenant_manager_1 = require("./tenant-manager"); Object.defineProperty(exports, "TenantAwareAuth", { enumerable: true, get: function () { return tenant_manager_1.TenantAwareAuth; } }); Object.defineProperty(exports, "TenantManager", { enumerable: true, get: function () { return tenant_manager_1.TenantManager; } }); var user_record_1 = require("./user-record"); Object.defineProperty(exports, "MultiFactorInfo", { enumerable: true, get: function () { return user_record_1.MultiFactorInfo; } }); Object.defineProperty(exports, "MultiFactorSettings", { enumerable: true, get: function () { return user_record_1.MultiFactorSettings; } }); Object.defineProperty(exports, "PhoneMultiFactorInfo", { enumerable: true, get: function () { return user_record_1.PhoneMultiFactorInfo; } }); Object.defineProperty(exports, "UserInfo", { enumerable: true, get: function () { return user_record_1.UserInfo; } }); Object.defineProperty(exports, "UserMetadata", { enumerable: true, get: function () { return user_record_1.UserMetadata; } }); Object.defineProperty(exports, "UserRecord", { enumerable: true, get: function () { return user_record_1.UserRecord; } });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Auth = void 0; const auth_api_request_1 = require("./auth-api-request"); const tenant_manager_1 = require("./tenant-manager"); const base_auth_1 = require("./base-auth"); /** * Auth service bound to the provided app. * An Auth instance can have multiple tenants. */ class Auth extends base_auth_1.BaseAuth { /** * @param app - The app for this Auth service. * @constructor * @internal */ constructor(app) { super(app, new auth_api_request_1.AuthRequestHandler(app)); this.app_ = app; this.tenantManager_ = new tenant_manager_1.TenantManager(app); } /** * Returns the app associated with this Auth instance. * * @returns The app associated with this Auth instance. */ get app() { return this.app_; } /** * Returns the tenant manager instance associated with the current project. * * @returns The tenant manager instance associated with the current project. */ tenantManager() { return this.tenantManager_; } } exports.Auth = Auth;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth-config.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth-config.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.OIDCConfig = exports.SAMLConfig = exports.EmailSignInConfig = exports.validateTestPhoneNumbers = exports.MultiFactorAuthConfig = exports.MAXIMUM_TEST_PHONE_NUMBERS = void 0; const validator = require("../utils/validator"); const deep_copy_1 = require("../utils/deep-copy"); const error_1 = require("../utils/error"); /** A maximum of 10 test phone number / code pairs can be configured. */ exports.MAXIMUM_TEST_PHONE_NUMBERS = 10; /** Client Auth factor type to server auth factor type mapping. */ const AUTH_FACTOR_CLIENT_TO_SERVER_TYPE = { phone: 'PHONE_SMS', }; /** Server Auth factor type to client auth factor type mapping. */ const AUTH_FACTOR_SERVER_TO_CLIENT_TYPE = Object.keys(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE) .reduce((res, key) => { res[AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[key]] = key; return res; }, {}); /** * Defines the multi-factor config class used to convert client side MultiFactorConfig * to a format that is understood by the Auth server. */ class MultiFactorAuthConfig { /** * The MultiFactorAuthConfig constructor. * * @param response - The server side response used to initialize the * MultiFactorAuthConfig object. * @constructor * @internal */ constructor(response) { if (typeof response.state === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response'); } this.state = response.state; this.factorIds = []; (response.enabledProviders || []).forEach((enabledProvider) => { // Ignore unsupported types. It is possible the current admin SDK version is // not up to date and newer backend types are supported. if (typeof AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider] !== 'undefined') { this.factorIds.push(AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider]); } }); } /** * Static method to convert a client side request to a MultiFactorAuthServerConfig. * Throws an error if validation fails. * * @param options - The options object to convert to a server request. * @returns The resulting server request. * @internal */ static buildServerRequest(options) { const request = {}; MultiFactorAuthConfig.validate(options); if (Object.prototype.hasOwnProperty.call(options, 'state')) { request.state = options.state; } if (Object.prototype.hasOwnProperty.call(options, 'factorIds')) { (options.factorIds || []).forEach((factorId) => { if (typeof request.enabledProviders === 'undefined') { request.enabledProviders = []; } request.enabledProviders.push(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId]); }); // In case an empty array is passed. Ensure it gets populated so the array is cleared. if (options.factorIds && options.factorIds.length === 0) { request.enabledProviders = []; } } return request; } /** * Validates the MultiFactorConfig options object. Throws an error on failure. * * @param options - The options object to validate. */ static validate(options) { const validKeys = { state: true, factorIds: true, }; if (!validator.isNonNullObject(options)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig" must be a non-null object.'); } // Check for unsupported top level attributes. for (const key in options) { if (!(key in validKeys)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid MultiFactorConfig parameter.`); } } // Validate content. if (typeof options.state !== 'undefined' && options.state !== 'ENABLED' && options.state !== 'DISABLED') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.state" must be either "ENABLED" or "DISABLED".'); } if (typeof options.factorIds !== 'undefined') { if (!validator.isArray(options.factorIds)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"MultiFactorConfig.factorIds" must be an array of valid "AuthFactorTypes".'); } // Validate content of array. options.factorIds.forEach((factorId) => { if (typeof AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId] === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${factorId}" is not a valid "AuthFactorType".`); } }); } } /** @returns The plain object representation of the multi-factor config instance. */ toJSON() { return { state: this.state, factorIds: this.factorIds, }; } } exports.MultiFactorAuthConfig = MultiFactorAuthConfig; /** * Validates the provided map of test phone number / code pairs. * @param testPhoneNumbers - The phone number / code pairs to validate. */ function validateTestPhoneNumbers(testPhoneNumbers) { if (!validator.isObject(testPhoneNumbers)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"testPhoneNumbers" must be a map of phone number / code pairs.'); } if (Object.keys(testPhoneNumbers).length > exports.MAXIMUM_TEST_PHONE_NUMBERS) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED); } for (const phoneNumber in testPhoneNumbers) { // Validate phone number. if (!validator.isPhoneNumber(phoneNumber)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER, `"${phoneNumber}" is not a valid E.164 standard compliant phone number.`); } // Validate code. if (!validator.isString(testPhoneNumbers[phoneNumber]) || !/^[\d]{6}$/.test(testPhoneNumbers[phoneNumber])) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER, `"${testPhoneNumbers[phoneNumber]}" is not a valid 6 digit code string.`); } } } exports.validateTestPhoneNumbers = validateTestPhoneNumbers; /** * Defines the email sign-in config class used to convert client side EmailSignInConfig * to a format that is understood by the Auth server. * * @internal */ class EmailSignInConfig { /** * The EmailSignInConfig constructor. * * @param response - The server side response used to initialize the * EmailSignInConfig object. * @constructor */ constructor(response) { if (typeof response.allowPasswordSignup === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid email sign-in configuration response'); } this.enabled = response.allowPasswordSignup; this.passwordRequired = !response.enableEmailLinkSignin; } /** * Static method to convert a client side request to a EmailSignInConfigServerRequest. * Throws an error if validation fails. * * @param options - The options object to convert to a server request. * @returns The resulting server request. * @internal */ static buildServerRequest(options) { const request = {}; EmailSignInConfig.validate(options); if (Object.prototype.hasOwnProperty.call(options, 'enabled')) { request.allowPasswordSignup = options.enabled; } if (Object.prototype.hasOwnProperty.call(options, 'passwordRequired')) { request.enableEmailLinkSignin = !options.passwordRequired; } return request; } /** * Validates the EmailSignInConfig options object. Throws an error on failure. * * @param options - The options object to validate. */ static validate(options) { // TODO: Validate the request. const validKeys = { enabled: true, passwordRequired: true, }; if (!validator.isNonNullObject(options)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig" must be a non-null object.'); } // Check for unsupported top level attributes. for (const key in options) { if (!(key in validKeys)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${key}" is not a valid EmailSignInConfig parameter.`); } } // Validate content. if (typeof options.enabled !== 'undefined' && !validator.isBoolean(options.enabled)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.enabled" must be a boolean.'); } if (typeof options.passwordRequired !== 'undefined' && !validator.isBoolean(options.passwordRequired)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.passwordRequired" must be a boolean.'); } } /** @returns The plain object representation of the email sign-in config. */ toJSON() { return { enabled: this.enabled, passwordRequired: this.passwordRequired, }; } } exports.EmailSignInConfig = EmailSignInConfig; /** * Defines the SAMLConfig class used to convert a client side configuration to its * server side representation. * * @internal */ class SAMLConfig { /** * The SAMLConfig constructor. * * @param response - The server side response used to initialize the SAMLConfig object. * @constructor */ constructor(response) { if (!response || !response.idpConfig || !response.idpConfig.idpEntityId || !response.idpConfig.ssoUrl || !response.spConfig || !response.spConfig.spEntityId || !response.name || !(validator.isString(response.name) && SAMLConfig.getProviderIdFromResourceName(response.name))) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response'); } const providerId = SAMLConfig.getProviderIdFromResourceName(response.name); if (!providerId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response'); } this.providerId = providerId; // RP config. this.rpEntityId = response.spConfig.spEntityId; this.callbackURL = response.spConfig.callbackUri; // IdP config. this.idpEntityId = response.idpConfig.idpEntityId; this.ssoURL = response.idpConfig.ssoUrl; this.enableRequestSigning = !!response.idpConfig.signRequest; const x509Certificates = []; for (const cert of (response.idpConfig.idpCertificates || [])) { if (cert.x509Certificate) { x509Certificates.push(cert.x509Certificate); } } this.x509Certificates = x509Certificates; // When enabled is undefined, it takes its default value of false. this.enabled = !!response.enabled; this.displayName = response.displayName; } /** * Converts a client side request to a SAMLConfigServerRequest which is the format * accepted by the backend server. * Throws an error if validation fails. If the request is not a SAMLConfig request, * returns null. * * @param options - The options object to convert to a server request. * @param ignoreMissingFields - Whether to ignore missing fields. * @returns The resulting server request or null if not valid. */ static buildServerRequest(options, ignoreMissingFields = false) { const makeRequest = validator.isNonNullObject(options) && (options.providerId || ignoreMissingFields); if (!makeRequest) { return null; } const request = {}; // Validate options. SAMLConfig.validate(options, ignoreMissingFields); request.enabled = options.enabled; request.displayName = options.displayName; // IdP config. if (options.idpEntityId || options.ssoURL || options.x509Certificates) { request.idpConfig = { idpEntityId: options.idpEntityId, ssoUrl: options.ssoURL, signRequest: options.enableRequestSigning, idpCertificates: typeof options.x509Certificates === 'undefined' ? undefined : [], }; if (options.x509Certificates) { for (const cert of (options.x509Certificates || [])) { request.idpConfig.idpCertificates.push({ x509Certificate: cert }); } } } // RP config. if (options.callbackURL || options.rpEntityId) { request.spConfig = { spEntityId: options.rpEntityId, callbackUri: options.callbackURL, }; } return request; } /** * Returns the provider ID corresponding to the resource name if available. * * @param resourceName - The server side resource name. * @returns The provider ID corresponding to the resource, null otherwise. */ static getProviderIdFromResourceName(resourceName) { // name is of form projects/project1/inboundSamlConfigs/providerId1 const matchProviderRes = resourceName.match(/\/inboundSamlConfigs\/(saml\..*)$/); if (!matchProviderRes || matchProviderRes.length < 2) { return null; } return matchProviderRes[1]; } /** * @param providerId - The provider ID to check. * @returns Whether the provider ID corresponds to a SAML provider. */ static isProviderId(providerId) { return validator.isNonEmptyString(providerId) && providerId.indexOf('saml.') === 0; } /** * Validates the SAMLConfig options object. Throws an error on failure. * * @param options - The options object to validate. * @param ignoreMissingFields - Whether to ignore missing fields. */ static validate(options, ignoreMissingFields = false) { const validKeys = { enabled: true, displayName: true, providerId: true, idpEntityId: true, ssoURL: true, x509Certificates: true, rpEntityId: true, callbackURL: true, enableRequestSigning: true, }; if (!validator.isNonNullObject(options)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig" must be a valid non-null object.'); } // Check for unsupported top level attributes. for (const key in options) { if (!(key in validKeys)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid SAML config parameter.`); } } // Required fields. if (validator.isNonEmptyString(options.providerId)) { if (options.providerId.indexOf('saml.') !== 0) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".'); } } else if (!ignoreMissingFields) { // providerId is required and not provided correctly. throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".'); } if (!(ignoreMissingFields && typeof options.idpEntityId === 'undefined') && !validator.isNonEmptyString(options.idpEntityId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.idpEntityId" must be a valid non-empty string.'); } if (!(ignoreMissingFields && typeof options.ssoURL === 'undefined') && !validator.isURL(options.ssoURL)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.ssoURL" must be a valid URL string.'); } if (!(ignoreMissingFields && typeof options.rpEntityId === 'undefined') && !validator.isNonEmptyString(options.rpEntityId)) { throw new error_1.FirebaseAuthError(!options.rpEntityId ? error_1.AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG : error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.rpEntityId" must be a valid non-empty string.'); } if (!(ignoreMissingFields && typeof options.callbackURL === 'undefined') && !validator.isURL(options.callbackURL)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.callbackURL" must be a valid URL string.'); } if (!(ignoreMissingFields && typeof options.x509Certificates === 'undefined') && !validator.isArray(options.x509Certificates)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.'); } (options.x509Certificates || []).forEach((cert) => { if (!validator.isNonEmptyString(cert)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.'); } }); if (typeof options.enableRequestSigning !== 'undefined' && !validator.isBoolean(options.enableRequestSigning)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enableRequestSigning" must be a boolean.'); } if (typeof options.enabled !== 'undefined' && !validator.isBoolean(options.enabled)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enabled" must be a boolean.'); } if (typeof options.displayName !== 'undefined' && !validator.isString(options.displayName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.displayName" must be a valid string.'); } } /** @returns The plain object representation of the SAMLConfig. */ toJSON() { return { enabled: this.enabled, displayName: this.displayName, providerId: this.providerId, idpEntityId: this.idpEntityId, ssoURL: this.ssoURL, x509Certificates: (0, deep_copy_1.deepCopy)(this.x509Certificates), rpEntityId: this.rpEntityId, callbackURL: this.callbackURL, enableRequestSigning: this.enableRequestSigning, }; } } exports.SAMLConfig = SAMLConfig; /** * Defines the OIDCConfig class used to convert a client side configuration to its * server side representation. * * @internal */ class OIDCConfig { /** * The OIDCConfig constructor. * * @param response - The server side response used to initialize the OIDCConfig object. * @constructor */ constructor(response) { if (!response || !response.issuer || !response.clientId || !response.name || !(validator.isString(response.name) && OIDCConfig.getProviderIdFromResourceName(response.name))) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid OIDC configuration response'); } const providerId = OIDCConfig.getProviderIdFromResourceName(response.name); if (!providerId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response'); } this.providerId = providerId; this.clientId = response.clientId; this.issuer = response.issuer; // When enabled is undefined, it takes its default value of false. this.enabled = !!response.enabled; this.displayName = response.displayName; if (typeof response.clientSecret !== 'undefined') { this.clientSecret = response.clientSecret; } if (typeof response.responseType !== 'undefined') { this.responseType = response.responseType; } } /** * Converts a client side request to a OIDCConfigServerRequest which is the format * accepted by the backend server. * Throws an error if validation fails. If the request is not a OIDCConfig request, * returns null. * * @param options - The options object to convert to a server request. * @param ignoreMissingFields - Whether to ignore missing fields. * @returns The resulting server request or null if not valid. */ static buildServerRequest(options, ignoreMissingFields = false) { const makeRequest = validator.isNonNullObject(options) && (options.providerId || ignoreMissingFields); if (!makeRequest) { return null; } const request = {}; // Validate options. OIDCConfig.validate(options, ignoreMissingFields); request.enabled = options.enabled; request.displayName = options.displayName; request.issuer = options.issuer; request.clientId = options.clientId; if (typeof options.clientSecret !== 'undefined') { request.clientSecret = options.clientSecret; } if (typeof options.responseType !== 'undefined') { request.responseType = options.responseType; } return request; } /** * Returns the provider ID corresponding to the resource name if available. * * @param resourceName - The server side resource name * @returns The provider ID corresponding to the resource, null otherwise. */ static getProviderIdFromResourceName(resourceName) { // name is of form projects/project1/oauthIdpConfigs/providerId1 const matchProviderRes = resourceName.match(/\/oauthIdpConfigs\/(oidc\..*)$/); if (!matchProviderRes || matchProviderRes.length < 2) { return null; } return matchProviderRes[1]; } /** * @param providerId - The provider ID to check. * @returns Whether the provider ID corresponds to an OIDC provider. */ static isProviderId(providerId) { return validator.isNonEmptyString(providerId) && providerId.indexOf('oidc.') === 0; } /** * Validates the OIDCConfig options object. Throws an error on failure. * * @param options - The options object to validate. * @param ignoreMissingFields - Whether to ignore missing fields. */ static validate(options, ignoreMissingFields = false) { const validKeys = { enabled: true, displayName: true, providerId: true, clientId: true, issuer: true, clientSecret: true, responseType: true, }; const validResponseTypes = { idToken: true, code: true, }; if (!validator.isNonNullObject(options)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig" must be a valid non-null object.'); } // Check for unsupported top level attributes. for (const key in options) { if (!(key in validKeys)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid OIDC config parameter.`); } } // Required fields. if (validator.isNonEmptyString(options.providerId)) { if (options.providerId.indexOf('oidc.') !== 0) { throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".'); } } else if (!ignoreMissingFields) { throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".'); } if (!(ignoreMissingFields && typeof options.clientId === 'undefined') && !validator.isNonEmptyString(options.clientId)) { throw new error_1.FirebaseAuthError(!options.clientId ? error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID : error_1.AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID, '"OIDCAuthProviderConfig.clientId" must be a valid non-empty string.'); } if (!(ignoreMissingFields && typeof options.issuer === 'undefined') && !validator.isURL(options.issuer)) { throw new error_1.FirebaseAuthError(!options.issuer ? error_1.AuthClientErrorCode.MISSING_ISSUER : error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.issuer" must be a valid URL string.'); } if (typeof options.enabled !== 'undefined' && !validator.isBoolean(options.enabled)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.enabled" must be a boolean.'); } if (typeof options.displayName !== 'undefined' && !validator.isString(options.displayName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.displayName" must be a valid string.'); } if (typeof options.clientSecret !== 'undefined' && !validator.isNonEmptyString(options.clientSecret)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.clientSecret" must be a valid string.'); } if (validator.isNonNullObject(options.responseType) && typeof options.responseType !== 'undefined') { Object.keys(options.responseType).forEach((key) => { if (!(key in validResponseTypes)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, `"${key}" is not a valid OAuthResponseType parameter.`); } }); const idToken = options.responseType.idToken; if (typeof idToken !== 'undefined' && !validator.isBoolean(idToken)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"OIDCAuthProviderConfig.responseType.idToken" must be a boolean.'); } const code = options.responseType.code; if (typeof code !== 'undefined') { if (!validator.isBoolean(code)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"OIDCAuthProviderConfig.responseType.code" must be a boolean.'); } // If code flow is enabled, client secret must be provided. if (code && typeof options.clientSecret === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_SECRET, 'The OAuth configuration client secret is required to enable OIDC code flow.'); } } const allKeys = Object.keys(options.responseType).length; const enabledCount = Object.values(options.responseType).filter(Boolean).length; // Only one of OAuth response types can be set to true. if (allKeys > 1 && enabledCount != 1) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_OAUTH_RESPONSETYPE, 'Only exactly one OAuth responseType should be set to true.'); } } } /** @returns The plain object representation of the OIDCConfig. */ toJSON() { return { enabled: this.enabled, displayName: this.displayName, providerId: this.providerId, issuer: this.issuer, clientId: this.clientId, clientSecret: (0, deep_copy_1.deepCopy)(this.clientSecret), responseType: (0, deep_copy_1.deepCopy)(this.responseType), }; } } exports.OIDCConfig = OIDCConfig;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/action-code-settings-builder.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/action-code-settings-builder.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ActionCodeSettingsBuilder = void 0; const validator = require("../utils/validator"); const error_1 = require("../utils/error"); /** * Defines the ActionCodeSettings builder class used to convert the * ActionCodeSettings object to its corresponding server request. * * @internal */ class ActionCodeSettingsBuilder { /** * ActionCodeSettingsBuilder constructor. * * @param {ActionCodeSettings} actionCodeSettings The ActionCodeSettings * object used to initiliaze this server request builder. * @constructor */ constructor(actionCodeSettings) { if (!validator.isNonNullObject(actionCodeSettings)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings" must be a non-null object.'); } if (typeof actionCodeSettings.url === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_CONTINUE_URI); } else if (!validator.isURL(actionCodeSettings.url)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONTINUE_URI); } this.continueUrl = actionCodeSettings.url; if (typeof actionCodeSettings.handleCodeInApp !== 'undefined' && !validator.isBoolean(actionCodeSettings.handleCodeInApp)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.handleCodeInApp" must be a boolean.'); } this.canHandleCodeInApp = actionCodeSettings.handleCodeInApp || false; if (typeof actionCodeSettings.dynamicLinkDomain !== 'undefined' && !validator.isNonEmptyString(actionCodeSettings.dynamicLinkDomain)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DYNAMIC_LINK_DOMAIN); } this.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain; if (typeof actionCodeSettings.iOS !== 'undefined') { if (!validator.isNonNullObject(actionCodeSettings.iOS)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.iOS" must be a valid non-null object.'); } else if (typeof actionCodeSettings.iOS.bundleId === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_IOS_BUNDLE_ID); } else if (!validator.isNonEmptyString(actionCodeSettings.iOS.bundleId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.iOS.bundleId" must be a valid non-empty string.'); } this.ibi = actionCodeSettings.iOS.bundleId; } if (typeof actionCodeSettings.android !== 'undefined') { if (!validator.isNonNullObject(actionCodeSettings.android)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android" must be a valid non-null object.'); } else if (typeof actionCodeSettings.android.packageName === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_ANDROID_PACKAGE_NAME); } else if (!validator.isNonEmptyString(actionCodeSettings.android.packageName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.packageName" must be a valid non-empty string.'); } else if (typeof actionCodeSettings.android.minimumVersion !== 'undefined' && !validator.isNonEmptyString(actionCodeSettings.android.minimumVersion)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.minimumVersion" must be a valid non-empty string.'); } else if (typeof actionCodeSettings.android.installApp !== 'undefined' && !validator.isBoolean(actionCodeSettings.android.installApp)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.installApp" must be a valid boolean.'); } this.apn = actionCodeSettings.android.packageName; this.amv = actionCodeSettings.android.minimumVersion; this.installApp = actionCodeSettings.android.installApp || false; } } /** * Returns the corresponding constructed server request corresponding to the * current ActionCodeSettings. * * @returns The constructed EmailActionCodeRequest request. */ buildRequest() { const request = { continueUrl: this.continueUrl, canHandleCodeInApp: this.canHandleCodeInApp, dynamicLinkDomain: this.dynamicLinkDomain, androidPackageName: this.apn, androidMinimumVersion: this.amv, androidInstallApp: this.installApp, iOSBundleId: this.ibi, }; // Remove all null and undefined fields from request. for (const key in request) { if (Object.prototype.hasOwnProperty.call(request, key)) { if (typeof request[key] === 'undefined' || request[key] === null) { delete request[key]; } } } return request; } } exports.ActionCodeSettingsBuilder = ActionCodeSettingsBuilder;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/base-auth.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/base-auth.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseAuth = exports.createFirebaseTokenGenerator = void 0; const error_1 = require("../utils/error"); const deep_copy_1 = require("../utils/deep-copy"); const validator = require("../utils/validator"); const auth_api_request_1 = require("./auth-api-request"); const token_generator_1 = require("./token-generator"); const token_verifier_1 = require("./token-verifier"); const auth_config_1 = require("./auth-config"); const user_record_1 = require("./user-record"); const identifier_1 = require("./identifier"); const crypto_signer_1 = require("../utils/crypto-signer"); /** * @internal */ function createFirebaseTokenGenerator(app, tenantId) { try { const signer = (0, auth_api_request_1.useEmulator)() ? new token_generator_1.EmulatedSigner() : (0, crypto_signer_1.cryptoSignerFromApp)(app); return new token_generator_1.FirebaseTokenGenerator(signer, tenantId); } catch (err) { throw (0, token_generator_1.handleCryptoSignerError)(err); } } exports.createFirebaseTokenGenerator = createFirebaseTokenGenerator; /** * Common parent interface for both `Auth` and `TenantAwareAuth` APIs. */ class BaseAuth { /** * The BaseAuth class constructor. * * @param app - The FirebaseApp to associate with this Auth instance. * @param authRequestHandler - The RPC request handler for this instance. * @param tokenGenerator - Optional token generator. If not specified, a * (non-tenant-aware) instance will be created. Use this paramter to * specify a tenant-aware tokenGenerator. * @constructor * @internal */ constructor(app, /** @internal */ authRequestHandler, tokenGenerator) { this.authRequestHandler = authRequestHandler; if (tokenGenerator) { this.tokenGenerator = tokenGenerator; } else { this.tokenGenerator = createFirebaseTokenGenerator(app); } this.sessionCookieVerifier = (0, token_verifier_1.createSessionCookieVerifier)(app); this.idTokenVerifier = (0, token_verifier_1.createIdTokenVerifier)(app); this.authBlockingTokenVerifier = (0, token_verifier_1.createAuthBlockingTokenVerifier)(app); } /** * Creates a new Firebase custom token (JWT) that can be sent back to a client * device to use to sign in with the client SDKs' `signInWithCustomToken()` * methods. (Tenant-aware instances will also embed the tenant ID in the * token.) * * See {@link https://firebase.google.com/docs/auth/admin/create-custom-tokens | Create Custom Tokens} * for code samples and detailed documentation. * * @param uid - The `uid` to use as the custom token's subject. * @param developerClaims - Optional additional claims to include * in the custom token's payload. * * @returns A promise fulfilled with a custom token for the * provided `uid` and payload. */ createCustomToken(uid, developerClaims) { return this.tokenGenerator.createCustomToken(uid, developerClaims); } /** * Verifies a Firebase ID token (JWT). If the token is valid, the promise is * fulfilled with the token's decoded claims; otherwise, the promise is * rejected. * * If `checkRevoked` is set to true, first verifies whether the corresponding * user is disabled. If yes, an `auth/user-disabled` error is thrown. If no, * verifies if the session corresponding to the ID token was revoked. If the * corresponding user's session was invalidated, an `auth/id-token-revoked` * error is thrown. If not specified the check is not applied. * * See {@link https://firebase.google.com/docs/auth/admin/verify-id-tokens | Verify ID Tokens} * for code samples and detailed documentation. * * @param idToken - The ID token to verify. * @param checkRevoked - Whether to check if the ID token was revoked. * This requires an extra request to the Firebase Auth backend to check * the `tokensValidAfterTime` time for the corresponding user. * When not specified, this additional check is not applied. * * @returns A promise fulfilled with the * token's decoded claims if the ID token is valid; otherwise, a rejected * promise. */ verifyIdToken(idToken, checkRevoked = false) { const isEmulator = (0, auth_api_request_1.useEmulator)(); return this.idTokenVerifier.verifyJWT(idToken, isEmulator) .then((decodedIdToken) => { // Whether to check if the token was revoked. if (checkRevoked || isEmulator) { return this.verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, error_1.AuthClientErrorCode.ID_TOKEN_REVOKED); } return decodedIdToken; }); } /** * Gets the user data for the user corresponding to a given `uid`. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param uid - The `uid` corresponding to the user whose data to fetch. * * @returns A promise fulfilled with the user * data corresponding to the provided `uid`. */ getUser(uid) { return this.authRequestHandler.getAccountInfoByUid(uid) .then((response) => { // Returns the user record populated with server response. return new user_record_1.UserRecord(response.users[0]); }); } /** * Gets the user data for the user corresponding to a given email. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param email - The email corresponding to the user whose data to * fetch. * * @returns A promise fulfilled with the user * data corresponding to the provided email. */ getUserByEmail(email) { return this.authRequestHandler.getAccountInfoByEmail(email) .then((response) => { // Returns the user record populated with server response. return new user_record_1.UserRecord(response.users[0]); }); } /** * Gets the user data for the user corresponding to a given phone number. The * phone number has to conform to the E.164 specification. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param phoneNumber - The phone number corresponding to the user whose * data to fetch. * * @returns A promise fulfilled with the user * data corresponding to the provided phone number. */ getUserByPhoneNumber(phoneNumber) { return this.authRequestHandler.getAccountInfoByPhoneNumber(phoneNumber) .then((response) => { // Returns the user record populated with server response. return new user_record_1.UserRecord(response.users[0]); }); } /** * Gets the user data for the user corresponding to a given provider id. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param providerId - The provider ID, for example, "google.com" for the * Google provider. * @param uid - The user identifier for the given provider. * * @returns A promise fulfilled with the user data corresponding to the * given provider id. */ getUserByProviderUid(providerId, uid) { // Although we don't really advertise it, we want to also handle // non-federated idps with this call. So if we detect one of them, we'll // reroute this request appropriately. if (providerId === 'phone') { return this.getUserByPhoneNumber(uid); } else if (providerId === 'email') { return this.getUserByEmail(uid); } return this.authRequestHandler.getAccountInfoByFederatedUid(providerId, uid) .then((response) => { // Returns the user record populated with server response. return new user_record_1.UserRecord(response.users[0]); }); } /** * Gets the user data corresponding to the specified identifiers. * * There are no ordering guarantees; in particular, the nth entry in the result list is not * guaranteed to correspond to the nth entry in the input parameters list. * * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied, * this method throws a FirebaseAuthError. * * @param identifiers - The identifiers used to indicate which user records should be returned. * Must not have more than 100 entries. * @returns A promise that resolves to the corresponding user records. * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100 * identifiers are specified. */ getUsers(identifiers) { if (!validator.isArray(identifiers)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`identifiers` parameter must be an array'); } return this.authRequestHandler .getAccountInfoByIdentifiers(identifiers) .then((response) => { /** * Checks if the specified identifier is within the list of * UserRecords. */ const isUserFound = ((id, userRecords) => { return !!userRecords.find((userRecord) => { if ((0, identifier_1.isUidIdentifier)(id)) { return id.uid === userRecord.uid; } else if ((0, identifier_1.isEmailIdentifier)(id)) { return id.email === userRecord.email; } else if ((0, identifier_1.isPhoneIdentifier)(id)) { return id.phoneNumber === userRecord.phoneNumber; } else if ((0, identifier_1.isProviderIdentifier)(id)) { const matchingUserInfo = userRecord.providerData.find((userInfo) => { return id.providerId === userInfo.providerId; }); return !!matchingUserInfo && id.providerUid === matchingUserInfo.uid; } else { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unhandled identifier type'); } }); }); const users = response.users ? response.users.map((user) => new user_record_1.UserRecord(user)) : []; const notFound = identifiers.filter((id) => !isUserFound(id, users)); return { users, notFound }; }); } /** * Retrieves a list of users (single batch only) with a size of `maxResults` * starting from the offset as specified by `pageToken`. This is used to * retrieve all the users of a specified project in batches. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#list_all_users | List all users} * for code samples and detailed documentation. * * @param maxResults - The page size, 1000 if undefined. This is also * the maximum allowed limit. * @param pageToken - The next page token. If not specified, returns * users starting without any offset. * @returns A promise that resolves with * the current batch of downloaded users and the next page token. */ listUsers(maxResults, pageToken) { return this.authRequestHandler.downloadAccount(maxResults, pageToken) .then((response) => { // List of users to return. const users = []; // Convert each user response to a UserRecord. response.users.forEach((userResponse) => { users.push(new user_record_1.UserRecord(userResponse)); }); // Return list of user records and the next page token if available. const result = { users, pageToken: response.nextPageToken, }; // Delete result.pageToken if undefined. if (typeof result.pageToken === 'undefined') { delete result.pageToken; } return result; }); } /** * Creates a new user. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#create_a_user | Create a user} * for code samples and detailed documentation. * * @param properties - The properties to set on the * new user record to be created. * * @returns A promise fulfilled with the user * data corresponding to the newly created user. */ createUser(properties) { return this.authRequestHandler.createNewAccount(properties) .then((uid) => { // Return the corresponding user record. return this.getUser(uid); }) .catch((error) => { if (error.code === 'auth/user-not-found') { // Something must have happened after creating the user and then retrieving it. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.'); } throw error; }); } /** * Deletes an existing user. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#delete_a_user | Delete a user} * for code samples and detailed documentation. * * @param uid - The `uid` corresponding to the user to delete. * * @returns An empty promise fulfilled once the user has been * deleted. */ deleteUser(uid) { return this.authRequestHandler.deleteAccount(uid) .then(() => { // Return nothing on success. }); } /** * Deletes the users specified by the given uids. * * Deleting a non-existing user won't generate an error (i.e. this method * is idempotent.) Non-existing users are considered to be successfully * deleted, and are therefore counted in the * `DeleteUsersResult.successCount` value. * * Only a maximum of 1000 identifiers may be supplied. If more than 1000 * identifiers are supplied, this method throws a FirebaseAuthError. * * This API is currently rate limited at the server to 1 QPS. If you exceed * this, you may get a quota exceeded error. Therefore, if you want to * delete more than 1000 users, you may need to add a delay to ensure you * don't go over this limit. * * @param uids - The `uids` corresponding to the users to delete. * * @returns A Promise that resolves to the total number of successful/failed * deletions, as well as the array of errors that corresponds to the * failed deletions. */ deleteUsers(uids) { if (!validator.isArray(uids)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`uids` parameter must be an array'); } return this.authRequestHandler.deleteAccounts(uids, /*force=*/ true) .then((batchDeleteAccountsResponse) => { const result = { failureCount: 0, successCount: uids.length, errors: [], }; if (!validator.isNonEmptyArray(batchDeleteAccountsResponse.errors)) { return result; } result.failureCount = batchDeleteAccountsResponse.errors.length; result.successCount = uids.length - batchDeleteAccountsResponse.errors.length; result.errors = batchDeleteAccountsResponse.errors.map((batchDeleteErrorInfo) => { if (batchDeleteErrorInfo.index === undefined) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Corrupt BatchDeleteAccountsResponse detected'); } const errMsgToError = (msg) => { // We unconditionally set force=true, so the 'NOT_DISABLED' error // should not be possible. const code = msg && msg.startsWith('NOT_DISABLED') ? error_1.AuthClientErrorCode.USER_NOT_DISABLED : error_1.AuthClientErrorCode.INTERNAL_ERROR; return new error_1.FirebaseAuthError(code, batchDeleteErrorInfo.message); }; return { index: batchDeleteErrorInfo.index, error: errMsgToError(batchDeleteErrorInfo.message), }; }); return result; }); } /** * Updates an existing user. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#update_a_user | Update a user} * for code samples and detailed documentation. * * @param uid - The `uid` corresponding to the user to update. * @param properties - The properties to update on * the provided user. * * @returns A promise fulfilled with the * updated user data. */ updateUser(uid, properties) { // Although we don't really advertise it, we want to also handle linking of // non-federated idps with this call. So if we detect one of them, we'll // adjust the properties parameter appropriately. This *does* imply that a // conflict could arise, e.g. if the user provides a phoneNumber property, // but also provides a providerToLink with a 'phone' provider id. In that // case, we'll throw an error. properties = (0, deep_copy_1.deepCopy)(properties); if (properties?.providerToLink) { if (properties.providerToLink.providerId === 'email') { if (typeof properties.email !== 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.email and UpdateRequest.providerToLink.providerId='email' were set. To " + 'link to the email/password provider, only specify the UpdateRequest.email field.'); } properties.email = properties.providerToLink.uid; delete properties.providerToLink; } else if (properties.providerToLink.providerId === 'phone') { if (typeof properties.phoneNumber !== 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber and UpdateRequest.providerToLink.providerId='phone' were set. To " + 'link to a phone provider, only specify the UpdateRequest.phoneNumber field.'); } properties.phoneNumber = properties.providerToLink.uid; delete properties.providerToLink; } } if (properties?.providersToUnlink) { if (properties.providersToUnlink.indexOf('phone') !== -1) { // If we've been told to unlink the phone provider both via setting // phoneNumber to null *and* by setting providersToUnlink to include // 'phone', then we'll reject that. Though it might also be reasonable // to relax this restriction and just unlink it. if (properties.phoneNumber === null) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber=null and UpdateRequest.providersToUnlink=['phone'] were set. To " + 'unlink from a phone provider, only specify the UpdateRequest.phoneNumber=null field.'); } } } return this.authRequestHandler.updateExistingAccount(uid, properties) .then((existingUid) => { // Return the corresponding user record. return this.getUser(existingUid); }); } /** * Sets additional developer claims on an existing user identified by the * provided `uid`, typically used to define user roles and levels of * access. These claims should propagate to all devices where the user is * already signed in (after token expiration or when token refresh is forced) * and the next time the user signs in. If a reserved OIDC claim name * is used (sub, iat, iss, etc), an error is thrown. They are set on the * authenticated user's ID token JWT. * * See {@link https://firebase.google.com/docs/auth/admin/custom-claims | * Defining user roles and access levels} * for code samples and detailed documentation. * * @param uid - The `uid` of the user to edit. * @param customUserClaims - The developer claims to set. If null is * passed, existing custom claims are deleted. Passing a custom claims payload * larger than 1000 bytes will throw an error. Custom claims are added to the * user's ID token which is transmitted on every authenticated request. * For profile non-access related user attributes, use database or other * separate storage systems. * @returns A promise that resolves when the operation completes * successfully. */ setCustomUserClaims(uid, customUserClaims) { return this.authRequestHandler.setCustomUserClaims(uid, customUserClaims) .then(() => { // Return nothing on success. }); } /** * Revokes all refresh tokens for an existing user. * * This API will update the user's {@link UserRecord.tokensValidAfterTime} to * the current UTC. It is important that the server on which this is called has * its clock set correctly and synchronized. * * While this will revoke all sessions for a specified user and disable any * new ID tokens for existing sessions from getting minted, existing ID tokens * may remain active until their natural expiration (one hour). To verify that * ID tokens are revoked, use {@link BaseAuth.verifyIdToken} * where `checkRevoked` is set to true. * * @param uid - The `uid` corresponding to the user whose refresh tokens * are to be revoked. * * @returns An empty promise fulfilled once the user's refresh * tokens have been revoked. */ revokeRefreshTokens(uid) { return this.authRequestHandler.revokeRefreshTokens(uid) .then(() => { // Return nothing on success. }); } /** * Imports the provided list of users into Firebase Auth. * A maximum of 1000 users are allowed to be imported one at a time. * When importing users with passwords, * {@link UserImportOptions} are required to be * specified. * This operation is optimized for bulk imports and will ignore checks on `uid`, * `email` and other identifier uniqueness which could result in duplications. * * @param users - The list of user records to import to Firebase Auth. * @param options - The user import options, required when the users provided include * password credentials. * @returns A promise that resolves when * the operation completes with the result of the import. This includes the * number of successful imports, the number of failed imports and their * corresponding errors. */ importUsers(users, options) { return this.authRequestHandler.uploadAccount(users, options); } /** * Creates a new Firebase session cookie with the specified options. The created * JWT string can be set as a server-side session cookie with a custom cookie * policy, and be used for session management. The session cookie JWT will have * the same payload claims as the provided ID token. * * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies | Manage Session Cookies} * for code samples and detailed documentation. * * @param idToken - The Firebase ID token to exchange for a session * cookie. * @param sessionCookieOptions - The session * cookie options which includes custom session duration. * * @returns A promise that resolves on success with the * created session cookie. */ createSessionCookie(idToken, sessionCookieOptions) { // Return rejected promise if expiresIn is not available. if (!validator.isNonNullObject(sessionCookieOptions) || !validator.isNumber(sessionCookieOptions.expiresIn)) { return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION)); } return this.authRequestHandler.createSessionCookie(idToken, sessionCookieOptions.expiresIn); } /** * Verifies a Firebase session cookie. Returns a Promise with the cookie claims. * Rejects the promise if the cookie could not be verified. * * If `checkRevoked` is set to true, first verifies whether the corresponding * user is disabled: If yes, an `auth/user-disabled` error is thrown. If no, * verifies if the session corresponding to the session cookie was revoked. * If the corresponding user's session was invalidated, an * `auth/session-cookie-revoked` error is thrown. If not specified the check * is not performed. * * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions | * Verify Session Cookies} * for code samples and detailed documentation * * @param sessionCookie - The session cookie to verify. * @param checkForRevocation - Whether to check if the session cookie was * revoked. This requires an extra request to the Firebase Auth backend to * check the `tokensValidAfterTime` time for the corresponding user. * When not specified, this additional check is not performed. * * @returns A promise fulfilled with the * session cookie's decoded claims if the session cookie is valid; otherwise, * a rejected promise. */ verifySessionCookie(sessionCookie, checkRevoked = false) { const isEmulator = (0, auth_api_request_1.useEmulator)(); return this.sessionCookieVerifier.verifyJWT(sessionCookie, isEmulator) .then((decodedIdToken) => { // Whether to check if the token was revoked. if (checkRevoked || isEmulator) { return this.verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, error_1.AuthClientErrorCode.SESSION_COOKIE_REVOKED); } return decodedIdToken; }); } /** * Generates the out of band email action link to reset a user's password. * The link is generated for the user with the specified email address. The * optional {@link ActionCodeSettings} object * defines whether the link is to be handled by a mobile app or browser and the * additional state information to be passed in the deep link, etc. * * @example * ```javascript * var actionCodeSettings = { * url: 'https://www.example.com/?email=user@example.com', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true, * dynamicLinkDomain: 'custom.page.link' * }; * admin.auth() * .generatePasswordResetLink('user@example.com', actionCodeSettings) * .then(function(link) { * // The link was successfully generated. * }) * .catch(function(error) { * // Some error occurred, you can inspect the code: error.code * }); * ``` * * @param email - The email address of the user whose password is to be * reset. * @param actionCodeSettings - The action * code settings. If specified, the state/continue URL is set as the * "continueUrl" parameter in the password reset link. The default password * reset landing page will use this to display a link to go back to the app * if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error is thrown. * Mobile app redirects are only applicable if the developer configures * and accepts the Firebase Dynamic Links terms of service. * The Android package name and iOS bundle ID are respected only if they * are configured in the same Firebase Auth project. * @returns A promise that resolves with the generated link. */ generatePasswordResetLink(email, actionCodeSettings) { return this.authRequestHandler.getEmailActionLink('PASSWORD_RESET', email, actionCodeSettings); } /** * Generates the out of band email action link to verify the user's ownership * of the specified email. The {@link ActionCodeSettings} object provided * as an argument to this method defines whether the link is to be handled by a * mobile app or browser along with additional state information to be passed in * the deep link, etc. * * @example * ```javascript * var actionCodeSettings = { * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true, * dynamicLinkDomain: 'custom.page.link' * }; * admin.auth() * .generateEmailVerificationLink('user@example.com', actionCodeSettings) * .then(function(link) { * // The link was successfully generated. * }) * .catch(function(error) { * // Some error occurred, you can inspect the code: error.code * }); * ``` * * @param email - The email account to verify. * @param actionCodeSettings - The action * code settings. If specified, the state/continue URL is set as the * "continueUrl" parameter in the email verification link. The default email * verification landing page will use this to display a link to go back to * the app if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error is thrown. * Mobile app redirects are only applicable if the developer configures * and accepts the Firebase Dynamic Links terms of service. * The Android package name and iOS bundle ID are respected only if they * are configured in the same Firebase Auth project. * @returns A promise that resolves with the generated link. */ generateEmailVerificationLink(email, actionCodeSettings) { return this.authRequestHandler.getEmailActionLink('VERIFY_EMAIL', email, actionCodeSettings); } /** * Generates an out-of-band email action link to verify the user's ownership
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/token-generator.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/token-generator.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.handleCryptoSignerError = exports.FirebaseTokenGenerator = exports.EmulatedSigner = exports.BLACKLISTED_CLAIMS = void 0; const error_1 = require("../utils/error"); const crypto_signer_1 = require("../utils/crypto-signer"); const validator = require("../utils/validator"); const utils_1 = require("../utils"); const ALGORITHM_NONE = 'none'; const ONE_HOUR_IN_SECONDS = 60 * 60; // List of blacklisted claims which cannot be provided when creating a custom token exports.BLACKLISTED_CLAIMS = [ 'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti', 'nbf', 'nonce', ]; // Audience to use for Firebase Auth Custom tokens const FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit'; /** * A CryptoSigner implementation that is used when communicating with the Auth emulator. * It produces unsigned tokens. */ class EmulatedSigner { constructor() { this.algorithm = ALGORITHM_NONE; } /** * @inheritDoc */ // eslint-disable-next-line @typescript-eslint/no-unused-vars sign(buffer) { return Promise.resolve(Buffer.from('')); } /** * @inheritDoc */ getAccountId() { return Promise.resolve('firebase-auth-emulator@example.com'); } } exports.EmulatedSigner = EmulatedSigner; /** * Class for generating different types of Firebase Auth tokens (JWTs). * * @internal */ class FirebaseTokenGenerator { /** * @param tenantId - The tenant ID to use for the generated Firebase Auth * Custom token. If absent, then no tenant ID claim will be set in the * resulting JWT. */ constructor(signer, tenantId) { this.tenantId = tenantId; if (!validator.isNonNullObject(signer)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'INTERNAL ASSERT: Must provide a CryptoSigner to use FirebaseTokenGenerator.'); } if (typeof this.tenantId !== 'undefined' && !validator.isNonEmptyString(this.tenantId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`tenantId` argument must be a non-empty string.'); } this.signer = signer; } /** * Creates a new Firebase Auth Custom token. * * @param uid - The user ID to use for the generated Firebase Auth Custom token. * @param developerClaims - Optional developer claims to include in the generated Firebase * Auth Custom token. * @returns A Promise fulfilled with a Firebase Auth Custom token signed with a * service account key and containing the provided payload. */ createCustomToken(uid, developerClaims) { let errorMessage; if (!validator.isNonEmptyString(uid)) { errorMessage = '`uid` argument must be a non-empty string uid.'; } else if (uid.length > 128) { errorMessage = '`uid` argument must a uid with less than or equal to 128 characters.'; } else if (!this.isDeveloperClaimsValid_(developerClaims)) { errorMessage = '`developerClaims` argument must be a valid, non-null object containing the developer claims.'; } if (errorMessage) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } const claims = {}; if (typeof developerClaims !== 'undefined') { for (const key in developerClaims) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(developerClaims, key)) { if (exports.BLACKLISTED_CLAIMS.indexOf(key) !== -1) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `Developer claim "${key}" is reserved and cannot be specified.`); } claims[key] = developerClaims[key]; } } } return this.signer.getAccountId().then((account) => { const header = { alg: this.signer.algorithm, typ: 'JWT', }; const iat = Math.floor(Date.now() / 1000); const body = { aud: FIREBASE_AUDIENCE, iat, exp: iat + ONE_HOUR_IN_SECONDS, iss: account, sub: account, uid, }; if (this.tenantId) { body.tenant_id = this.tenantId; } if (Object.keys(claims).length > 0) { body.claims = claims; } const token = `${this.encodeSegment(header)}.${this.encodeSegment(body)}`; const signPromise = this.signer.sign(Buffer.from(token)); return Promise.all([token, signPromise]); }).then(([token, signature]) => { return `${token}.${this.encodeSegment(signature)}`; }).catch((err) => { throw handleCryptoSignerError(err); }); } encodeSegment(segment) { const buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment)); return (0, utils_1.toWebSafeBase64)(buffer).replace(/=+$/, ''); } /** * Returns whether or not the provided developer claims are valid. * * @param developerClaims - Optional developer claims to validate. * @returns True if the provided claims are valid; otherwise, false. */ // eslint-disable-next-line @typescript-eslint/naming-convention isDeveloperClaimsValid_(developerClaims) { if (typeof developerClaims === 'undefined') { return true; } return validator.isNonNullObject(developerClaims); } } exports.FirebaseTokenGenerator = FirebaseTokenGenerator; /** * Creates a new FirebaseAuthError by extracting the error code, message and other relevant * details from a CryptoSignerError. * * @param err - The Error to convert into a FirebaseAuthError error * @returns A Firebase Auth error that can be returned to the user. */ function handleCryptoSignerError(err) { if (!(err instanceof crypto_signer_1.CryptoSignerError)) { return err; } if (err.code === crypto_signer_1.CryptoSignerErrorCode.SERVER_ERROR && validator.isNonNullObject(err.cause)) { const httpError = err.cause; const errorResponse = httpError.response.data; if (validator.isNonNullObject(errorResponse) && errorResponse.error) { const errorCode = errorResponse.error.status; const description = 'Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens ' + 'for more details on how to use and troubleshoot this feature.'; const errorMsg = `${errorResponse.error.message}; ${description}`; return error_1.FirebaseAuthError.fromServerError(errorCode, errorMsg, errorResponse); } return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Error returned from server: ' + errorResponse + '. Additionally, an ' + 'internal error occurred while attempting to extract the ' + 'errorcode from the error.'); } return new error_1.FirebaseAuthError(mapToAuthClientErrorCode(err.code), err.message); } exports.handleCryptoSignerError = handleCryptoSignerError; function mapToAuthClientErrorCode(code) { switch (code) { case crypto_signer_1.CryptoSignerErrorCode.INVALID_CREDENTIAL: return error_1.AuthClientErrorCode.INVALID_CREDENTIAL; case crypto_signer_1.CryptoSignerErrorCode.INVALID_ARGUMENT: return error_1.AuthClientErrorCode.INVALID_ARGUMENT; default: return error_1.AuthClientErrorCode.INTERNAL_ERROR; } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/tenant-manager.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/tenant-manager.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TenantManager = exports.TenantAwareAuth = void 0; const validator = require("../utils/validator"); const utils = require("../utils/index"); const error_1 = require("../utils/error"); const base_auth_1 = require("./base-auth"); const tenant_1 = require("./tenant"); const auth_api_request_1 = require("./auth-api-request"); /** * Tenant-aware `Auth` interface used for managing users, configuring SAML/OIDC providers, * generating email links for password reset, email verification, etc for specific tenants. * * Multi-tenancy support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * Each tenant contains its own identity providers, settings and sets of users. * Using `TenantAwareAuth`, users for a specific tenant and corresponding OIDC/SAML * configurations can also be managed, ID tokens for users signed in to a specific tenant * can be verified, and email action links can also be generated for users belonging to the * tenant. * * `TenantAwareAuth` instances for a specific `tenantId` can be instantiated by calling * {@link TenantManager.authForTenant}. */ class TenantAwareAuth extends base_auth_1.BaseAuth { /** * The TenantAwareAuth class constructor. * * @param app - The app that created this tenant. * @param tenantId - The corresponding tenant ID. * @constructor * @internal */ constructor(app, tenantId) { super(app, new auth_api_request_1.TenantAwareAuthRequestHandler(app, tenantId), (0, base_auth_1.createFirebaseTokenGenerator)(app, tenantId)); utils.addReadonlyGetter(this, 'tenantId', tenantId); } /** * {@inheritdoc BaseAuth.verifyIdToken} */ verifyIdToken(idToken, checkRevoked = false) { return super.verifyIdToken(idToken, checkRevoked) .then((decodedClaims) => { // Validate tenant ID. if (decodedClaims.firebase.tenant !== this.tenantId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID); } return decodedClaims; }); } /** * {@inheritdoc BaseAuth.createSessionCookie} */ createSessionCookie(idToken, sessionCookieOptions) { // Validate arguments before processing. if (!validator.isNonEmptyString(idToken)) { return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ID_TOKEN)); } if (!validator.isNonNullObject(sessionCookieOptions) || !validator.isNumber(sessionCookieOptions.expiresIn)) { return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION)); } // This will verify the ID token and then match the tenant ID before creating the session cookie. return this.verifyIdToken(idToken) .then(() => { return super.createSessionCookie(idToken, sessionCookieOptions); }); } /** * {@inheritdoc BaseAuth.verifySessionCookie} */ verifySessionCookie(sessionCookie, checkRevoked = false) { return super.verifySessionCookie(sessionCookie, checkRevoked) .then((decodedClaims) => { if (decodedClaims.firebase.tenant !== this.tenantId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID); } return decodedClaims; }); } } exports.TenantAwareAuth = TenantAwareAuth; /** * Defines the tenant manager used to help manage tenant related operations. * This includes: * <ul> * <li>The ability to create, update, list, get and delete tenants for the underlying * project.</li> * <li>Getting a `TenantAwareAuth` instance for running Auth related operations * (user management, provider configuration management, token verification, * email link generation, etc) in the context of a specified tenant.</li> * </ul> */ class TenantManager { /** * Initializes a TenantManager instance for a specified FirebaseApp. * * @param app - The app for this TenantManager instance. * * @constructor * @internal */ constructor(app) { this.app = app; this.authRequestHandler = new auth_api_request_1.AuthRequestHandler(app); this.tenantsMap = {}; } /** * Returns a `TenantAwareAuth` instance bound to the given tenant ID. * * @param tenantId - The tenant ID whose `TenantAwareAuth` instance is to be returned. * * @returns The `TenantAwareAuth` instance corresponding to this tenant identifier. */ authForTenant(tenantId) { if (!validator.isNonEmptyString(tenantId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID); } if (typeof this.tenantsMap[tenantId] === 'undefined') { this.tenantsMap[tenantId] = new TenantAwareAuth(this.app, tenantId); } return this.tenantsMap[tenantId]; } /** * Gets the tenant configuration for the tenant corresponding to a given `tenantId`. * * @param tenantId - The tenant identifier corresponding to the tenant whose data to fetch. * * @returns A promise fulfilled with the tenant configuration to the provided `tenantId`. */ getTenant(tenantId) { return this.authRequestHandler.getTenant(tenantId) .then((response) => { return new tenant_1.Tenant(response); }); } /** * Retrieves a list of tenants (single batch only) with a size of `maxResults` * starting from the offset as specified by `pageToken`. This is used to * retrieve all the tenants of a specified project in batches. * * @param maxResults - The page size, 1000 if undefined. This is also * the maximum allowed limit. * @param pageToken - The next page token. If not specified, returns * tenants starting without any offset. * * @returns A promise that resolves with * a batch of downloaded tenants and the next page token. */ listTenants(maxResults, pageToken) { return this.authRequestHandler.listTenants(maxResults, pageToken) .then((response) => { // List of tenants to return. const tenants = []; // Convert each user response to a Tenant. response.tenants.forEach((tenantResponse) => { tenants.push(new tenant_1.Tenant(tenantResponse)); }); // Return list of tenants and the next page token if available. const result = { tenants, pageToken: response.nextPageToken, }; // Delete result.pageToken if undefined. if (typeof result.pageToken === 'undefined') { delete result.pageToken; } return result; }); } /** * Deletes an existing tenant. * * @param tenantId - The `tenantId` corresponding to the tenant to delete. * * @returns An empty promise fulfilled once the tenant has been deleted. */ deleteTenant(tenantId) { return this.authRequestHandler.deleteTenant(tenantId); } /** * Creates a new tenant. * When creating new tenants, tenants that use separate billing and quota will require their * own project and must be defined as `full_service`. * * @param tenantOptions - The properties to set on the new tenant configuration to be created. * * @returns A promise fulfilled with the tenant configuration corresponding to the newly * created tenant. */ createTenant(tenantOptions) { return this.authRequestHandler.createTenant(tenantOptions) .then((response) => { return new tenant_1.Tenant(response); }); } /** * Updates an existing tenant configuration. * * @param tenantId - The `tenantId` corresponding to the tenant to delete. * @param tenantOptions - The properties to update on the provided tenant. * * @returns A promise fulfilled with the update tenant data. */ updateTenant(tenantId, tenantOptions) { return this.authRequestHandler.updateTenant(tenantId, tenantOptions) .then((response) => { return new tenant_1.Tenant(response); }); } } exports.TenantManager = TenantManager;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/identifier.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/identifier.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.isProviderIdentifier = exports.isPhoneIdentifier = exports.isEmailIdentifier = exports.isUidIdentifier = void 0; /* * User defined type guards. See * https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards */ function isUidIdentifier(id) { return id.uid !== undefined; } exports.isUidIdentifier = isUidIdentifier; function isEmailIdentifier(id) { return id.email !== undefined; } exports.isEmailIdentifier = isEmailIdentifier; function isPhoneIdentifier(id) { return id.phoneNumber !== undefined; } exports.isPhoneIdentifier = isPhoneIdentifier; function isProviderIdentifier(id) { const pid = id; return pid.providerId !== undefined && pid.providerUid !== undefined; } exports.isProviderIdentifier = isProviderIdentifier;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/tenant.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/tenant.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Tenant = void 0; const validator = require("../utils/validator"); const deep_copy_1 = require("../utils/deep-copy"); const error_1 = require("../utils/error"); const auth_config_1 = require("./auth-config"); /** * Represents a tenant configuration. * * Multi-tenancy support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * Before multi-tenancy can be used on a Google Cloud Identity Platform project, * tenants must be allowed on that project via the Cloud Console UI. * * A tenant configuration provides information such as the display name, tenant * identifier and email authentication configuration. * For OIDC/SAML provider configuration management, `TenantAwareAuth` instances should * be used instead of a `Tenant` to retrieve the list of configured IdPs on a tenant. * When configuring these providers, note that tenants will inherit * whitelisted domains and authenticated redirect URIs of their parent project. * * All other settings of a tenant will also be inherited. These will need to be managed * from the Cloud Console UI. */ class Tenant { /** * The Tenant object constructor. * * @param response - The server side response used to initialize the Tenant object. * @constructor * @internal */ constructor(response) { const tenantId = Tenant.getTenantIdFromResourceName(response.name); if (!tenantId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid tenant response'); } this.tenantId = tenantId; this.displayName = response.displayName; try { this.emailSignInConfig_ = new auth_config_1.EmailSignInConfig(response); } catch (e) { // If allowPasswordSignup is undefined, it is disabled by default. this.emailSignInConfig_ = new auth_config_1.EmailSignInConfig({ allowPasswordSignup: false, }); } this.anonymousSignInEnabled = !!response.enableAnonymousUser; if (typeof response.mfaConfig !== 'undefined') { this.multiFactorConfig_ = new auth_config_1.MultiFactorAuthConfig(response.mfaConfig); } if (typeof response.testPhoneNumbers !== 'undefined') { this.testPhoneNumbers = (0, deep_copy_1.deepCopy)(response.testPhoneNumbers || {}); } } /** * Builds the corresponding server request for a TenantOptions object. * * @param tenantOptions - The properties to convert to a server request. * @param createRequest - Whether this is a create request. * @returns The equivalent server request. * * @internal */ static buildServerRequest(tenantOptions, createRequest) { Tenant.validate(tenantOptions, createRequest); let request = {}; if (typeof tenantOptions.emailSignInConfig !== 'undefined') { request = auth_config_1.EmailSignInConfig.buildServerRequest(tenantOptions.emailSignInConfig); } if (typeof tenantOptions.displayName !== 'undefined') { request.displayName = tenantOptions.displayName; } if (typeof tenantOptions.anonymousSignInEnabled !== 'undefined') { request.enableAnonymousUser = tenantOptions.anonymousSignInEnabled; } if (typeof tenantOptions.multiFactorConfig !== 'undefined') { request.mfaConfig = auth_config_1.MultiFactorAuthConfig.buildServerRequest(tenantOptions.multiFactorConfig); } if (typeof tenantOptions.testPhoneNumbers !== 'undefined') { // null will clear existing test phone numbers. Translate to empty object. request.testPhoneNumbers = tenantOptions.testPhoneNumbers ?? {}; } return request; } /** * Returns the tenant ID corresponding to the resource name if available. * * @param resourceName - The server side resource name * @returns The tenant ID corresponding to the resource, null otherwise. * * @internal */ static getTenantIdFromResourceName(resourceName) { // name is of form projects/project1/tenants/tenant1 const matchTenantRes = resourceName.match(/\/tenants\/(.*)$/); if (!matchTenantRes || matchTenantRes.length < 2) { return null; } return matchTenantRes[1]; } /** * Validates a tenant options object. Throws an error on failure. * * @param request - The tenant options object to validate. * @param createRequest - Whether this is a create request. */ static validate(request, createRequest) { const validKeys = { displayName: true, emailSignInConfig: true, anonymousSignInEnabled: true, multiFactorConfig: true, testPhoneNumbers: true, }; const label = createRequest ? 'CreateTenantRequest' : 'UpdateTenantRequest'; if (!validator.isNonNullObject(request)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${label}" must be a valid non-null object.`); } // Check for unsupported top level attributes. for (const key in request) { if (!(key in validKeys)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${key}" is not a valid ${label} parameter.`); } } // Validate displayName type if provided. if (typeof request.displayName !== 'undefined' && !validator.isNonEmptyString(request.displayName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${label}.displayName" must be a valid non-empty string.`); } // Validate emailSignInConfig type if provided. if (typeof request.emailSignInConfig !== 'undefined') { // This will throw an error if invalid. auth_config_1.EmailSignInConfig.buildServerRequest(request.emailSignInConfig); } // Validate test phone numbers if provided. if (typeof request.testPhoneNumbers !== 'undefined' && request.testPhoneNumbers !== null) { (0, auth_config_1.validateTestPhoneNumbers)(request.testPhoneNumbers); } else if (request.testPhoneNumbers === null && createRequest) { // null allowed only for update operations. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${label}.testPhoneNumbers" must be a non-null object.`); } // Validate multiFactorConfig type if provided. if (typeof request.multiFactorConfig !== 'undefined') { // This will throw an error if invalid. auth_config_1.MultiFactorAuthConfig.buildServerRequest(request.multiFactorConfig); } } /** * The email sign in provider configuration. */ get emailSignInConfig() { return this.emailSignInConfig_; } /** * The multi-factor auth configuration on the current tenant. */ get multiFactorConfig() { return this.multiFactorConfig_; } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ toJSON() { const json = { tenantId: this.tenantId, displayName: this.displayName, emailSignInConfig: this.emailSignInConfig_?.toJSON(), multiFactorConfig: this.multiFactorConfig_?.toJSON(), anonymousSignInEnabled: this.anonymousSignInEnabled, testPhoneNumbers: this.testPhoneNumbers, }; if (typeof json.multiFactorConfig === 'undefined') { delete json.multiFactorConfig; } if (typeof json.testPhoneNumbers === 'undefined') { delete json.testPhoneNumbers; } return json; } } exports.Tenant = Tenant;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/user-import-builder.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/user-import-builder.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.UserImportBuilder = exports.convertMultiFactorInfoToServerFormat = void 0; const deep_copy_1 = require("../utils/deep-copy"); const utils = require("../utils"); const validator = require("../utils/validator"); const error_1 = require("../utils/error"); /** * Converts a client format second factor object to server format. * @param multiFactorInfo - The client format second factor. * @returns The corresponding AuthFactorInfo server request format. */ function convertMultiFactorInfoToServerFormat(multiFactorInfo) { let enrolledAt; if (typeof multiFactorInfo.enrollmentTime !== 'undefined') { if (validator.isUTCDateString(multiFactorInfo.enrollmentTime)) { // Convert from UTC date string (client side format) to ISO date string (server side format). enrolledAt = new Date(multiFactorInfo.enrollmentTime).toISOString(); } else { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLMENT_TIME, `The second factor "enrollmentTime" for "${multiFactorInfo.uid}" must be a valid ` + 'UTC date string.'); } } // Currently only phone second factors are supported. if (isPhoneFactor(multiFactorInfo)) { // If any required field is missing or invalid, validation will still fail later. const authFactorInfo = { mfaEnrollmentId: multiFactorInfo.uid, displayName: multiFactorInfo.displayName, // Required for all phone second factors. phoneInfo: multiFactorInfo.phoneNumber, enrolledAt, }; for (const objKey in authFactorInfo) { if (typeof authFactorInfo[objKey] === 'undefined') { delete authFactorInfo[objKey]; } } return authFactorInfo; } else { // Unsupported second factor. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.UNSUPPORTED_SECOND_FACTOR, `Unsupported second factor "${JSON.stringify(multiFactorInfo)}" provided.`); } } exports.convertMultiFactorInfoToServerFormat = convertMultiFactorInfoToServerFormat; function isPhoneFactor(multiFactorInfo) { return multiFactorInfo.factorId === 'phone'; } /** * @param {any} obj The object to check for number field within. * @param {string} key The entry key. * @returns {number} The corresponding number if available. Otherwise, NaN. */ function getNumberField(obj, key) { if (typeof obj[key] !== 'undefined' && obj[key] !== null) { return parseInt(obj[key].toString(), 10); } return NaN; } /** * Converts a UserImportRecord to a UploadAccountUser object. Throws an error when invalid * fields are provided. * @param {UserImportRecord} user The UserImportRecord to conver to UploadAccountUser. * @param {ValidatorFunction=} userValidator The user validator function. * @returns {UploadAccountUser} The corresponding UploadAccountUser to return. */ function populateUploadAccountUser(user, userValidator) { const result = { localId: user.uid, email: user.email, emailVerified: user.emailVerified, displayName: user.displayName, disabled: user.disabled, photoUrl: user.photoURL, phoneNumber: user.phoneNumber, providerUserInfo: [], mfaInfo: [], tenantId: user.tenantId, customAttributes: user.customClaims && JSON.stringify(user.customClaims), }; if (typeof user.passwordHash !== 'undefined') { if (!validator.isBuffer(user.passwordHash)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_HASH); } result.passwordHash = utils.toWebSafeBase64(user.passwordHash); } if (typeof user.passwordSalt !== 'undefined') { if (!validator.isBuffer(user.passwordSalt)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_SALT); } result.salt = utils.toWebSafeBase64(user.passwordSalt); } if (validator.isNonNullObject(user.metadata)) { if (validator.isNonEmptyString(user.metadata.creationTime)) { result.createdAt = new Date(user.metadata.creationTime).getTime(); } if (validator.isNonEmptyString(user.metadata.lastSignInTime)) { result.lastLoginAt = new Date(user.metadata.lastSignInTime).getTime(); } } if (validator.isArray(user.providerData)) { user.providerData.forEach((providerData) => { result.providerUserInfo.push({ providerId: providerData.providerId, rawId: providerData.uid, email: providerData.email, displayName: providerData.displayName, photoUrl: providerData.photoURL, }); }); } // Convert user.multiFactor.enrolledFactors to server format. if (validator.isNonNullObject(user.multiFactor) && validator.isNonEmptyArray(user.multiFactor.enrolledFactors)) { user.multiFactor.enrolledFactors.forEach((multiFactorInfo) => { result.mfaInfo.push(convertMultiFactorInfoToServerFormat(multiFactorInfo)); }); } // Remove blank fields. let key; for (key in result) { if (typeof result[key] === 'undefined') { delete result[key]; } } if (result.providerUserInfo.length === 0) { delete result.providerUserInfo; } if (result.mfaInfo.length === 0) { delete result.mfaInfo; } // Validate the constructured user individual request. This will throw if an error // is detected. if (typeof userValidator === 'function') { userValidator(result); } return result; } /** * Class that provides a helper for building/validating uploadAccount requests and * UserImportResult responses. */ class UserImportBuilder { /** * @param {UserImportRecord[]} users The list of user records to import. * @param {UserImportOptions=} options The import options which includes hashing * algorithm details. * @param {ValidatorFunction=} userRequestValidator The user request validator function. * @constructor */ constructor(users, options, userRequestValidator) { this.requiresHashOptions = false; this.validatedUsers = []; this.userImportResultErrors = []; this.indexMap = {}; this.validatedUsers = this.populateUsers(users, userRequestValidator); this.validatedOptions = this.populateOptions(options, this.requiresHashOptions); } /** * Returns the corresponding constructed uploadAccount request. * @returns {UploadAccountRequest} The constructed uploadAccount request. */ buildRequest() { const users = this.validatedUsers.map((user) => { return (0, deep_copy_1.deepCopy)(user); }); return (0, deep_copy_1.deepExtend)({ users }, (0, deep_copy_1.deepCopy)(this.validatedOptions)); } /** * Populates the UserImportResult using the client side detected errors and the server * side returned errors. * @returns {UserImportResult} The user import result based on the returned failed * uploadAccount response. */ buildResponse(failedUploads) { // Initialize user import result. const importResult = { successCount: this.validatedUsers.length, failureCount: this.userImportResultErrors.length, errors: (0, deep_copy_1.deepCopy)(this.userImportResultErrors), }; importResult.failureCount += failedUploads.length; importResult.successCount -= failedUploads.length; failedUploads.forEach((failedUpload) => { importResult.errors.push({ // Map backend request index to original developer provided array index. index: this.indexMap[failedUpload.index], error: new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_USER_IMPORT, failedUpload.message), }); }); // Sort errors by index. importResult.errors.sort((a, b) => { return a.index - b.index; }); // Return sorted result. return importResult; } /** * Validates and returns the hashing options of the uploadAccount request. * Throws an error whenever an invalid or missing options is detected. * @param {UserImportOptions} options The UserImportOptions. * @param {boolean} requiresHashOptions Whether to require hash options. * @returns {UploadAccountOptions} The populated UploadAccount options. */ populateOptions(options, requiresHashOptions) { let populatedOptions; if (!requiresHashOptions) { return {}; } if (!validator.isNonNullObject(options)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"UserImportOptions" are required when importing users with passwords.'); } if (!validator.isNonNullObject(options.hash)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_HASH_ALGORITHM, '"hash.algorithm" is missing from the provided "UserImportOptions".'); } if (typeof options.hash.algorithm === 'undefined' || !validator.isNonEmptyString(options.hash.algorithm)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ALGORITHM, '"hash.algorithm" must be a string matching the list of supported algorithms.'); } let rounds; switch (options.hash.algorithm) { case 'HMAC_SHA512': case 'HMAC_SHA256': case 'HMAC_SHA1': case 'HMAC_MD5': if (!validator.isBuffer(options.hash.key)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_KEY, 'A non-empty "hash.key" byte buffer must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } populatedOptions = { hashAlgorithm: options.hash.algorithm, signerKey: utils.toWebSafeBase64(options.hash.key), }; break; case 'MD5': case 'SHA1': case 'SHA256': case 'SHA512': { // MD5 is [0,8192] but SHA1, SHA256, and SHA512 are [1,8192] rounds = getNumberField(options.hash, 'rounds'); const minRounds = options.hash.algorithm === 'MD5' ? 0 : 1; if (isNaN(rounds) || rounds < minRounds || rounds > 8192) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, `A valid "hash.rounds" number between ${minRounds} and 8192 must be provided for ` + `hash algorithm ${options.hash.algorithm}.`); } populatedOptions = { hashAlgorithm: options.hash.algorithm, rounds, }; break; } case 'PBKDF_SHA1': case 'PBKDF2_SHA256': rounds = getNumberField(options.hash, 'rounds'); if (isNaN(rounds) || rounds < 0 || rounds > 120000) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, 'A valid "hash.rounds" number between 0 and 120000 must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } populatedOptions = { hashAlgorithm: options.hash.algorithm, rounds, }; break; case 'SCRYPT': { if (!validator.isBuffer(options.hash.key)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_KEY, 'A "hash.key" byte buffer must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } rounds = getNumberField(options.hash, 'rounds'); if (isNaN(rounds) || rounds <= 0 || rounds > 8) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, 'A valid "hash.rounds" number between 1 and 8 must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } const memoryCost = getNumberField(options.hash, 'memoryCost'); if (isNaN(memoryCost) || memoryCost <= 0 || memoryCost > 14) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_MEMORY_COST, 'A valid "hash.memoryCost" number between 1 and 14 must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } if (typeof options.hash.saltSeparator !== 'undefined' && !validator.isBuffer(options.hash.saltSeparator)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_SALT_SEPARATOR, '"hash.saltSeparator" must be a byte buffer.'); } populatedOptions = { hashAlgorithm: options.hash.algorithm, signerKey: utils.toWebSafeBase64(options.hash.key), rounds, memoryCost, saltSeparator: utils.toWebSafeBase64(options.hash.saltSeparator || Buffer.from('')), }; break; } case 'BCRYPT': populatedOptions = { hashAlgorithm: options.hash.algorithm, }; break; case 'STANDARD_SCRYPT': { const cpuMemCost = getNumberField(options.hash, 'memoryCost'); if (isNaN(cpuMemCost)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_MEMORY_COST, 'A valid "hash.memoryCost" number must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } const parallelization = getNumberField(options.hash, 'parallelization'); if (isNaN(parallelization)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_PARALLELIZATION, 'A valid "hash.parallelization" number must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } const blockSize = getNumberField(options.hash, 'blockSize'); if (isNaN(blockSize)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_BLOCK_SIZE, 'A valid "hash.blockSize" number must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } const dkLen = getNumberField(options.hash, 'derivedKeyLength'); if (isNaN(dkLen)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_DERIVED_KEY_LENGTH, 'A valid "hash.derivedKeyLength" number must be provided for ' + `hash algorithm ${options.hash.algorithm}.`); } populatedOptions = { hashAlgorithm: options.hash.algorithm, cpuMemCost, parallelization, blockSize, dkLen, }; break; } default: throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ALGORITHM, `Unsupported hash algorithm provider "${options.hash.algorithm}".`); } return populatedOptions; } /** * Validates and returns the users list of the uploadAccount request. * Whenever a user with an error is detected, the error is cached and will later be * merged into the user import result. This allows the processing of valid users without * failing early on the first error detected. * @param {UserImportRecord[]} users The UserImportRecords to convert to UnploadAccountUser * objects. * @param {ValidatorFunction=} userValidator The user validator function. * @returns {UploadAccountUser[]} The populated uploadAccount users. */ populateUsers(users, userValidator) { const populatedUsers = []; users.forEach((user, index) => { try { const result = populateUploadAccountUser(user, userValidator); if (typeof result.passwordHash !== 'undefined') { this.requiresHashOptions = true; } // Only users that pass client screening will be passed to backend for processing. populatedUsers.push(result); // Map user's index (the one to be sent to backend) to original developer provided array. this.indexMap[populatedUsers.length - 1] = index; } catch (error) { // Save the client side error with respect to the developer provided array. this.userImportResultErrors.push({ index, error, }); } }); return populatedUsers; } } exports.UserImportBuilder = UserImportBuilder;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth-api-request.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/auth-api-request.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.useEmulator = exports.TenantAwareAuthRequestHandler = exports.AuthRequestHandler = exports.AbstractAuthRequestHandler = exports.FIREBASE_AUTH_SIGN_UP_NEW_USER = exports.FIREBASE_AUTH_SET_ACCOUNT_INFO = exports.FIREBASE_AUTH_BATCH_DELETE_ACCOUNTS = exports.FIREBASE_AUTH_DELETE_ACCOUNT = exports.FIREBASE_AUTH_GET_ACCOUNTS_INFO = exports.FIREBASE_AUTH_GET_ACCOUNT_INFO = exports.FIREBASE_AUTH_DOWNLOAD_ACCOUNT = exports.FIREBASE_AUTH_UPLOAD_ACCOUNT = exports.FIREBASE_AUTH_CREATE_SESSION_COOKIE = exports.EMAIL_ACTION_REQUEST_TYPES = exports.RESERVED_CLAIMS = void 0; const validator = require("../utils/validator"); const deep_copy_1 = require("../utils/deep-copy"); const error_1 = require("../utils/error"); const api_request_1 = require("../utils/api-request"); const utils = require("../utils/index"); const user_import_builder_1 = require("./user-import-builder"); const action_code_settings_builder_1 = require("./action-code-settings-builder"); const tenant_1 = require("./tenant"); const identifier_1 = require("./identifier"); const auth_config_1 = require("./auth-config"); /** Firebase Auth request header. */ const FIREBASE_AUTH_HEADER = { 'X-Client-Version': `Node/Admin/${utils.getSdkVersion()}`, }; /** Firebase Auth request timeout duration in milliseconds. */ const FIREBASE_AUTH_TIMEOUT = 25000; /** List of reserved claims which cannot be provided when creating a custom token. */ exports.RESERVED_CLAIMS = [ 'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti', 'nbf', 'nonce', 'sub', 'firebase', ]; /** List of supported email action request types. */ exports.EMAIL_ACTION_REQUEST_TYPES = [ 'PASSWORD_RESET', 'VERIFY_EMAIL', 'EMAIL_SIGNIN', 'VERIFY_AND_CHANGE_EMAIL', ]; /** Maximum allowed number of characters in the custom claims payload. */ const MAX_CLAIMS_PAYLOAD_SIZE = 1000; /** Maximum allowed number of users to batch download at one time. */ const MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE = 1000; /** Maximum allowed number of users to batch upload at one time. */ const MAX_UPLOAD_ACCOUNT_BATCH_SIZE = 1000; /** Maximum allowed number of users to batch get at one time. */ const MAX_GET_ACCOUNTS_BATCH_SIZE = 100; /** Maximum allowed number of users to batch delete at one time. */ const MAX_DELETE_ACCOUNTS_BATCH_SIZE = 1000; /** Minimum allowed session cookie duration in seconds (5 minutes). */ const MIN_SESSION_COOKIE_DURATION_SECS = 5 * 60; /** Maximum allowed session cookie duration in seconds (2 weeks). */ const MAX_SESSION_COOKIE_DURATION_SECS = 14 * 24 * 60 * 60; /** Maximum allowed number of provider configurations to batch download at one time. */ const MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE = 100; /** The Firebase Auth backend base URL format. */ const FIREBASE_AUTH_BASE_URL_FORMAT = 'https://identitytoolkit.googleapis.com/{version}/projects/{projectId}{api}'; /** Firebase Auth base URlLformat when using the auth emultor. */ const FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT = 'http://{host}/identitytoolkit.googleapis.com/{version}/projects/{projectId}{api}'; /** The Firebase Auth backend multi-tenancy base URL format. */ const FIREBASE_AUTH_TENANT_URL_FORMAT = FIREBASE_AUTH_BASE_URL_FORMAT.replace('projects/{projectId}', 'projects/{projectId}/tenants/{tenantId}'); /** Firebase Auth base URL format when using the auth emultor with multi-tenancy. */ const FIREBASE_AUTH_EMULATOR_TENANT_URL_FORMAT = FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT.replace('projects/{projectId}', 'projects/{projectId}/tenants/{tenantId}'); /** Maximum allowed number of tenants to download at one time. */ const MAX_LIST_TENANT_PAGE_SIZE = 1000; /** * Enum for the user write operation type. */ var WriteOperationType; (function (WriteOperationType) { WriteOperationType["Create"] = "create"; WriteOperationType["Update"] = "update"; WriteOperationType["Upload"] = "upload"; })(WriteOperationType || (WriteOperationType = {})); /** Defines a base utility to help with resource URL construction. */ class AuthResourceUrlBuilder { /** * The resource URL builder constructor. * * @param projectId - The resource project ID. * @param version - The endpoint API version. * @constructor */ constructor(app, version = 'v1') { this.app = app; this.version = version; if (useEmulator()) { this.urlFormat = utils.formatString(FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT, { host: emulatorHost() }); } else { this.urlFormat = FIREBASE_AUTH_BASE_URL_FORMAT; } } /** * Returns the resource URL corresponding to the provided parameters. * * @param api - The backend API name. * @param params - The optional additional parameters to substitute in the * URL path. * @returns The corresponding resource URL. */ getUrl(api, params) { return this.getProjectId() .then((projectId) => { const baseParams = { version: this.version, projectId, api: api || '', }; const baseUrl = utils.formatString(this.urlFormat, baseParams); // Substitute additional api related parameters. return utils.formatString(baseUrl, params || {}); }); } getProjectId() { if (this.projectId) { return Promise.resolve(this.projectId); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'Failed to determine project ID for Auth. Initialize the ' + 'SDK with service account credentials or set project ID as an app option. ' + 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.'); } this.projectId = projectId; return projectId; }); } } /** Tenant aware resource builder utility. */ class TenantAwareAuthResourceUrlBuilder extends AuthResourceUrlBuilder { /** * The tenant aware resource URL builder constructor. * * @param projectId - The resource project ID. * @param version - The endpoint API version. * @param tenantId - The tenant ID. * @constructor */ constructor(app, version, tenantId) { super(app, version); this.app = app; this.version = version; this.tenantId = tenantId; if (useEmulator()) { this.urlFormat = utils.formatString(FIREBASE_AUTH_EMULATOR_TENANT_URL_FORMAT, { host: emulatorHost() }); } else { this.urlFormat = FIREBASE_AUTH_TENANT_URL_FORMAT; } } /** * Returns the resource URL corresponding to the provided parameters. * * @param api - The backend API name. * @param params - The optional additional parameters to substitute in the * URL path. * @returns The corresponding resource URL. */ getUrl(api, params) { return super.getUrl(api, params) .then((url) => { return utils.formatString(url, { tenantId: this.tenantId }); }); } } /** * Auth-specific HTTP client which uses the special "owner" token * when communicating with the Auth Emulator. */ class AuthHttpClient extends api_request_1.AuthorizedHttpClient { getToken() { if (useEmulator()) { return Promise.resolve('owner'); } return super.getToken(); } } /** * Validates an AuthFactorInfo object. All unsupported parameters * are removed from the original request. If an invalid field is passed * an error is thrown. * * @param request - The AuthFactorInfo request object. */ function validateAuthFactorInfo(request) { const validKeys = { mfaEnrollmentId: true, displayName: true, phoneInfo: true, enrolledAt: true, }; // Remove unsupported keys from the original request. for (const key in request) { if (!(key in validKeys)) { delete request[key]; } } // No enrollment ID is available for signupNewUser. Use another identifier. const authFactorInfoIdentifier = request.mfaEnrollmentId || request.phoneInfo || JSON.stringify(request); // Enrollment uid may or may not be specified for update operations. if (typeof request.mfaEnrollmentId !== 'undefined' && !validator.isNonEmptyString(request.mfaEnrollmentId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID, 'The second factor "uid" must be a valid non-empty string.'); } if (typeof request.displayName !== 'undefined' && !validator.isString(request.displayName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISPLAY_NAME, `The second factor "displayName" for "${authFactorInfoIdentifier}" must be a valid string.`); } // enrolledAt must be a valid UTC date string. if (typeof request.enrolledAt !== 'undefined' && !validator.isISODateString(request.enrolledAt)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLMENT_TIME, `The second factor "enrollmentTime" for "${authFactorInfoIdentifier}" must be a valid ` + 'UTC date string.'); } // Validate required fields depending on second factor type. if (typeof request.phoneInfo !== 'undefined') { // phoneNumber should be a string and a valid phone number. if (!validator.isPhoneNumber(request.phoneInfo)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHONE_NUMBER, `The second factor "phoneNumber" for "${authFactorInfoIdentifier}" must be a non-empty ` + 'E.164 standard compliant identifier string.'); } } else { // Invalid second factor. For example, a phone second factor may have been provided without // a phone number. A TOTP based second factor may require a secret key, etc. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLED_FACTORS, 'MFAInfo object provided is invalid.'); } } /** * Validates a providerUserInfo object. All unsupported parameters * are removed from the original request. If an invalid field is passed * an error is thrown. * * @param request - The providerUserInfo request object. */ function validateProviderUserInfo(request) { const validKeys = { rawId: true, providerId: true, email: true, displayName: true, photoUrl: true, }; // Remove invalid keys from original request. for (const key in request) { if (!(key in validKeys)) { delete request[key]; } } if (!validator.isNonEmptyString(request.providerId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID); } if (typeof request.displayName !== 'undefined' && typeof request.displayName !== 'string') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISPLAY_NAME, `The provider "displayName" for "${request.providerId}" must be a valid string.`); } if (!validator.isNonEmptyString(request.rawId)) { // This is called localId on the backend but the developer specifies this as // uid externally. So the error message should use the client facing name. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID, `The provider "uid" for "${request.providerId}" must be a valid non-empty string.`); } // email should be a string and a valid email. if (typeof request.email !== 'undefined' && !validator.isEmail(request.email)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL, `The provider "email" for "${request.providerId}" must be a valid email string.`); } // photoUrl should be a URL. if (typeof request.photoUrl !== 'undefined' && !validator.isURL(request.photoUrl)) { // This is called photoUrl on the backend but the developer specifies this as // photoURL externally. So the error message should use the client facing name. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHOTO_URL, `The provider "photoURL" for "${request.providerId}" must be a valid URL string.`); } } /** * Validates a create/edit request object. All unsupported parameters * are removed from the original request. If an invalid field is passed * an error is thrown. * * @param request - The create/edit request object. * @param writeOperationType - The write operation type. */ function validateCreateEditRequest(request, writeOperationType) { const uploadAccountRequest = writeOperationType === WriteOperationType.Upload; // Hash set of whitelisted parameters. const validKeys = { displayName: true, localId: true, email: true, password: true, rawPassword: true, emailVerified: true, photoUrl: true, disabled: true, disableUser: true, deleteAttribute: true, deleteProvider: true, sanityCheck: true, phoneNumber: true, customAttributes: true, validSince: true, // Pass linkProviderUserInfo only for updates (i.e. not for uploads.) linkProviderUserInfo: !uploadAccountRequest, // Pass tenantId only for uploadAccount requests. tenantId: uploadAccountRequest, passwordHash: uploadAccountRequest, salt: uploadAccountRequest, createdAt: uploadAccountRequest, lastLoginAt: uploadAccountRequest, providerUserInfo: uploadAccountRequest, mfaInfo: uploadAccountRequest, // Only for non-uploadAccount requests. mfa: !uploadAccountRequest, }; // Remove invalid keys from original request. for (const key in request) { if (!(key in validKeys)) { delete request[key]; } } if (typeof request.tenantId !== 'undefined' && !validator.isNonEmptyString(request.tenantId)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID); } // For any invalid parameter, use the external key name in the error description. // displayName should be a string. if (typeof request.displayName !== 'undefined' && !validator.isString(request.displayName)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISPLAY_NAME); } if ((typeof request.localId !== 'undefined' || uploadAccountRequest) && !validator.isUid(request.localId)) { // This is called localId on the backend but the developer specifies this as // uid externally. So the error message should use the client facing name. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_UID); } // email should be a string and a valid email. if (typeof request.email !== 'undefined' && !validator.isEmail(request.email)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL); } // phoneNumber should be a string and a valid phone number. if (typeof request.phoneNumber !== 'undefined' && !validator.isPhoneNumber(request.phoneNumber)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHONE_NUMBER); } // password should be a string and a minimum of 6 chars. if (typeof request.password !== 'undefined' && !validator.isPassword(request.password)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD); } // rawPassword should be a string and a minimum of 6 chars. if (typeof request.rawPassword !== 'undefined' && !validator.isPassword(request.rawPassword)) { // This is called rawPassword on the backend but the developer specifies this as // password externally. So the error message should use the client facing name. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD); } // emailVerified should be a boolean. if (typeof request.emailVerified !== 'undefined' && typeof request.emailVerified !== 'boolean') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL_VERIFIED); } // photoUrl should be a URL. if (typeof request.photoUrl !== 'undefined' && !validator.isURL(request.photoUrl)) { // This is called photoUrl on the backend but the developer specifies this as // photoURL externally. So the error message should use the client facing name. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PHOTO_URL); } // disabled should be a boolean. if (typeof request.disabled !== 'undefined' && typeof request.disabled !== 'boolean') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISABLED_FIELD); } // validSince should be a number. if (typeof request.validSince !== 'undefined' && !validator.isNumber(request.validSince)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TOKENS_VALID_AFTER_TIME); } // createdAt should be a number. if (typeof request.createdAt !== 'undefined' && !validator.isNumber(request.createdAt)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREATION_TIME); } // lastSignInAt should be a number. if (typeof request.lastLoginAt !== 'undefined' && !validator.isNumber(request.lastLoginAt)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_LAST_SIGN_IN_TIME); } // disableUser should be a boolean. if (typeof request.disableUser !== 'undefined' && typeof request.disableUser !== 'boolean') { // This is called disableUser on the backend but the developer specifies this as // disabled externally. So the error message should use the client facing name. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DISABLED_FIELD); } // customAttributes should be stringified JSON with no blacklisted claims. // The payload should not exceed 1KB. if (typeof request.customAttributes !== 'undefined') { let developerClaims; try { developerClaims = JSON.parse(request.customAttributes); } catch (error) { // JSON parsing error. This should never happen as we stringify the claims internally. // However, we still need to check since setAccountInfo via edit requests could pass // this field. throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CLAIMS, error.message); } const invalidClaims = []; // Check for any invalid claims. exports.RESERVED_CLAIMS.forEach((blacklistedClaim) => { if (Object.prototype.hasOwnProperty.call(developerClaims, blacklistedClaim)) { invalidClaims.push(blacklistedClaim); } }); // Throw an error if an invalid claim is detected. if (invalidClaims.length > 0) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.FORBIDDEN_CLAIM, invalidClaims.length > 1 ? `Developer claims "${invalidClaims.join('", "')}" are reserved and cannot be specified.` : `Developer claim "${invalidClaims[0]}" is reserved and cannot be specified.`); } // Check claims payload does not exceed maxmimum size. if (request.customAttributes.length > MAX_CLAIMS_PAYLOAD_SIZE) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.CLAIMS_TOO_LARGE, `Developer claims payload should not exceed ${MAX_CLAIMS_PAYLOAD_SIZE} characters.`); } } // passwordHash has to be a base64 encoded string. if (typeof request.passwordHash !== 'undefined' && !validator.isString(request.passwordHash)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_HASH); } // salt has to be a base64 encoded string. if (typeof request.salt !== 'undefined' && !validator.isString(request.salt)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_SALT); } // providerUserInfo has to be an array of valid UserInfo requests. if (typeof request.providerUserInfo !== 'undefined' && !validator.isArray(request.providerUserInfo)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_DATA); } else if (validator.isArray(request.providerUserInfo)) { request.providerUserInfo.forEach((providerUserInfoEntry) => { validateProviderUserInfo(providerUserInfoEntry); }); } // linkProviderUserInfo must be a (single) UserProvider value. if (typeof request.linkProviderUserInfo !== 'undefined') { validateProviderUserInfo(request.linkProviderUserInfo); } // mfaInfo is used for importUsers. // mfa.enrollments is used for setAccountInfo. // enrollments has to be an array of valid AuthFactorInfo requests. let enrollments = null; if (request.mfaInfo) { enrollments = request.mfaInfo; } else if (request.mfa && request.mfa.enrollments) { enrollments = request.mfa.enrollments; } if (enrollments) { if (!validator.isArray(enrollments)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ENROLLED_FACTORS); } enrollments.forEach((authFactorInfoEntry) => { validateAuthFactorInfo(authFactorInfoEntry); }); } } /** * Instantiates the createSessionCookie endpoint settings. * * @internal */ exports.FIREBASE_AUTH_CREATE_SESSION_COOKIE = new api_request_1.ApiSettings(':createSessionCookie', 'POST') // Set request validator. .setRequestValidator((request) => { // Validate the ID token is a non-empty string. if (!validator.isNonEmptyString(request.idToken)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ID_TOKEN); } // Validate the custom session cookie duration. if (!validator.isNumber(request.validDuration) || request.validDuration < MIN_SESSION_COOKIE_DURATION_SECS || request.validDuration > MAX_SESSION_COOKIE_DURATION_SECS) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION); } }) // Set response validator. .setResponseValidator((response) => { // Response should always contain the session cookie. if (!validator.isNonEmptyString(response.sessionCookie)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR); } }); /** * Instantiates the uploadAccount endpoint settings. * * @internal */ exports.FIREBASE_AUTH_UPLOAD_ACCOUNT = new api_request_1.ApiSettings('/accounts:batchCreate', 'POST'); /** * Instantiates the downloadAccount endpoint settings. * * @internal */ exports.FIREBASE_AUTH_DOWNLOAD_ACCOUNT = new api_request_1.ApiSettings('/accounts:batchGet', 'GET') // Set request validator. .setRequestValidator((request) => { // Validate next page token. if (typeof request.nextPageToken !== 'undefined' && !validator.isNonEmptyString(request.nextPageToken)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PAGE_TOKEN); } // Validate max results. if (!validator.isNumber(request.maxResults) || request.maxResults <= 0 || request.maxResults > MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'Required "maxResults" must be a positive integer that does not exceed ' + `${MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE}.`); } }); /** * Instantiates the getAccountInfo endpoint settings. * * @internal */ exports.FIREBASE_AUTH_GET_ACCOUNT_INFO = new api_request_1.ApiSettings('/accounts:lookup', 'POST') // Set request validator. .setRequestValidator((request) => { if (!request.localId && !request.email && !request.phoneNumber && !request.federatedUserId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); } }) // Set response validator. .setResponseValidator((response) => { if (!response.users || !response.users.length) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.USER_NOT_FOUND); } }); /** * Instantiates the getAccountInfo endpoint settings for use when fetching info * for multiple accounts. * * @internal */ exports.FIREBASE_AUTH_GET_ACCOUNTS_INFO = new api_request_1.ApiSettings('/accounts:lookup', 'POST') // Set request validator. .setRequestValidator((request) => { if (!request.localId && !request.email && !request.phoneNumber && !request.federatedUserId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); } }); /** * Instantiates the deleteAccount endpoint settings. * * @internal */ exports.FIREBASE_AUTH_DELETE_ACCOUNT = new api_request_1.ApiSettings('/accounts:delete', 'POST') // Set request validator. .setRequestValidator((request) => { if (!request.localId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); } }); /** * @internal */ exports.FIREBASE_AUTH_BATCH_DELETE_ACCOUNTS = new api_request_1.ApiSettings('/accounts:batchDelete', 'POST') .setRequestValidator((request) => { if (!request.localIds) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifiers'); } if (typeof request.force === 'undefined' || request.force !== true) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing force=true field'); } }) .setResponseValidator((response) => { const errors = response.errors || []; errors.forEach((batchDeleteErrorInfo) => { if (typeof batchDeleteErrorInfo.index === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server BatchDeleteAccountResponse is missing an errors.index field'); } if (!batchDeleteErrorInfo.localId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server BatchDeleteAccountResponse is missing an errors.localId field'); } // Allow the (error) message to be missing/undef. }); }); /** * Instantiates the setAccountInfo endpoint settings for updating existing accounts. * * @internal */ exports.FIREBASE_AUTH_SET_ACCOUNT_INFO = new api_request_1.ApiSettings('/accounts:update', 'POST') // Set request validator. .setRequestValidator((request) => { // localId is a required parameter. if (typeof request.localId === 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Server request is missing user identifier'); } // Throw error when tenantId is passed in POST body. if (typeof request.tenantId !== 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"tenantId" is an invalid "UpdateRequest" property.'); } validateCreateEditRequest(request, WriteOperationType.Update); }) // Set response validator. .setResponseValidator((response) => { // If the localId is not returned, then the request failed. if (!response.localId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.USER_NOT_FOUND); } }); /** * Instantiates the signupNewUser endpoint settings for creating a new user with or without * uid being specified. The backend will create a new one if not provided and return it. * * @internal */ exports.FIREBASE_AUTH_SIGN_UP_NEW_USER = new api_request_1.ApiSettings('/accounts', 'POST') // Set request validator. .setRequestValidator((request) => { // signupNewUser does not support customAttributes. if (typeof request.customAttributes !== 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"customAttributes" cannot be set when creating a new user.'); } // signupNewUser does not support validSince. if (typeof request.validSince !== 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"validSince" cannot be set when creating a new user.'); } // Throw error when tenantId is passed in POST body. if (typeof request.tenantId !== 'undefined') { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"tenantId" is an invalid "CreateRequest" property.'); } validateCreateEditRequest(request, WriteOperationType.Create); }) // Set response validator. .setResponseValidator((response) => { // If the localId is not returned, then the request failed. if (!response.localId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create new user'); } }); const FIREBASE_AUTH_GET_OOB_CODE = new api_request_1.ApiSettings('/accounts:sendOobCode', 'POST') // Set request validator. .setRequestValidator((request) => { if (!validator.isEmail(request.email)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_EMAIL); } if (typeof request.newEmail !== 'undefined' && !validator.isEmail(request.newEmail)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_NEW_EMAIL); } if (exports.EMAIL_ACTION_REQUEST_TYPES.indexOf(request.requestType) === -1) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, `"${request.requestType}" is not a supported email action request type.`); } }) // Set response validator. .setResponseValidator((response) => { // If the oobLink is not returned, then the request failed. if (!response.oobLink) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to create the email action link'); } }); /** * Instantiates the retrieve OIDC configuration endpoint settings. * * @internal */ const GET_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs/{providerId}', 'GET') // Set response validator. .setResponseValidator((response) => { // Response should always contain the OIDC provider resource name. if (!validator.isNonEmptyString(response.name)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Unable to get OIDC configuration'); } }); /** * Instantiates the delete OIDC configuration endpoint settings. * * @internal */ const DELETE_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs/{providerId}', 'DELETE'); /** * Instantiates the create OIDC configuration endpoint settings. * * @internal */ const CREATE_OAUTH_IDP_CONFIG = new api_request_1.ApiSettings('/oauthIdpConfigs?oauthIdpConfigId={providerId}', 'POST') // Set response validator. .setResponseValidator((response) => {
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/auth/user-record.js
aws/lti-middleware/node_modules/firebase-admin/lib/auth/user-record.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.UserRecord = exports.UserInfo = exports.UserMetadata = exports.MultiFactorSettings = exports.PhoneMultiFactorInfo = exports.MultiFactorInfo = void 0; const deep_copy_1 = require("../utils/deep-copy"); const validator_1 = require("../utils/validator"); const utils = require("../utils"); const error_1 = require("../utils/error"); /** * 'REDACTED', encoded as a base64 string. */ const B64_REDACTED = Buffer.from('REDACTED').toString('base64'); /** * Parses a time stamp string or number and returns the corresponding date if valid. * * @param time - The unix timestamp string or number in milliseconds. * @returns The corresponding date as a UTC string, if valid. Otherwise, null. */ function parseDate(time) { try { const date = new Date(parseInt(time, 10)); if (!isNaN(date.getTime())) { return date.toUTCString(); } } catch (e) { // Do nothing. null will be returned. } return null; } var MultiFactorId; (function (MultiFactorId) { MultiFactorId["Phone"] = "phone"; })(MultiFactorId || (MultiFactorId = {})); /** * Interface representing the common properties of a user-enrolled second factor. */ class MultiFactorInfo { /** * Initializes the MultiFactorInfo object using the server side response. * * @param response - The server side response. * @constructor * @internal */ constructor(response) { this.initFromServerResponse(response); } /** * Initializes the MultiFactorInfo associated subclass using the server side. * If no MultiFactorInfo is associated with the response, null is returned. * * @param response - The server side response. * @internal */ static initMultiFactorInfo(response) { let multiFactorInfo = null; // Only PhoneMultiFactorInfo currently available. try { multiFactorInfo = new PhoneMultiFactorInfo(response); } catch (e) { // Ignore error. } return multiFactorInfo; } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ toJSON() { return { uid: this.uid, displayName: this.displayName, factorId: this.factorId, enrollmentTime: this.enrollmentTime, }; } /** * Initializes the MultiFactorInfo object using the provided server response. * * @param response - The server side response. */ initFromServerResponse(response) { const factorId = response && this.getFactorId(response); if (!factorId || !response || !response.mfaEnrollmentId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor info response'); } utils.addReadonlyGetter(this, 'uid', response.mfaEnrollmentId); utils.addReadonlyGetter(this, 'factorId', factorId); utils.addReadonlyGetter(this, 'displayName', response.displayName); // Encoded using [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. // For example, "2017-01-15T01:30:15.01Z". // This can be parsed directly via Date constructor. // This can be computed using Data.prototype.toISOString. if (response.enrolledAt) { utils.addReadonlyGetter(this, 'enrollmentTime', new Date(response.enrolledAt).toUTCString()); } else { utils.addReadonlyGetter(this, 'enrollmentTime', null); } } } exports.MultiFactorInfo = MultiFactorInfo; /** * Interface representing a phone specific user-enrolled second factor. */ class PhoneMultiFactorInfo extends MultiFactorInfo { /** * Initializes the PhoneMultiFactorInfo object using the server side response. * * @param response - The server side response. * @constructor * @internal */ constructor(response) { super(response); utils.addReadonlyGetter(this, 'phoneNumber', response.phoneInfo); } /** * {@inheritdoc MultiFactorInfo.toJSON} */ toJSON() { return Object.assign(super.toJSON(), { phoneNumber: this.phoneNumber, }); } /** * Returns the factor ID based on the response provided. * * @param response - The server side response. * @returns The multi-factor ID associated with the provided response. If the response is * not associated with any known multi-factor ID, null is returned. * * @internal */ getFactorId(response) { return (response && response.phoneInfo) ? MultiFactorId.Phone : null; } } exports.PhoneMultiFactorInfo = PhoneMultiFactorInfo; /** * The multi-factor related user settings. */ class MultiFactorSettings { /** * Initializes the MultiFactor object using the server side or JWT format response. * * @param response - The server side response. * @constructor * @internal */ constructor(response) { const parsedEnrolledFactors = []; if (!(0, validator_1.isNonNullObject)(response)) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid multi-factor response'); } else if (response.mfaInfo) { response.mfaInfo.forEach((factorResponse) => { const multiFactorInfo = MultiFactorInfo.initMultiFactorInfo(factorResponse); if (multiFactorInfo) { parsedEnrolledFactors.push(multiFactorInfo); } }); } // Make enrolled factors immutable. utils.addReadonlyGetter(this, 'enrolledFactors', Object.freeze(parsedEnrolledFactors)); } /** * Returns a JSON-serializable representation of this multi-factor object. * * @returns A JSON-serializable representation of this multi-factor object. */ toJSON() { return { enrolledFactors: this.enrolledFactors.map((info) => info.toJSON()), }; } } exports.MultiFactorSettings = MultiFactorSettings; /** * Represents a user's metadata. */ class UserMetadata { /** * @param response - The server side response returned from the getAccountInfo * endpoint. * @constructor * @internal */ constructor(response) { // Creation date should always be available but due to some backend bugs there // were cases in the past where users did not have creation date properly set. // This included legacy Firebase migrating project users and some anonymous users. // These bugs have already been addressed since then. utils.addReadonlyGetter(this, 'creationTime', parseDate(response.createdAt)); utils.addReadonlyGetter(this, 'lastSignInTime', parseDate(response.lastLoginAt)); const lastRefreshAt = response.lastRefreshAt ? new Date(response.lastRefreshAt).toUTCString() : null; utils.addReadonlyGetter(this, 'lastRefreshTime', lastRefreshAt); } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ toJSON() { return { lastSignInTime: this.lastSignInTime, creationTime: this.creationTime, }; } } exports.UserMetadata = UserMetadata; /** * Represents a user's info from a third-party identity provider * such as Google or Facebook. */ class UserInfo { /** * @param response - The server side response returned from the `getAccountInfo` * endpoint. * @constructor * @internal */ constructor(response) { // Provider user id and provider id are required. if (!response.rawId || !response.providerId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user info response'); } utils.addReadonlyGetter(this, 'uid', response.rawId); utils.addReadonlyGetter(this, 'displayName', response.displayName); utils.addReadonlyGetter(this, 'email', response.email); utils.addReadonlyGetter(this, 'photoURL', response.photoUrl); utils.addReadonlyGetter(this, 'providerId', response.providerId); utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ toJSON() { return { uid: this.uid, displayName: this.displayName, email: this.email, photoURL: this.photoURL, providerId: this.providerId, phoneNumber: this.phoneNumber, }; } } exports.UserInfo = UserInfo; /** * Represents a user. */ class UserRecord { /** * @param response - The server side response returned from the getAccountInfo * endpoint. * @constructor * @internal */ constructor(response) { // The Firebase user id is required. if (!response.localId) { throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user response'); } utils.addReadonlyGetter(this, 'uid', response.localId); utils.addReadonlyGetter(this, 'email', response.email); utils.addReadonlyGetter(this, 'emailVerified', !!response.emailVerified); utils.addReadonlyGetter(this, 'displayName', response.displayName); utils.addReadonlyGetter(this, 'photoURL', response.photoUrl); utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber); // If disabled is not provided, the account is enabled by default. utils.addReadonlyGetter(this, 'disabled', response.disabled || false); utils.addReadonlyGetter(this, 'metadata', new UserMetadata(response)); const providerData = []; for (const entry of (response.providerUserInfo || [])) { providerData.push(new UserInfo(entry)); } utils.addReadonlyGetter(this, 'providerData', providerData); // If the password hash is redacted (probably due to missing permissions) // then clear it out, similar to how the salt is returned. (Otherwise, it // *looks* like a b64-encoded hash is present, which is confusing.) if (response.passwordHash === B64_REDACTED) { utils.addReadonlyGetter(this, 'passwordHash', undefined); } else { utils.addReadonlyGetter(this, 'passwordHash', response.passwordHash); } utils.addReadonlyGetter(this, 'passwordSalt', response.salt); if (response.customAttributes) { utils.addReadonlyGetter(this, 'customClaims', JSON.parse(response.customAttributes)); } let validAfterTime = null; // Convert validSince first to UTC milliseconds and then to UTC date string. if (typeof response.validSince !== 'undefined') { validAfterTime = parseDate(parseInt(response.validSince, 10) * 1000); } utils.addReadonlyGetter(this, 'tokensValidAfterTime', validAfterTime || undefined); utils.addReadonlyGetter(this, 'tenantId', response.tenantId); const multiFactor = new MultiFactorSettings(response); if (multiFactor.enrolledFactors.length > 0) { utils.addReadonlyGetter(this, 'multiFactor', multiFactor); } } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ toJSON() { const json = { uid: this.uid, email: this.email, emailVerified: this.emailVerified, displayName: this.displayName, photoURL: this.photoURL, phoneNumber: this.phoneNumber, disabled: this.disabled, // Convert metadata to json. metadata: this.metadata.toJSON(), passwordHash: this.passwordHash, passwordSalt: this.passwordSalt, customClaims: (0, deep_copy_1.deepCopy)(this.customClaims), tokensValidAfterTime: this.tokensValidAfterTime, tenantId: this.tenantId, }; if (this.multiFactor) { json.multiFactor = this.multiFactor.toJSON(); } json.providerData = []; for (const entry of this.providerData) { // Convert each provider data to json. json.providerData.push(entry.toJSON()); } return json; } } exports.UserRecord = UserRecord;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/app-metadata.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/app-metadata.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.AppPlatform = void 0; /** * Platforms with which a Firebase App can be associated. */ var AppPlatform; (function (AppPlatform) { /** * Unknown state. This is only used for distinguishing unset values. */ AppPlatform["PLATFORM_UNKNOWN"] = "PLATFORM_UNKNOWN"; /** * The Firebase App is associated with iOS. */ AppPlatform["IOS"] = "IOS"; /** * The Firebase App is associated with Android. */ AppPlatform["ANDROID"] = "ANDROID"; })(AppPlatform = exports.AppPlatform || (exports.AppPlatform = {}));
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/project-management-api-request-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ProjectManagementRequestHandler = exports.assertServerResponse = void 0; const api_request_1 = require("../utils/api-request"); const error_1 = require("../utils/error"); const index_1 = require("../utils/index"); const validator = require("../utils/validator"); /** Project management backend host and port. */ const PROJECT_MANAGEMENT_HOST_AND_PORT = 'firebase.googleapis.com:443'; /** Project management backend path. */ const PROJECT_MANAGEMENT_PATH = '/v1/'; /** Project management beta backend path. */ const PROJECT_MANAGEMENT_BETA_PATH = '/v1beta1/'; /** Project management request header. */ const PROJECT_MANAGEMENT_HEADERS = { 'X-Client-Version': `Node/Admin/${(0, index_1.getSdkVersion)()}`, }; /** Project management request timeout duration in milliseconds. */ const PROJECT_MANAGEMENT_TIMEOUT_MILLIS = 10000; const LIST_APPS_MAX_PAGE_SIZE = 100; const CERT_TYPE_API_MAP = { sha1: 'SHA_1', sha256: 'SHA_256', }; function assertServerResponse(condition, responseData, message) { if (!condition) { throw new error_1.FirebaseProjectManagementError('invalid-server-response', `${message} Response data: ${JSON.stringify(responseData, null, 2)}`); } } exports.assertServerResponse = assertServerResponse; /** * Class that provides mechanism to send requests to the Firebase project management backend * endpoints. * * @internal */ class ProjectManagementRequestHandler { /** * @param app - The app used to fetch access tokens to sign API requests. * @constructor */ constructor(app) { this.baseUrl = `https://${PROJECT_MANAGEMENT_HOST_AND_PORT}${PROJECT_MANAGEMENT_PATH}`; this.baseBetaUrl = `https://${PROJECT_MANAGEMENT_HOST_AND_PORT}${PROJECT_MANAGEMENT_BETA_PATH}`; this.httpClient = new api_request_1.AuthorizedHttpClient(app); } static wrapAndRethrowHttpError(errStatusCode, errText) { let errorCode; let errorMessage; switch (errStatusCode) { case 400: errorCode = 'invalid-argument'; errorMessage = 'Invalid argument provided.'; break; case 401: case 403: errorCode = 'authentication-error'; errorMessage = 'An error occurred when trying to authenticate. Make sure the credential ' + 'used to authenticate this SDK has the proper permissions. See ' + 'https://firebase.google.com/docs/admin/setup for setup instructions.'; break; case 404: errorCode = 'not-found'; errorMessage = 'The specified entity could not be found.'; break; case 409: errorCode = 'already-exists'; errorMessage = 'The specified entity already exists.'; break; case 500: errorCode = 'internal-error'; errorMessage = 'An internal error has occurred. Please retry the request.'; break; case 503: errorCode = 'service-unavailable'; errorMessage = 'The server could not process the request in time. See the error ' + 'documentation for more details.'; break; default: errorCode = 'unknown-error'; errorMessage = 'An unknown server error was returned.'; } if (!errText) { errText = '<missing>'; } throw new error_1.FirebaseProjectManagementError(errorCode, `${errorMessage} Status code: ${errStatusCode}. Raw server response: "${errText}".`); } /** * @param parentResourceName - Fully-qualified resource name of the project whose Android * apps you want to list. */ listAndroidApps(parentResourceName) { return this.invokeRequestHandler('GET', `${parentResourceName}/androidApps?page_size=${LIST_APPS_MAX_PAGE_SIZE}`, /* requestData */ null, 'v1beta1'); } /** * @param parentResourceName - Fully-qualified resource name of the project whose iOS apps * you want to list. */ listIosApps(parentResourceName) { return this.invokeRequestHandler('GET', `${parentResourceName}/iosApps?page_size=${LIST_APPS_MAX_PAGE_SIZE}`, /* requestData */ null, 'v1beta1'); } /** * @param parentResourceName - Fully-qualified resource name of the project whose iOS apps * you want to list. */ listAppMetadata(parentResourceName) { return this.invokeRequestHandler('GET', `${parentResourceName}:searchApps?page_size=${LIST_APPS_MAX_PAGE_SIZE}`, /* requestData */ null, 'v1beta1'); } /** * @param parentResourceName - Fully-qualified resource name of the project that you want * to create the Android app within. */ createAndroidApp(parentResourceName, packageName, displayName) { const requestData = { packageName, }; if (validator.isNonEmptyString(displayName)) { requestData.displayName = displayName; } return this .invokeRequestHandler('POST', `${parentResourceName}/androidApps`, requestData, 'v1beta1') .then((responseData) => { assertServerResponse(validator.isNonNullObject(responseData), responseData, 'createAndroidApp\'s responseData must be a non-null object.'); assertServerResponse(validator.isNonEmptyString(responseData.name), responseData, 'createAndroidApp\'s responseData.name must be a non-empty string.'); return this.pollRemoteOperationWithExponentialBackoff(responseData.name); }); } /** * @param parentResourceName - Fully-qualified resource name of the project that you want * to create the iOS app within. */ createIosApp(parentResourceName, bundleId, displayName) { const requestData = { bundleId, }; if (validator.isNonEmptyString(displayName)) { requestData.displayName = displayName; } return this .invokeRequestHandler('POST', `${parentResourceName}/iosApps`, requestData, 'v1beta1') .then((responseData) => { assertServerResponse(validator.isNonNullObject(responseData), responseData, 'createIosApp\'s responseData must be a non-null object.'); assertServerResponse(validator.isNonEmptyString(responseData.name), responseData, 'createIosApp\'s responseData.name must be a non-empty string.'); return this.pollRemoteOperationWithExponentialBackoff(responseData.name); }); } /** * @param resourceName - Fully-qualified resource name of the entity whose display name you * want to set. */ setDisplayName(resourceName, newDisplayName) { const requestData = { displayName: newDisplayName, }; return this .invokeRequestHandler('PATCH', `${resourceName}?update_mask=display_name`, requestData, 'v1beta1') .then(() => undefined); } /** * @param parentResourceName - Fully-qualified resource name of the Android app whose SHA * certificates you want to get. */ getAndroidShaCertificates(parentResourceName) { return this.invokeRequestHandler('GET', `${parentResourceName}/sha`, /* requestData */ null, 'v1beta1'); } /** * @param parentResourceName - Fully-qualified resource name of the Android app that you * want to add the given SHA certificate to. */ addAndroidShaCertificate(parentResourceName, certificate) { const requestData = { shaHash: certificate.shaHash, certType: CERT_TYPE_API_MAP[certificate.certType], }; return this .invokeRequestHandler('POST', `${parentResourceName}/sha`, requestData, 'v1beta1') .then(() => undefined); } /** * @param parentResourceName - Fully-qualified resource name of the app whose config you * want to get. */ getConfig(parentResourceName) { return this.invokeRequestHandler('GET', `${parentResourceName}/config`, /* requestData */ null, 'v1beta1'); } /** * @param parentResourceName - Fully-qualified resource name of the entity that you want to * get. */ getResource(parentResourceName) { return this.invokeRequestHandler('GET', parentResourceName, /* requestData */ null, 'v1beta1'); } /** * @param resourceName - Fully-qualified resource name of the entity that you want to * delete. */ deleteResource(resourceName) { return this .invokeRequestHandler('DELETE', resourceName, /* requestData */ null, 'v1beta1') .then(() => undefined); } pollRemoteOperationWithExponentialBackoff(operationResourceName) { const poller = new api_request_1.ExponentialBackoffPoller(); return poller.poll(() => { return this.invokeRequestHandler('GET', operationResourceName, /* requestData */ null) .then((responseData) => { if (responseData.error) { const errStatusCode = responseData.error.code || 500; const errText = responseData.error.message || JSON.stringify(responseData.error); ProjectManagementRequestHandler.wrapAndRethrowHttpError(errStatusCode, errText); } if (!responseData.done) { // Continue polling. return null; } // Polling complete. Resolve with operation response JSON. return responseData.response; }); }); } /** * Invokes the request handler with the provided request data. */ invokeRequestHandler(method, path, requestData, apiVersion = 'v1') { const baseUrlToUse = (apiVersion === 'v1') ? this.baseUrl : this.baseBetaUrl; const request = { method, url: `${baseUrlToUse}${path}`, headers: PROJECT_MANAGEMENT_HEADERS, data: requestData, timeout: PROJECT_MANAGEMENT_TIMEOUT_MILLIS, }; return this.httpClient.send(request) .then((response) => { // Send non-JSON responses to the catch() below, where they will be treated as errors. if (!response.isJson()) { throw new api_request_1.HttpError(response); } return response.data; }) .catch((err) => { if (err instanceof api_request_1.HttpError) { ProjectManagementRequestHandler.wrapAndRethrowHttpError(err.response.status, err.response.text); } throw err; }); } } exports.ProjectManagementRequestHandler = ProjectManagementRequestHandler;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/ios-app.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/ios-app.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.IosApp = void 0; const error_1 = require("../utils/error"); const validator = require("../utils/validator"); const project_management_api_request_internal_1 = require("./project-management-api-request-internal"); const app_metadata_1 = require("./app-metadata"); /** * A reference to a Firebase iOS app. * * Do not call this constructor directly. Instead, use {@link ProjectManagement.iosApp}. */ class IosApp { /** * @internal */ constructor(appId, requestHandler) { this.appId = appId; this.requestHandler = requestHandler; if (!validator.isNonEmptyString(appId)) { throw new error_1.FirebaseProjectManagementError('invalid-argument', 'appId must be a non-empty string.'); } this.resourceName = `projects/-/iosApps/${appId}`; } /** * Retrieves metadata about this iOS app. * * @returns A promise that * resolves to the retrieved metadata about this iOS app. */ getMetadata() { return this.requestHandler.getResource(this.resourceName) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getMetadata()\'s responseData must be a non-null object.'); const requiredFieldsList = ['name', 'appId', 'projectId', 'bundleId']; requiredFieldsList.forEach((requiredField) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData[requiredField]), responseData, `getMetadata()'s responseData.${requiredField} must be a non-empty string.`); }); const metadata = { platform: app_metadata_1.AppPlatform.IOS, resourceName: responseData.name, appId: responseData.appId, displayName: responseData.displayName || null, projectId: responseData.projectId, bundleId: responseData.bundleId, }; return metadata; }); } /** * Sets the optional user-assigned display name of the app. * * @param newDisplayName - The new display name to set. * * @returns A promise that resolves when the display name has * been set. */ setDisplayName(newDisplayName) { return this.requestHandler.setDisplayName(this.resourceName, newDisplayName); } /** * Gets the configuration artifact associated with this app. * * @returns A promise that resolves to the iOS app's Firebase * config file, in UTF-8 string format. This string is typically intended to * be written to a plist file that gets shipped with your iOS app. */ getConfig() { return this.requestHandler.getConfig(this.resourceName) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getConfig()\'s responseData must be a non-null object.'); const base64ConfigFileContents = responseData.configFileContents; (0, project_management_api_request_internal_1.assertServerResponse)(validator.isBase64String(base64ConfigFileContents), responseData, 'getConfig()\'s responseData.configFileContents must be a base64 string.'); return Buffer.from(base64ConfigFileContents, 'base64').toString('utf8'); }); } } exports.IosApp = IosApp;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/project-management.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/project-management.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ProjectManagement = void 0; const error_1 = require("../utils/error"); const utils = require("../utils/index"); const validator = require("../utils/validator"); const android_app_1 = require("./android-app"); const ios_app_1 = require("./ios-app"); const project_management_api_request_internal_1 = require("./project-management-api-request-internal"); const app_metadata_1 = require("./app-metadata"); /** * The Firebase ProjectManagement service interface. */ class ProjectManagement { /** * @param app - The app for this ProjectManagement service. * @constructor * @internal */ constructor(app) { this.app = app; if (!validator.isNonNullObject(app) || !('options' in app)) { throw new error_1.FirebaseProjectManagementError('invalid-argument', 'First argument passed to admin.projectManagement() must be a valid Firebase app ' + 'instance.'); } this.requestHandler = new project_management_api_request_internal_1.ProjectManagementRequestHandler(app); } /** * Lists up to 100 Firebase Android apps associated with this Firebase project. * * @returns The list of Android apps. */ listAndroidApps() { return this.listPlatformApps('android', 'listAndroidApps()'); } /** * Lists up to 100 Firebase iOS apps associated with this Firebase project. * * @returns The list of iOS apps. */ listIosApps() { return this.listPlatformApps('ios', 'listIosApps()'); } /** * Creates an `AndroidApp` object, referencing the specified Android app within * this Firebase project. * * This method does not perform an RPC. * * @param appId - The `appId` of the Android app to reference. * * @returns An `AndroidApp` object that references the specified Firebase Android app. */ androidApp(appId) { return new android_app_1.AndroidApp(appId, this.requestHandler); } /** * Creates an `iOSApp` object, referencing the specified iOS app within * this Firebase project. * * This method does not perform an RPC. * * @param appId - The `appId` of the iOS app to reference. * * @returns An `iOSApp` object that references the specified Firebase iOS app. */ iosApp(appId) { return new ios_app_1.IosApp(appId, this.requestHandler); } /** * Creates a `ShaCertificate` object. * * This method does not perform an RPC. * * @param shaHash - The SHA-1 or SHA-256 hash for this certificate. * * @returns A `ShaCertificate` object contains the specified SHA hash. */ shaCertificate(shaHash) { return new android_app_1.ShaCertificate(shaHash); } /** * Creates a new Firebase Android app associated with this Firebase project. * * @param packageName - The canonical package name of the Android App, * as would appear in the Google Play Developer Console. * @param displayName - An optional user-assigned display name for this * new app. * * @returns A promise that resolves to the newly created Android app. */ createAndroidApp(packageName, displayName) { return this.getResourceName() .then((resourceName) => { return this.requestHandler.createAndroidApp(resourceName, packageName, displayName); }) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'createAndroidApp()\'s responseData must be a non-null object.'); (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData.appId), responseData, '"responseData.appId" field must be present in createAndroidApp()\'s response data.'); return new android_app_1.AndroidApp(responseData.appId, this.requestHandler); }); } /** * Creates a new Firebase iOS app associated with this Firebase project. * * @param bundleId - The iOS app bundle ID to use for this new app. * @param displayName - An optional user-assigned display name for this * new app. * * @returns A promise that resolves to the newly created iOS app. */ createIosApp(bundleId, displayName) { return this.getResourceName() .then((resourceName) => { return this.requestHandler.createIosApp(resourceName, bundleId, displayName); }) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'createIosApp()\'s responseData must be a non-null object.'); (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData.appId), responseData, '"responseData.appId" field must be present in createIosApp()\'s response data.'); return new ios_app_1.IosApp(responseData.appId, this.requestHandler); }); } /** * Lists up to 100 Firebase apps associated with this Firebase project. * * @returns A promise that resolves to the metadata list of the apps. */ listAppMetadata() { return this.getResourceName() .then((resourceName) => { return this.requestHandler.listAppMetadata(resourceName); }) .then((responseData) => { return this.getProjectId() .then((projectId) => { return this.transformResponseToAppMetadata(responseData, projectId); }); }); } /** * Update the display name of this Firebase project. * * @param newDisplayName - The new display name to be updated. * * @returns A promise that resolves when the project display name has been updated. */ setDisplayName(newDisplayName) { return this.getResourceName() .then((resourceName) => { return this.requestHandler.setDisplayName(resourceName, newDisplayName); }); } transformResponseToAppMetadata(responseData, projectId) { this.assertListAppsResponseData(responseData, 'listAppMetadata()'); if (!responseData.apps) { return []; } return responseData.apps.map((appJson) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(appJson.appId), responseData, '"apps[].appId" field must be present in the listAppMetadata() response data.'); (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(appJson.platform), responseData, '"apps[].platform" field must be present in the listAppMetadata() response data.'); const metadata = { appId: appJson.appId, platform: app_metadata_1.AppPlatform[appJson.platform] || app_metadata_1.AppPlatform.PLATFORM_UNKNOWN, projectId, resourceName: appJson.name, }; if (appJson.displayName) { metadata.displayName = appJson.displayName; } return metadata; }); } getResourceName() { return this.getProjectId() .then((projectId) => { return `projects/${projectId}`; }); } getProjectId() { if (this.projectId) { return Promise.resolve(this.projectId); } return utils.findProjectId(this.app) .then((projectId) => { // Assert that a specific project ID was provided within the app. if (!validator.isNonEmptyString(projectId)) { throw new error_1.FirebaseProjectManagementError('invalid-project-id', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + 'environment variable.'); } this.projectId = projectId; return this.projectId; }); } /** * Lists up to 100 Firebase apps for a specified platform, associated with this Firebase project. */ listPlatformApps(platform, callerName) { return this.getResourceName() .then((resourceName) => { return (platform === 'android') ? this.requestHandler.listAndroidApps(resourceName) : this.requestHandler.listIosApps(resourceName); }) .then((responseData) => { this.assertListAppsResponseData(responseData, callerName); if (!responseData.apps) { return []; } return responseData.apps.map((appJson) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(appJson.appId), responseData, `"apps[].appId" field must be present in the ${callerName} response data.`); if (platform === 'android') { return new android_app_1.AndroidApp(appJson.appId, this.requestHandler); } else { return new ios_app_1.IosApp(appJson.appId, this.requestHandler); } }); }); } assertListAppsResponseData(responseData, callerName) { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, `${callerName}'s responseData must be a non-null object.`); if (responseData.apps) { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isArray(responseData.apps), responseData, `"apps" field must be present in the ${callerName} response data.`); } } } exports.ProjectManagement = ProjectManagement;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getProjectManagement = exports.IosApp = exports.ShaCertificate = exports.AndroidApp = exports.ProjectManagement = exports.AppPlatform = void 0; /** * Firebase project management. * * @packageDocumentation */ const app_1 = require("../app"); const project_management_1 = require("./project-management"); var app_metadata_1 = require("./app-metadata"); Object.defineProperty(exports, "AppPlatform", { enumerable: true, get: function () { return app_metadata_1.AppPlatform; } }); var project_management_2 = require("./project-management"); Object.defineProperty(exports, "ProjectManagement", { enumerable: true, get: function () { return project_management_2.ProjectManagement; } }); var android_app_1 = require("./android-app"); Object.defineProperty(exports, "AndroidApp", { enumerable: true, get: function () { return android_app_1.AndroidApp; } }); Object.defineProperty(exports, "ShaCertificate", { enumerable: true, get: function () { return android_app_1.ShaCertificate; } }); var ios_app_1 = require("./ios-app"); Object.defineProperty(exports, "IosApp", { enumerable: true, get: function () { return ios_app_1.IosApp; } }); /** * Gets the {@link ProjectManagement} service for the default app or a given app. * * `getProjectManagement()` can be called with no arguments to access the * default app's `ProjectManagement` service, or as `getProjectManagement(app)` to access * the `ProjectManagement` service associated with a specific app. * * @example * ```javascript * // Get the ProjectManagement service for the default app * const defaultProjectManagement = getProjectManagement(); * ``` * * @example * ```javascript * // Get the ProjectManagement service for a given app * const otherProjectManagement = getProjectManagement(otherApp); * ``` * * @param app - Optional app whose `ProjectManagement` service * to return. If not provided, the default `ProjectManagement` service will * be returned. * * @returns The default `ProjectManagement` service if no app is provided or the * `ProjectManagement` service associated with the provided app. */ function getProjectManagement(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('projectManagement', (app) => new project_management_1.ProjectManagement(app)); } exports.getProjectManagement = getProjectManagement;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/project-management-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/project-management-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/project-management/android-app.js
aws/lti-middleware/node_modules/firebase-admin/lib/project-management/android-app.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ShaCertificate = exports.AndroidApp = void 0; const error_1 = require("../utils/error"); const validator = require("../utils/validator"); const project_management_api_request_internal_1 = require("./project-management-api-request-internal"); const app_metadata_1 = require("./app-metadata"); /** * A reference to a Firebase Android app. * * Do not call this constructor directly. Instead, use {@link ProjectManagement.androidApp}. */ class AndroidApp { /** * @internal */ constructor(appId, requestHandler) { this.appId = appId; this.requestHandler = requestHandler; if (!validator.isNonEmptyString(appId)) { throw new error_1.FirebaseProjectManagementError('invalid-argument', 'appId must be a non-empty string.'); } this.resourceName = `projects/-/androidApps/${appId}`; } /** * Retrieves metadata about this Android app. * * @returns A promise that resolves to the retrieved metadata about this Android app. */ getMetadata() { return this.requestHandler.getResource(this.resourceName) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getMetadata()\'s responseData must be a non-null object.'); const requiredFieldsList = ['name', 'appId', 'projectId', 'packageName']; requiredFieldsList.forEach((requiredField) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(responseData[requiredField]), responseData, `getMetadata()'s responseData.${requiredField} must be a non-empty string.`); }); const metadata = { platform: app_metadata_1.AppPlatform.ANDROID, resourceName: responseData.name, appId: responseData.appId, displayName: responseData.displayName || null, projectId: responseData.projectId, packageName: responseData.packageName, }; return metadata; }); } /** * Sets the optional user-assigned display name of the app. * * @param newDisplayName - The new display name to set. * * @returns A promise that resolves when the display name has been set. */ setDisplayName(newDisplayName) { return this.requestHandler.setDisplayName(this.resourceName, newDisplayName); } /** * Gets the list of SHA certificates associated with this Android app in Firebase. * * @returns The list of SHA-1 and SHA-256 certificates associated with this Android app in * Firebase. */ getShaCertificates() { return this.requestHandler.getAndroidShaCertificates(this.resourceName) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getShaCertificates()\'s responseData must be a non-null object.'); if (!responseData.certificates) { return []; } (0, project_management_api_request_internal_1.assertServerResponse)(validator.isArray(responseData.certificates), responseData, '"certificates" field must be present in the getShaCertificates() response data.'); const requiredFieldsList = ['name', 'shaHash']; return responseData.certificates.map((certificateJson) => { requiredFieldsList.forEach((requiredField) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonEmptyString(certificateJson[requiredField]), responseData, `getShaCertificates()'s responseData.certificates[].${requiredField} must be a ` + 'non-empty string.'); }); return new ShaCertificate(certificateJson.shaHash, certificateJson.name); }); }); } /** * Adds the given SHA certificate to this Android app. * * @param certificateToAdd - The SHA certificate to add. * * @returns A promise that resolves when the given certificate * has been added to the Android app. */ addShaCertificate(certificateToAdd) { return this.requestHandler.addAndroidShaCertificate(this.resourceName, certificateToAdd); } /** * Deletes the specified SHA certificate from this Android app. * * @param certificateToDelete - The SHA certificate to delete. * * @returns A promise that resolves when the specified * certificate has been removed from the Android app. */ deleteShaCertificate(certificateToDelete) { if (!certificateToDelete.resourceName) { throw new error_1.FirebaseProjectManagementError('invalid-argument', 'Specified certificate does not include a resourceName. (Use AndroidApp.getShaCertificates() to retrieve ' + 'certificates with a resourceName.'); } return this.requestHandler.deleteResource(certificateToDelete.resourceName); } /** * Gets the configuration artifact associated with this app. * * @returns A promise that resolves to the Android app's * Firebase config file, in UTF-8 string format. This string is typically * intended to be written to a JSON file that gets shipped with your Android * app. */ getConfig() { return this.requestHandler.getConfig(this.resourceName) .then((responseData) => { (0, project_management_api_request_internal_1.assertServerResponse)(validator.isNonNullObject(responseData), responseData, 'getConfig()\'s responseData must be a non-null object.'); const base64ConfigFileContents = responseData.configFileContents; (0, project_management_api_request_internal_1.assertServerResponse)(validator.isBase64String(base64ConfigFileContents), responseData, 'getConfig()\'s responseData.configFileContents must be a base64 string.'); return Buffer.from(base64ConfigFileContents, 'base64').toString('utf8'); }); } } exports.AndroidApp = AndroidApp; /** * A SHA-1 or SHA-256 certificate. * * Do not call this constructor directly. Instead, use * [`projectManagement.shaCertificate()`](projectManagement.ProjectManagement#shaCertificate). */ class ShaCertificate { /** * Creates a ShaCertificate using the given hash. The ShaCertificate's type (eg. 'sha256') is * automatically determined from the hash itself. * * @param shaHash - The sha256 or sha1 hash for this certificate. * @example * ```javascript * var shaHash = shaCertificate.shaHash; * ``` * @param resourceName - The Firebase resource name for this certificate. This does not need to be * set when creating a new certificate. * @example * ```javascript * var resourceName = shaCertificate.resourceName; * ``` * * @internal */ constructor(shaHash, resourceName) { this.shaHash = shaHash; this.resourceName = resourceName; if (/^[a-fA-F0-9]{40}$/.test(shaHash)) { this.certType = 'sha1'; } else if (/^[a-fA-F0-9]{64}$/.test(shaHash)) { this.certType = 'sha256'; } else { throw new error_1.FirebaseProjectManagementError('invalid-argument', 'shaHash must be either a sha256 hash or a sha1 hash.'); } } } exports.ShaCertificate = ShaCertificate;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/core.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/core.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/credential-factory.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/credential-factory.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.clearGlobalAppDefaultCred = exports.refreshToken = exports.cert = exports.applicationDefault = void 0; const credential_internal_1 = require("./credential-internal"); let globalAppDefaultCred; const globalCertCreds = {}; const globalRefreshTokenCreds = {}; /** * Returns a credential created from the * {@link https://developers.google.com/identity/protocols/application-default-credentials | * Google Application Default Credentials} * that grants admin access to Firebase services. This credential can be used * in the call to {@link firebase-admin.app#initializeApp}. * * Google Application Default Credentials are available on any Google * infrastructure, such as Google App Engine and Google Compute Engine. * * See * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} * for more details. * * @example * ```javascript * initializeApp({ * credential: applicationDefault(), * databaseURL: "https://<DATABASE_NAME>.firebaseio.com" * }); * ``` * * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} * to be used when retrieving access tokens from Google token servers. * * @returns A credential authenticated via Google * Application Default Credentials that can be used to initialize an app. */ function applicationDefault(httpAgent) { if (typeof globalAppDefaultCred === 'undefined') { globalAppDefaultCred = (0, credential_internal_1.getApplicationDefault)(httpAgent); } return globalAppDefaultCred; } exports.applicationDefault = applicationDefault; /** * Returns a credential created from the provided service account that grants * admin access to Firebase services. This credential can be used in the call * to {@link firebase-admin.app#initializeApp}. * * See * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} * for more details. * * @example * ```javascript * // Providing a path to a service account key JSON file * const serviceAccount = require("path/to/serviceAccountKey.json"); * initializeApp({ * credential: cert(serviceAccount), * databaseURL: "https://<DATABASE_NAME>.firebaseio.com" * }); * ``` * * @example * ```javascript * // Providing a service account object inline * initializeApp({ * credential: cert({ * projectId: "<PROJECT_ID>", * clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com", * privateKey: "-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n" * }), * databaseURL: "https://<DATABASE_NAME>.firebaseio.com" * }); * ``` * * @param serviceAccountPathOrObject - The path to a service * account key JSON file or an object representing a service account key. * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} * to be used when retrieving access tokens from Google token servers. * * @returns A credential authenticated via the * provided service account that can be used to initialize an app. */ function cert(serviceAccountPathOrObject, httpAgent) { const stringifiedServiceAccount = JSON.stringify(serviceAccountPathOrObject); if (!(stringifiedServiceAccount in globalCertCreds)) { globalCertCreds[stringifiedServiceAccount] = new credential_internal_1.ServiceAccountCredential(serviceAccountPathOrObject, httpAgent); } return globalCertCreds[stringifiedServiceAccount]; } exports.cert = cert; /** * Returns a credential created from the provided refresh token that grants * admin access to Firebase services. This credential can be used in the call * to {@link firebase-admin.app#initializeApp}. * * See * {@link https://firebase.google.com/docs/admin/setup#initialize_the_sdk | Initialize the SDK} * for more details. * * @example * ```javascript * // Providing a path to a refresh token JSON file * const refreshToken = require("path/to/refreshToken.json"); * initializeApp({ * credential: refreshToken(refreshToken), * databaseURL: "https://<DATABASE_NAME>.firebaseio.com" * }); * ``` * * @param refreshTokenPathOrObject - The path to a Google * OAuth2 refresh token JSON file or an object representing a Google OAuth2 * refresh token. * @param httpAgent - Optional {@link https://nodejs.org/api/http.html#http_class_http_agent | HTTP Agent} * to be used when retrieving access tokens from Google token servers. * * @returns A credential authenticated via the * provided service account that can be used to initialize an app. */ function refreshToken(refreshTokenPathOrObject, httpAgent) { const stringifiedRefreshToken = JSON.stringify(refreshTokenPathOrObject); if (!(stringifiedRefreshToken in globalRefreshTokenCreds)) { globalRefreshTokenCreds[stringifiedRefreshToken] = new credential_internal_1.RefreshTokenCredential(refreshTokenPathOrObject, httpAgent); } return globalRefreshTokenCreds[stringifiedRefreshToken]; } exports.refreshToken = refreshToken; /** * Clears the global ADC cache. Exported for testing. */ function clearGlobalAppDefaultCred() { globalAppDefaultCred = undefined; } exports.clearGlobalAppDefaultCred = clearGlobalAppDefaultCred;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/firebase-app.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/firebase-app.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebaseApp = exports.FirebaseAppInternals = void 0; const credential_internal_1 = require("./credential-internal"); const validator = require("../utils/validator"); const deep_copy_1 = require("../utils/deep-copy"); const error_1 = require("../utils/error"); const TOKEN_EXPIRY_THRESHOLD_MILLIS = 5 * 60 * 1000; /** * Internals of a FirebaseApp instance. */ class FirebaseAppInternals { // eslint-disable-next-line @typescript-eslint/naming-convention constructor(credential_) { this.credential_ = credential_; this.tokenListeners_ = []; } getToken(forceRefresh = false) { if (forceRefresh || this.shouldRefresh()) { return this.refreshToken(); } return Promise.resolve(this.cachedToken_); } getCachedToken() { return this.cachedToken_ || null; } refreshToken() { return Promise.resolve(this.credential_.getAccessToken()) .then((result) => { // Since the developer can provide the credential implementation, we want to weakly verify // the return type until the type is properly exported. if (!validator.isNonNullObject(result) || typeof result.expires_in !== 'number' || typeof result.access_token !== 'string') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, `Invalid access token generated: "${JSON.stringify(result)}". Valid access ` + 'tokens must be an object with the "expires_in" (number) and "access_token" ' + '(string) properties.'); } const token = { accessToken: result.access_token, expirationTime: Date.now() + (result.expires_in * 1000), }; if (!this.cachedToken_ || this.cachedToken_.accessToken !== token.accessToken || this.cachedToken_.expirationTime !== token.expirationTime) { // Update the cache before firing listeners. Listeners may directly query the // cached token state. this.cachedToken_ = token; this.tokenListeners_.forEach((listener) => { listener(token.accessToken); }); } return token; }) .catch((error) => { let errorMessage = (typeof error === 'string') ? error : error.message; errorMessage = 'Credential implementation provided to initializeApp() via the ' + '"credential" property failed to fetch a valid Google OAuth2 access token with the ' + `following error: "${errorMessage}".`; if (errorMessage.indexOf('invalid_grant') !== -1) { errorMessage += ' There are two likely causes: (1) your server time is not properly ' + 'synced or (2) your certificate key file has been revoked. To solve (1), re-sync the ' + 'time on your server. To solve (2), make sure the key ID for your key file is still ' + 'present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If ' + 'not, generate a new key file at ' + 'https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.'; } throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); }); } shouldRefresh() { return !this.cachedToken_ || (this.cachedToken_.expirationTime - Date.now()) <= TOKEN_EXPIRY_THRESHOLD_MILLIS; } /** * Adds a listener that is called each time a token changes. * * @param listener - The listener that will be called with each new token. */ addAuthTokenListener(listener) { this.tokenListeners_.push(listener); if (this.cachedToken_) { listener(this.cachedToken_.accessToken); } } /** * Removes a token listener. * * @param listener - The listener to remove. */ removeAuthTokenListener(listener) { this.tokenListeners_ = this.tokenListeners_.filter((other) => other !== listener); } } exports.FirebaseAppInternals = FirebaseAppInternals; /** * Global context object for a collection of services using a shared authentication state. * * @internal */ class FirebaseApp { constructor(options, name, appStore) { this.appStore = appStore; this.services_ = {}; this.isDeleted_ = false; this.name_ = name; this.options_ = (0, deep_copy_1.deepCopy)(options); if (!validator.isNonNullObject(this.options_)) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Invalid Firebase app options passed as the first argument to initializeApp() for the ' + `app named "${this.name_}". Options must be a non-null object.`); } const hasCredential = ('credential' in this.options_); if (!hasCredential) { this.options_.credential = (0, credential_internal_1.getApplicationDefault)(this.options_.httpAgent); } const credential = this.options_.credential; if (typeof credential !== 'object' || credential === null || typeof credential.getAccessToken !== 'function') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Invalid Firebase app options passed as the first argument to initializeApp() for the ' + `app named "${this.name_}". The "credential" property must be an object which implements ` + 'the Credential interface.'); } this.INTERNAL = new FirebaseAppInternals(credential); } /** * Returns the name of the FirebaseApp instance. * * @returns The name of the FirebaseApp instance. */ get name() { this.checkDestroyed_(); return this.name_; } /** * Returns the options for the FirebaseApp instance. * * @returns The options for the FirebaseApp instance. */ get options() { this.checkDestroyed_(); return (0, deep_copy_1.deepCopy)(this.options_); } /** * @internal */ getOrInitService(name, init) { return this.ensureService_(name, () => init(this)); } /** * Deletes the FirebaseApp instance. * * @returns An empty Promise fulfilled once the FirebaseApp instance is deleted. */ delete() { this.checkDestroyed_(); // Also remove the instance from the AppStore. This is needed to support the existing // app.delete() use case. In the future we can remove this API, and deleteApp() will // become the only way to tear down an App. this.appStore?.removeApp(this.name); return Promise.all(Object.keys(this.services_).map((serviceName) => { const service = this.services_[serviceName]; if (isStateful(service)) { return service.delete(); } return Promise.resolve(); })).then(() => { this.services_ = {}; this.isDeleted_ = true; }); } // eslint-disable-next-line @typescript-eslint/naming-convention ensureService_(serviceName, initializer) { this.checkDestroyed_(); if (!(serviceName in this.services_)) { this.services_[serviceName] = initializer(); } return this.services_[serviceName]; } /** * Throws an Error if the FirebaseApp instance has already been deleted. */ // eslint-disable-next-line @typescript-eslint/naming-convention checkDestroyed_() { if (this.isDeleted_) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.APP_DELETED, `Firebase app named "${this.name_}" has already been deleted.`); } } } exports.FirebaseApp = FirebaseApp; function isStateful(service) { return typeof service.delete === 'function'; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.SDK_VERSION = exports.refreshToken = exports.cert = exports.applicationDefault = exports.deleteApp = exports.getApps = exports.getApp = exports.initializeApp = void 0; const utils_1 = require("../utils"); var lifecycle_1 = require("./lifecycle"); Object.defineProperty(exports, "initializeApp", { enumerable: true, get: function () { return lifecycle_1.initializeApp; } }); Object.defineProperty(exports, "getApp", { enumerable: true, get: function () { return lifecycle_1.getApp; } }); Object.defineProperty(exports, "getApps", { enumerable: true, get: function () { return lifecycle_1.getApps; } }); Object.defineProperty(exports, "deleteApp", { enumerable: true, get: function () { return lifecycle_1.deleteApp; } }); var credential_factory_1 = require("./credential-factory"); Object.defineProperty(exports, "applicationDefault", { enumerable: true, get: function () { return credential_factory_1.applicationDefault; } }); Object.defineProperty(exports, "cert", { enumerable: true, get: function () { return credential_factory_1.cert; } }); Object.defineProperty(exports, "refreshToken", { enumerable: true, get: function () { return credential_factory_1.refreshToken; } }); exports.SDK_VERSION = (0, utils_1.getSdkVersion)();
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/credential-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/credential-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getApplicationDefault = exports.isApplicationDefault = exports.RefreshTokenCredential = exports.ComputeEngineCredential = exports.ServiceAccountCredential = void 0; const fs = require("fs"); const os = require("os"); const path = require("path"); const error_1 = require("../utils/error"); const api_request_1 = require("../utils/api-request"); const util = require("../utils/validator"); const GOOGLE_TOKEN_AUDIENCE = 'https://accounts.google.com/o/oauth2/token'; const GOOGLE_AUTH_TOKEN_HOST = 'accounts.google.com'; const GOOGLE_AUTH_TOKEN_PATH = '/o/oauth2/token'; // NOTE: the Google Metadata Service uses HTTP over a vlan const GOOGLE_METADATA_SERVICE_HOST = 'metadata.google.internal'; const GOOGLE_METADATA_SERVICE_TOKEN_PATH = '/computeMetadata/v1/instance/service-accounts/default/token'; const GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH = '/computeMetadata/v1/project/project-id'; const GOOGLE_METADATA_SERVICE_ACCOUNT_ID_PATH = '/computeMetadata/v1/instance/service-accounts/default/email'; const configDir = (() => { // Windows has a dedicated low-rights location for apps at ~/Application Data const sys = os.platform(); if (sys && sys.length >= 3 && sys.substring(0, 3).toLowerCase() === 'win') { return process.env.APPDATA; } // On *nix the gcloud cli creates a . dir. return process.env.HOME && path.resolve(process.env.HOME, '.config'); })(); const GCLOUD_CREDENTIAL_SUFFIX = 'gcloud/application_default_credentials.json'; const GCLOUD_CREDENTIAL_PATH = configDir && path.resolve(configDir, GCLOUD_CREDENTIAL_SUFFIX); const REFRESH_TOKEN_HOST = 'www.googleapis.com'; const REFRESH_TOKEN_PATH = '/oauth2/v4/token'; const ONE_HOUR_IN_SECONDS = 60 * 60; const JWT_ALGORITHM = 'RS256'; /** * Implementation of Credential that uses a service account. */ class ServiceAccountCredential { /** * Creates a new ServiceAccountCredential from the given parameters. * * @param serviceAccountPathOrObject - Service account json object or path to a service account json file. * @param httpAgent - Optional http.Agent to use when calling the remote token server. * @param implicit - An optinal boolean indicating whether this credential was implicitly discovered from the * environment, as opposed to being explicitly specified by the developer. * * @constructor */ constructor(serviceAccountPathOrObject, httpAgent, implicit = false) { this.httpAgent = httpAgent; this.implicit = implicit; const serviceAccount = (typeof serviceAccountPathOrObject === 'string') ? ServiceAccount.fromPath(serviceAccountPathOrObject) : new ServiceAccount(serviceAccountPathOrObject); this.projectId = serviceAccount.projectId; this.privateKey = serviceAccount.privateKey; this.clientEmail = serviceAccount.clientEmail; this.httpClient = new api_request_1.HttpClient(); } getAccessToken() { const token = this.createAuthJwt_(); const postData = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3A' + 'grant-type%3Ajwt-bearer&assertion=' + token; const request = { method: 'POST', url: `https://${GOOGLE_AUTH_TOKEN_HOST}${GOOGLE_AUTH_TOKEN_PATH}`, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, data: postData, httpAgent: this.httpAgent, }; return requestAccessToken(this.httpClient, request); } // eslint-disable-next-line @typescript-eslint/naming-convention createAuthJwt_() { const claims = { scope: [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/firebase.database', 'https://www.googleapis.com/auth/firebase.messaging', 'https://www.googleapis.com/auth/identitytoolkit', 'https://www.googleapis.com/auth/userinfo.email', ].join(' '), }; // eslint-disable-next-line @typescript-eslint/no-var-requires const jwt = require('jsonwebtoken'); // This method is actually synchronous so we can capture and return the buffer. return jwt.sign(claims, this.privateKey, { audience: GOOGLE_TOKEN_AUDIENCE, expiresIn: ONE_HOUR_IN_SECONDS, issuer: this.clientEmail, algorithm: JWT_ALGORITHM, }); } } exports.ServiceAccountCredential = ServiceAccountCredential; /** * A struct containing the properties necessary to use service account JSON credentials. */ class ServiceAccount { constructor(json) { if (!util.isNonNullObject(json)) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Service account must be an object.'); } copyAttr(this, json, 'projectId', 'project_id'); copyAttr(this, json, 'privateKey', 'private_key'); copyAttr(this, json, 'clientEmail', 'client_email'); let errorMessage; if (!util.isNonEmptyString(this.projectId)) { errorMessage = 'Service account object must contain a string "project_id" property.'; } else if (!util.isNonEmptyString(this.privateKey)) { errorMessage = 'Service account object must contain a string "private_key" property.'; } else if (!util.isNonEmptyString(this.clientEmail)) { errorMessage = 'Service account object must contain a string "client_email" property.'; } if (typeof errorMessage !== 'undefined') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); } // eslint-disable-next-line @typescript-eslint/no-var-requires const forge = require('node-forge'); try { forge.pki.privateKeyFromPem(this.privateKey); } catch (error) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error); } } static fromPath(filePath) { try { return new ServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8'))); } catch (error) { // Throw a nicely formed error message if the file contents cannot be parsed throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse service account json file: ' + error); } } } /** * Implementation of Credential that gets access tokens from the metadata service available * in the Google Cloud Platform. This authenticates the process as the default service account * of an App Engine instance or Google Compute Engine machine. */ class ComputeEngineCredential { constructor(httpAgent) { this.httpClient = new api_request_1.HttpClient(); this.httpAgent = httpAgent; } getAccessToken() { const request = this.buildRequest(GOOGLE_METADATA_SERVICE_TOKEN_PATH); return requestAccessToken(this.httpClient, request); } getProjectId() { if (this.projectId) { return Promise.resolve(this.projectId); } const request = this.buildRequest(GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH); return this.httpClient.send(request) .then((resp) => { this.projectId = resp.text; return this.projectId; }) .catch((err) => { const detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message; throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, `Failed to determine project ID: ${detail}`); }); } getServiceAccountEmail() { if (this.accountId) { return Promise.resolve(this.accountId); } const request = this.buildRequest(GOOGLE_METADATA_SERVICE_ACCOUNT_ID_PATH); return this.httpClient.send(request) .then((resp) => { this.accountId = resp.text; return this.accountId; }) .catch((err) => { const detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message; throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, `Failed to determine service account email: ${detail}`); }); } buildRequest(urlPath) { return { method: 'GET', url: `http://${GOOGLE_METADATA_SERVICE_HOST}${urlPath}`, headers: { 'Metadata-Flavor': 'Google', }, httpAgent: this.httpAgent, }; } } exports.ComputeEngineCredential = ComputeEngineCredential; /** * Implementation of Credential that gets access tokens from refresh tokens. */ class RefreshTokenCredential { /** * Creates a new RefreshTokenCredential from the given parameters. * * @param refreshTokenPathOrObject - Refresh token json object or path to a refresh token * (user credentials) json file. * @param httpAgent - Optional http.Agent to use when calling the remote token server. * @param implicit - An optinal boolean indicating whether this credential was implicitly * discovered from the environment, as opposed to being explicitly specified by the developer. * * @constructor */ constructor(refreshTokenPathOrObject, httpAgent, implicit = false) { this.httpAgent = httpAgent; this.implicit = implicit; this.refreshToken = (typeof refreshTokenPathOrObject === 'string') ? RefreshToken.fromPath(refreshTokenPathOrObject) : new RefreshToken(refreshTokenPathOrObject); this.httpClient = new api_request_1.HttpClient(); } getAccessToken() { const postData = 'client_id=' + this.refreshToken.clientId + '&' + 'client_secret=' + this.refreshToken.clientSecret + '&' + 'refresh_token=' + this.refreshToken.refreshToken + '&' + 'grant_type=refresh_token'; const request = { method: 'POST', url: `https://${REFRESH_TOKEN_HOST}${REFRESH_TOKEN_PATH}`, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, data: postData, httpAgent: this.httpAgent, }; return requestAccessToken(this.httpClient, request); } } exports.RefreshTokenCredential = RefreshTokenCredential; class RefreshToken { constructor(json) { copyAttr(this, json, 'clientId', 'client_id'); copyAttr(this, json, 'clientSecret', 'client_secret'); copyAttr(this, json, 'refreshToken', 'refresh_token'); copyAttr(this, json, 'type', 'type'); let errorMessage; if (!util.isNonEmptyString(this.clientId)) { errorMessage = 'Refresh token must contain a "client_id" property.'; } else if (!util.isNonEmptyString(this.clientSecret)) { errorMessage = 'Refresh token must contain a "client_secret" property.'; } else if (!util.isNonEmptyString(this.refreshToken)) { errorMessage = 'Refresh token must contain a "refresh_token" property.'; } else if (!util.isNonEmptyString(this.type)) { errorMessage = 'Refresh token must contain a "type" property.'; } if (typeof errorMessage !== 'undefined') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage); } } /* * Tries to load a RefreshToken from a path. Throws if the path doesn't exist or the * data at the path is invalid. */ static fromPath(filePath) { try { return new RefreshToken(JSON.parse(fs.readFileSync(filePath, 'utf8'))); } catch (error) { // Throw a nicely formed error message if the file contents cannot be parsed throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse refresh token file: ' + error); } } } /** * Checks if the given credential was loaded via the application default credentials mechanism. This * includes all ComputeEngineCredential instances, and the ServiceAccountCredential and RefreshTokenCredential * instances that were loaded from well-known files or environment variables, rather than being explicitly * instantiated. * * @param credential - The credential instance to check. */ function isApplicationDefault(credential) { return credential instanceof ComputeEngineCredential || (credential instanceof ServiceAccountCredential && credential.implicit) || (credential instanceof RefreshTokenCredential && credential.implicit); } exports.isApplicationDefault = isApplicationDefault; function getApplicationDefault(httpAgent) { if (process.env.GOOGLE_APPLICATION_CREDENTIALS) { return credentialFromFile(process.env.GOOGLE_APPLICATION_CREDENTIALS, httpAgent); } // It is OK to not have this file. If it is present, it must be valid. if (GCLOUD_CREDENTIAL_PATH) { const refreshToken = readCredentialFile(GCLOUD_CREDENTIAL_PATH, true); if (refreshToken) { return new RefreshTokenCredential(refreshToken, httpAgent, true); } } return new ComputeEngineCredential(httpAgent); } exports.getApplicationDefault = getApplicationDefault; /** * Copies the specified property from one object to another. * * If no property exists by the given "key", looks for a property identified by "alt", and copies it instead. * This can be used to implement behaviors such as "copy property myKey or my_key". * * @param to - Target object to copy the property into. * @param from - Source object to copy the property from. * @param key - Name of the property to copy. * @param alt - Alternative name of the property to copy. */ function copyAttr(to, from, key, alt) { const tmp = from[key] || from[alt]; if (typeof tmp !== 'undefined') { to[key] = tmp; } } /** * Obtain a new OAuth2 token by making a remote service call. */ function requestAccessToken(client, request) { return client.send(request).then((resp) => { const json = resp.data; if (!json.access_token || !json.expires_in) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, `Unexpected response while fetching access token: ${JSON.stringify(json)}`); } return json; }).catch((err) => { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, getErrorMessage(err)); }); } /** * Constructs a human-readable error message from the given Error. */ function getErrorMessage(err) { const detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message; return `Error fetching access token: ${detail}`; } /** * Extracts details from the given HTTP error response, and returns a human-readable description. If * the response is JSON-formatted, looks up the error and error_description fields sent by the * Google Auth servers. Otherwise returns the entire response payload as the error detail. */ function getDetailFromResponse(response) { if (response.isJson() && response.data.error) { const json = response.data; let detail = json.error; if (json.error_description) { detail += ' (' + json.error_description + ')'; } return detail; } return response.text || 'Missing error payload'; } function credentialFromFile(filePath, httpAgent) { const credentialsFile = readCredentialFile(filePath); if (typeof credentialsFile !== 'object' || credentialsFile === null) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse contents of the credentials file as an object'); } if (credentialsFile.type === 'service_account') { return new ServiceAccountCredential(credentialsFile, httpAgent, true); } if (credentialsFile.type === 'authorized_user') { return new RefreshTokenCredential(credentialsFile, httpAgent, true); } throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Invalid contents in the credentials file'); } function readCredentialFile(filePath, ignoreMissing) { let fileText; try { fileText = fs.readFileSync(filePath, 'utf8'); } catch (error) { if (ignoreMissing) { return null; } throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, `Failed to read credentials from file ${filePath}: ` + error); } try { return JSON.parse(fileText); } catch (error) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse contents of the credentials file as an object: ' + error); } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/credential.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/credential.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/firebase-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/firebase-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultNamespace = exports.FirebaseNamespace = exports.FirebaseNamespaceInternals = void 0; const lifecycle_1 = require("./lifecycle"); const credential_factory_1 = require("./credential-factory"); const index_1 = require("../utils/index"); /** * Internals of a FirebaseNamespace instance. */ class FirebaseNamespaceInternals { constructor(appStore) { this.appStore = appStore; } /** * Initializes the App instance. * * @param options - Optional options for the App instance. If none present will try to initialize * from the FIREBASE_CONFIG environment variable. If the environment variable contains a string * that starts with '{' it will be parsed as JSON, otherwise it will be assumed to be pointing * to a file. * @param appName - Optional name of the FirebaseApp instance. * * @returns A new App instance. */ initializeApp(options, appName) { const app = this.appStore.initializeApp(options, appName); return extendApp(app); } /** * Returns the App instance with the provided name (or the default App instance * if no name is provided). * * @param appName - Optional name of the FirebaseApp instance to return. * @returns The App instance which has the provided name. */ app(appName) { const app = this.appStore.getApp(appName); return extendApp(app); } /* * Returns an array of all the non-deleted App instances. */ get apps() { return this.appStore.getApps().map((app) => extendApp(app)); } } exports.FirebaseNamespaceInternals = FirebaseNamespaceInternals; const firebaseCredential = { cert: credential_factory_1.cert, refreshToken: credential_factory_1.refreshToken, applicationDefault: credential_factory_1.applicationDefault }; /** * Global Firebase context object. */ class FirebaseNamespace { /* tslint:enable */ constructor(appStore) { // Hack to prevent Babel from modifying the object returned as the default admin namespace. /* tslint:disable:variable-name */ this.__esModule = true; /* tslint:enable:variable-name */ this.credential = firebaseCredential; this.SDK_VERSION = (0, index_1.getSdkVersion)(); /* tslint:disable */ // TODO(jwenger): Database is the only consumer of firebase.Promise. We should update it to use // use the native Promise and then remove this. this.Promise = Promise; this.INTERNAL = new FirebaseNamespaceInternals(appStore ?? new lifecycle_1.AppStore()); } /** * Gets the `Auth` service namespace. The returned namespace can be used to get the * `Auth` service for the default app or an explicitly specified app. */ get auth() { const fn = (app) => { return this.ensureApp(app).auth(); }; const auth = require('../auth/auth').Auth; return Object.assign(fn, { Auth: auth }); } /** * Gets the `Database` service namespace. The returned namespace can be used to get the * `Database` service for the default app or an explicitly specified app. */ get database() { const fn = (app) => { return this.ensureApp(app).database(); }; // eslint-disable-next-line @typescript-eslint/no-var-requires return Object.assign(fn, require('@firebase/database-compat/standalone')); } /** * Gets the `Messaging` service namespace. The returned namespace can be used to get the * `Messaging` service for the default app or an explicitly specified app. */ get messaging() { const fn = (app) => { return this.ensureApp(app).messaging(); }; const messaging = require('../messaging/messaging').Messaging; return Object.assign(fn, { Messaging: messaging }); } /** * Gets the `Storage` service namespace. The returned namespace can be used to get the * `Storage` service for the default app or an explicitly specified app. */ get storage() { const fn = (app) => { return this.ensureApp(app).storage(); }; const storage = require('../storage/storage').Storage; return Object.assign(fn, { Storage: storage }); } /** * Gets the `Firestore` service namespace. The returned namespace can be used to get the * `Firestore` service for the default app or an explicitly specified app. */ get firestore() { let fn = (app) => { return this.ensureApp(app).firestore(); }; // eslint-disable-next-line @typescript-eslint/no-var-requires const firestore = require('@google-cloud/firestore'); fn = Object.assign(fn, firestore.Firestore); // `v1beta1` and `v1` are lazy-loaded in the Firestore SDK. We use the same trick here // to avoid triggering this lazy-loading upon initialization. Object.defineProperty(fn, 'v1beta1', { get: () => { return firestore.v1beta1; }, }); Object.defineProperty(fn, 'v1', { get: () => { return firestore.v1; }, }); return fn; } /** * Gets the `MachineLearning` service namespace. The returned namespace can be * used to get the `MachineLearning` service for the default app or an * explicityly specified app. */ get machineLearning() { const fn = (app) => { return this.ensureApp(app).machineLearning(); }; const machineLearning = require('../machine-learning/machine-learning').MachineLearning; return Object.assign(fn, { MachineLearning: machineLearning }); } /** * Gets the `Installations` service namespace. The returned namespace can be used to get the * `Installations` service for the default app or an explicitly specified app. */ get installations() { const fn = (app) => { return this.ensureApp(app).installations(); }; const installations = require('../installations/installations').Installations; return Object.assign(fn, { Installations: installations }); } /** * Gets the `InstanceId` service namespace. The returned namespace can be used to get the * `Instance` service for the default app or an explicitly specified app. */ get instanceId() { const fn = (app) => { return this.ensureApp(app).instanceId(); }; const instanceId = require('../instance-id/instance-id').InstanceId; return Object.assign(fn, { InstanceId: instanceId }); } /** * Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the * `ProjectManagement` service for the default app or an explicitly specified app. */ get projectManagement() { const fn = (app) => { return this.ensureApp(app).projectManagement(); }; const projectManagement = require('../project-management/project-management').ProjectManagement; return Object.assign(fn, { ProjectManagement: projectManagement }); } /** * Gets the `SecurityRules` service namespace. The returned namespace can be used to get the * `SecurityRules` service for the default app or an explicitly specified app. */ get securityRules() { const fn = (app) => { return this.ensureApp(app).securityRules(); }; const securityRules = require('../security-rules/security-rules').SecurityRules; return Object.assign(fn, { SecurityRules: securityRules }); } /** * Gets the `RemoteConfig` service namespace. The returned namespace can be used to get the * `RemoteConfig` service for the default app or an explicitly specified app. */ get remoteConfig() { const fn = (app) => { return this.ensureApp(app).remoteConfig(); }; const remoteConfig = require('../remote-config/remote-config').RemoteConfig; return Object.assign(fn, { RemoteConfig: remoteConfig }); } /** * Gets the `AppCheck` service namespace. The returned namespace can be used to get the * `AppCheck` service for the default app or an explicitly specified app. */ get appCheck() { const fn = (app) => { return this.ensureApp(app).appCheck(); }; const appCheck = require('../app-check/app-check').AppCheck; return Object.assign(fn, { AppCheck: appCheck }); } // TODO: Change the return types to app.App in the following methods. /** * Initializes the FirebaseApp instance. * * @param options - Optional options for the FirebaseApp instance. * If none present will try to initialize from the FIREBASE_CONFIG environment variable. * If the environment variable contains a string that starts with '{' it will be parsed as JSON, * otherwise it will be assumed to be pointing to a file. * @param appName - Optional name of the FirebaseApp instance. * * @returns A new FirebaseApp instance. */ initializeApp(options, appName) { return this.INTERNAL.initializeApp(options, appName); } /** * Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance * if no name is provided). * * @param appName - Optional name of the FirebaseApp instance to return. * @returns The FirebaseApp instance which has the provided name. */ app(appName) { return this.INTERNAL.app(appName); } /* * Returns an array of all the non-deleted FirebaseApp instances. */ get apps() { return this.INTERNAL.apps; } ensureApp(app) { if (typeof app === 'undefined') { app = this.app(); } return app; } } exports.FirebaseNamespace = FirebaseNamespace; /** * In order to maintain backward compatibility, we instantiate a default namespace instance in * this module, and delegate all app lifecycle operations to it. In a future implementation where * the old admin namespace is no longer supported, we should remove this. * * @internal */ exports.defaultNamespace = new FirebaseNamespace(lifecycle_1.defaultAppStore); function extendApp(app) { const result = app; if (result.__extended) { return result; } result.auth = () => { const fn = require('../auth/index').getAuth; return fn(app); }; result.appCheck = () => { const fn = require('../app-check/index').getAppCheck; return fn(app); }; result.database = (url) => { const fn = require('../database/index').getDatabaseWithUrl; return fn(url, app); }; result.messaging = () => { const fn = require('../messaging/index').getMessaging; return fn(app); }; result.storage = () => { const fn = require('../storage/index').getStorage; return fn(app); }; result.firestore = () => { const fn = require('../firestore/index').getFirestore; return fn(app); }; result.instanceId = () => { const fn = require('../instance-id/index').getInstanceId; return fn(app); }; result.installations = () => { const fn = require('../installations/index').getInstallations; return fn(app); }; result.machineLearning = () => { const fn = require('../machine-learning/index').getMachineLearning; return fn(app); }; result.projectManagement = () => { const fn = require('../project-management/index').getProjectManagement; return fn(app); }; result.securityRules = () => { const fn = require('../security-rules/index').getSecurityRules; return fn(app); }; result.remoteConfig = () => { const fn = require('../remote-config/index').getRemoteConfig; return fn(app); }; result.__extended = true; return result; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app/lifecycle.js
aws/lti-middleware/node_modules/firebase-admin/lib/app/lifecycle.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FIREBASE_CONFIG_VAR = exports.deleteApp = exports.getApps = exports.getApp = exports.initializeApp = exports.defaultAppStore = exports.AppStore = void 0; const fs = require("fs"); const validator = require("../utils/validator"); const error_1 = require("../utils/error"); const credential_internal_1 = require("./credential-internal"); const firebase_app_1 = require("./firebase-app"); const DEFAULT_APP_NAME = '[DEFAULT]'; class AppStore { constructor() { this.appStore = new Map(); } initializeApp(options, appName = DEFAULT_APP_NAME) { if (typeof options === 'undefined') { options = loadOptionsFromEnvVar(); options.credential = (0, credential_internal_1.getApplicationDefault)(); } if (typeof appName !== 'string' || appName === '') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_NAME, `Invalid Firebase app name "${appName}" provided. App name must be a non-empty string.`); } else if (this.appStore.has(appName)) { if (appName === DEFAULT_APP_NAME) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.DUPLICATE_APP, 'The default Firebase app already exists. This means you called initializeApp() ' + 'more than once without providing an app name as the second argument. In most cases ' + 'you only need to call initializeApp() once. But if you do want to initialize ' + 'multiple apps, pass a second argument to initializeApp() to give each app a unique ' + 'name.'); } else { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.DUPLICATE_APP, `Firebase app named "${appName}" already exists. This means you called initializeApp() ` + 'more than once with the same app name as the second argument. Make sure you provide a ' + 'unique name every time you call initializeApp().'); } } const app = new firebase_app_1.FirebaseApp(options, appName, this); this.appStore.set(app.name, app); return app; } getApp(appName = DEFAULT_APP_NAME) { if (typeof appName !== 'string' || appName === '') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_NAME, `Invalid Firebase app name "${appName}" provided. App name must be a non-empty string.`); } else if (!this.appStore.has(appName)) { let errorMessage = (appName === DEFAULT_APP_NAME) ? 'The default Firebase app does not exist. ' : `Firebase app named "${appName}" does not exist. `; errorMessage += 'Make sure you call initializeApp() before using any of the Firebase services.'; throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NO_APP, errorMessage); } return this.appStore.get(appName); } getApps() { // Return a copy so the caller cannot mutate the array return Array.from(this.appStore.values()); } deleteApp(app) { if (typeof app !== 'object' || app === null || !('options' in app)) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'Invalid app argument.'); } // Make sure the given app already exists. const existingApp = getApp(app.name); // Delegate delete operation to the App instance itself. That will also remove the App // instance from the AppStore. return existingApp.delete(); } clearAllApps() { const promises = []; this.getApps().forEach((app) => { promises.push(this.deleteApp(app)); }); return Promise.all(promises).then(); } /** * Removes the specified App instance from the store. This is currently called by the * {@link FirebaseApp.delete} method. Can be removed once the app deletion is handled * entirely by the {@link deleteApp} top-level function. */ removeApp(appName) { this.appStore.delete(appName); } } exports.AppStore = AppStore; exports.defaultAppStore = new AppStore(); function initializeApp(options, appName = DEFAULT_APP_NAME) { return exports.defaultAppStore.initializeApp(options, appName); } exports.initializeApp = initializeApp; function getApp(appName = DEFAULT_APP_NAME) { return exports.defaultAppStore.getApp(appName); } exports.getApp = getApp; function getApps() { return exports.defaultAppStore.getApps(); } exports.getApps = getApps; /** * Renders this given `App` unusable and frees the resources of * all associated services (though it does *not* clean up any backend * resources). When running the SDK locally, this method * must be called to ensure graceful termination of the process. * * @example * ```javascript * deleteApp(app) * .then(function() { * console.log("App deleted successfully"); * }) * .catch(function(error) { * console.log("Error deleting app:", error); * }); * ``` */ function deleteApp(app) { return exports.defaultAppStore.deleteApp(app); } exports.deleteApp = deleteApp; /** * Constant holding the environment variable name with the default config. * If the environment variable contains a string that starts with '{' it will be parsed as JSON, * otherwise it will be assumed to be pointing to a file. */ exports.FIREBASE_CONFIG_VAR = 'FIREBASE_CONFIG'; /** * Parse the file pointed to by the FIREBASE_CONFIG_VAR, if it exists. * Or if the FIREBASE_CONFIG_ENV contains a valid JSON object, parse it directly. * If the environment variable contains a string that starts with '{' it will be parsed as JSON, * otherwise it will be assumed to be pointing to a file. */ function loadOptionsFromEnvVar() { const config = process.env[exports.FIREBASE_CONFIG_VAR]; if (!validator.isNonEmptyString(config)) { return {}; } try { const contents = config.startsWith('{') ? config : fs.readFileSync(config, 'utf8'); return JSON.parse(contents); } catch (error) { // Throw a nicely formed error message if the file contents cannot be parsed throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, 'Failed to parse app options file: ' + error); } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/instance-id/instance-id.js
aws/lti-middleware/node_modules/firebase-admin/lib/instance-id/instance-id.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.InstanceId = void 0; const installations_1 = require("../installations"); const error_1 = require("../utils/error"); const validator = require("../utils/validator"); /** * The `InstanceId` service enables deleting the Firebase instance IDs * associated with Firebase client app instances. * * @deprecated Use {@link firebase-admin.installations#Installations} instead. */ class InstanceId { /** * @param app - The app for this InstanceId service. * @constructor * @internal */ constructor(app) { if (!validator.isNonNullObject(app) || !('options' in app)) { throw new error_1.FirebaseInstanceIdError(error_1.InstanceIdClientErrorCode.INVALID_ARGUMENT, 'First argument passed to instanceId() must be a valid Firebase app instance.'); } this.app_ = app; } /** * Deletes the specified instance ID and the associated data from Firebase. * * Note that Google Analytics for Firebase uses its own form of Instance ID to * keep track of analytics data. Therefore deleting a Firebase Instance ID does * not delete Analytics data. See * {@link https://firebase.google.com/support/privacy/manage-iids#delete_an_instance_id | * Delete an Instance ID} * for more information. * * @param instanceId - The instance ID to be deleted. * * @returns A promise fulfilled when the instance ID is deleted. */ deleteInstanceId(instanceId) { return (0, installations_1.getInstallations)(this.app).deleteInstallation(instanceId) .catch((err) => { if (err instanceof error_1.FirebaseInstallationsError) { let code = err.code.replace('installations/', ''); if (code === error_1.InstallationsClientErrorCode.INVALID_INSTALLATION_ID.code) { code = error_1.InstanceIdClientErrorCode.INVALID_INSTANCE_ID.code; } throw new error_1.FirebaseInstanceIdError({ code, message: err.message }); } throw err; }); } /** * Returns the app associated with this InstanceId instance. * * @returns The app associated with this InstanceId instance. */ get app() { return this.app_; } } exports.InstanceId = InstanceId;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/instance-id/instance-id-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/instance-id/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/instance-id/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getInstanceId = exports.InstanceId = void 0; /** * Firebase Instance ID service. * * @packageDocumentation */ const index_1 = require("../app/index"); const instance_id_1 = require("./instance-id"); Object.defineProperty(exports, "InstanceId", { enumerable: true, get: function () { return instance_id_1.InstanceId; } }); /** * Gets the {@link InstanceId} service for the default app or a given app. * * This API is deprecated. Developers are advised to use the * {@link firebase-admin.installations#getInstallations} * API to delete their instance IDs and Firebase installation IDs. * * `getInstanceId()` can be called with no arguments to access the default * app's `InstanceId` service or as `getInstanceId(app)` to access the * `InstanceId` service associated with a specific app. * * @example * ```javascript * // Get the Instance ID service for the default app * const defaultInstanceId = getInstanceId(); * ``` * * @example * ```javascript * // Get the Instance ID service for a given app * const otherInstanceId = getInstanceId(otherApp); *``` * * This API is deprecated. Developers are advised to use the `admin.installations()` * API to delete their instance IDs and Firebase installation IDs. * * @param app - Optional app whose `InstanceId` service to * return. If not provided, the default `InstanceId` service will be * returned. * * @returns The default `InstanceId` service if * no app is provided or the `InstanceId` service associated with the * provided app. * * @deprecated Use {@link firebase-admin.installations#getInstallations} instead. */ function getInstanceId(app) { if (typeof app === 'undefined') { app = (0, index_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('instanceId', (app) => new instance_id_1.InstanceId(app)); } exports.getInstanceId = getInstanceId;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.js
aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning-utils.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebaseMachineLearningError = void 0; const error_1 = require("../utils/error"); class FirebaseMachineLearningError extends error_1.PrefixedFirebaseError { static fromOperationError(code, message) { switch (code) { case 1: return new FirebaseMachineLearningError('cancelled', message); case 2: return new FirebaseMachineLearningError('unknown-error', message); case 3: return new FirebaseMachineLearningError('invalid-argument', message); case 4: return new FirebaseMachineLearningError('deadline-exceeded', message); case 5: return new FirebaseMachineLearningError('not-found', message); case 6: return new FirebaseMachineLearningError('already-exists', message); case 7: return new FirebaseMachineLearningError('permission-denied', message); case 8: return new FirebaseMachineLearningError('resource-exhausted', message); case 9: return new FirebaseMachineLearningError('failed-precondition', message); case 10: return new FirebaseMachineLearningError('aborted', message); case 11: return new FirebaseMachineLearningError('out-of-range', message); case 13: return new FirebaseMachineLearningError('internal-error', message); case 14: return new FirebaseMachineLearningError('service-unavailable', message); case 15: return new FirebaseMachineLearningError('data-loss', message); case 16: return new FirebaseMachineLearningError('unauthenticated', message); default: return new FirebaseMachineLearningError('unknown-error', message); } } constructor(code, message) { super('machine-learning', code, message); } } exports.FirebaseMachineLearningError = FirebaseMachineLearningError;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning.js
aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Model = exports.MachineLearning = void 0; const index_1 = require("../storage/index"); const error_1 = require("../utils/error"); const validator = require("../utils/validator"); const deep_copy_1 = require("../utils/deep-copy"); const utils = require("../utils"); const machine_learning_api_client_1 = require("./machine-learning-api-client"); const machine_learning_utils_1 = require("./machine-learning-utils"); /** * The Firebase `MachineLearning` service interface. */ class MachineLearning { /** * @param app - The app for this ML service. * @constructor * @internal */ constructor(app) { if (!validator.isNonNullObject(app) || !('options' in app)) { throw new error_1.FirebaseError({ code: 'machine-learning/invalid-argument', message: 'First argument passed to admin.machineLearning() must be a ' + 'valid Firebase app instance.', }); } this.appInternal = app; this.client = new machine_learning_api_client_1.MachineLearningApiClient(app); } /** * The {@link firebase-admin.app#App} associated with the current `MachineLearning` * service instance. */ get app() { return this.appInternal; } /** * Creates a model in the current Firebase project. * * @param model - The model to create. * * @returns A Promise fulfilled with the created model. */ createModel(model) { return this.signUrlIfPresent(model) .then((modelContent) => this.client.createModel(modelContent)) .then((operation) => this.client.handleOperation(operation)) .then((modelResponse) => new Model(modelResponse, this.client)); } /** * Updates a model's metadata or model file. * * @param modelId - The ID of the model to update. * @param model - The model fields to update. * * @returns A Promise fulfilled with the updated model. */ updateModel(modelId, model) { const updateMask = utils.generateUpdateMask(model); return this.signUrlIfPresent(model) .then((modelContent) => this.client.updateModel(modelId, modelContent, updateMask)) .then((operation) => this.client.handleOperation(operation)) .then((modelResponse) => new Model(modelResponse, this.client)); } /** * Publishes a Firebase ML model. * * A published model can be downloaded to client apps. * * @param modelId - The ID of the model to publish. * * @returns A Promise fulfilled with the published model. */ publishModel(modelId) { return this.setPublishStatus(modelId, true); } /** * Unpublishes a Firebase ML model. * * @param modelId - The ID of the model to unpublish. * * @returns A Promise fulfilled with the unpublished model. */ unpublishModel(modelId) { return this.setPublishStatus(modelId, false); } /** * Gets the model specified by the given ID. * * @param modelId - The ID of the model to get. * * @returns A Promise fulfilled with the model object. */ getModel(modelId) { return this.client.getModel(modelId) .then((modelResponse) => new Model(modelResponse, this.client)); } /** * Lists the current project's models. * * @param options - The listing options. * * @returns A promise that * resolves with the current (filtered) list of models and the next page * token. For the last page, an empty list of models and no page token * are returned. */ listModels(options = {}) { return this.client.listModels(options) .then((resp) => { if (!validator.isNonNullObject(resp)) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', `Invalid ListModels response: ${JSON.stringify(resp)}`); } let models = []; if (resp.models) { models = resp.models.map((rs) => new Model(rs, this.client)); } const result = { models }; if (resp.nextPageToken) { result.pageToken = resp.nextPageToken; } return result; }); } /** * Deletes a model from the current project. * * @param modelId - The ID of the model to delete. */ deleteModel(modelId) { return this.client.deleteModel(modelId); } setPublishStatus(modelId, publish) { const updateMask = ['state.published']; const options = { state: { published: publish } }; return this.client.updateModel(modelId, options, updateMask) .then((operation) => this.client.handleOperation(operation)) .then((modelResponse) => new Model(modelResponse, this.client)); } signUrlIfPresent(options) { const modelOptions = (0, deep_copy_1.deepCopy)(options); if ((0, machine_learning_api_client_1.isGcsTfliteModelOptions)(modelOptions)) { return this.signUrl(modelOptions.tfliteModel.gcsTfliteUri) .then((uri) => { modelOptions.tfliteModel.gcsTfliteUri = uri; return modelOptions; }) .catch((err) => { throw new machine_learning_utils_1.FirebaseMachineLearningError('internal-error', `Error during signing upload url: ${err.message}`); }); } return Promise.resolve(modelOptions); } signUrl(unsignedUrl) { const MINUTES_IN_MILLIS = 60 * 1000; const URL_VALID_DURATION = 10 * MINUTES_IN_MILLIS; const gcsRegex = /^gs:\/\/([a-z0-9_.-]{3,63})\/(.+)$/; const matches = gcsRegex.exec(unsignedUrl); if (!matches) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', `Invalid unsigned url: ${unsignedUrl}`); } const bucketName = matches[1]; const blobName = matches[2]; const bucket = (0, index_1.getStorage)(this.app).bucket(bucketName); const blob = bucket.file(blobName); return blob.getSignedUrl({ action: 'read', expires: Date.now() + URL_VALID_DURATION, }).then((signUrl) => signUrl[0]); } } exports.MachineLearning = MachineLearning; /** * A Firebase ML Model output object. */ class Model { /** * @internal */ constructor(model, client) { this.model = Model.validateAndClone(model); this.client = client; } /** The ID of the model. */ get modelId() { return extractModelId(this.model.name); } /** * The model's name. This is the name you use from your app to load the * model. */ get displayName() { return this.model.displayName; } /** * The model's tags, which can be used to group or filter models in list * operations. */ get tags() { return this.model.tags || []; } /** The timestamp of the model's creation. */ get createTime() { return new Date(this.model.createTime).toUTCString(); } /** The timestamp of the model's most recent update. */ get updateTime() { return new Date(this.model.updateTime).toUTCString(); } /** Error message when model validation fails. */ get validationError() { return this.model.state?.validationError?.message; } /** True if the model is published. */ get published() { return this.model.state?.published || false; } /** * The ETag identifier of the current version of the model. This value * changes whenever you update any of the model's properties. */ get etag() { return this.model.etag; } /** * The hash of the model's `tflite` file. This value changes only when * you upload a new TensorFlow Lite model. */ get modelHash() { return this.model.modelHash; } /** Metadata about the model's TensorFlow Lite model file. */ get tfliteModel() { // Make a copy so people can't directly modify the private this.model object. return (0, deep_copy_1.deepCopy)(this.model.tfliteModel); } /** * True if the model is locked by a server-side operation. You can't make * changes to a locked model. See {@link Model.waitForUnlocked}. */ get locked() { return (this.model.activeOperations?.length ?? 0) > 0; } /** * Return the model as a JSON object. */ toJSON() { // We can't just return this.model because it has extra fields and // different formats etc. So we build the expected model object. const jsonModel = { modelId: this.modelId, displayName: this.displayName, tags: this.tags, createTime: this.createTime, updateTime: this.updateTime, published: this.published, etag: this.etag, locked: this.locked, }; // Also add possibly undefined fields if they exist. if (this.validationError) { jsonModel['validationError'] = this.validationError; } if (this.modelHash) { jsonModel['modelHash'] = this.modelHash; } if (this.tfliteModel) { jsonModel['tfliteModel'] = this.tfliteModel; } return jsonModel; } /** * Wait for the model to be unlocked. * * @param maxTimeMillis - The maximum time in milliseconds to wait. * If not specified, a default maximum of 2 minutes is used. * * @returns A promise that resolves when the model is unlocked * or the maximum wait time has passed. */ waitForUnlocked(maxTimeMillis) { if ((this.model.activeOperations?.length ?? 0) > 0) { // The client will always be defined on Models that have activeOperations // because models with active operations came back from the server and // were constructed with a non-empty client. return this.client.handleOperation(this.model.activeOperations[0], { wait: true, maxTimeMillis }) .then((modelResponse) => { this.model = Model.validateAndClone(modelResponse); }); } return Promise.resolve(); } static validateAndClone(model) { if (!validator.isNonNullObject(model) || !validator.isNonEmptyString(model.name) || !validator.isNonEmptyString(model.createTime) || !validator.isNonEmptyString(model.updateTime) || !validator.isNonEmptyString(model.displayName) || !validator.isNonEmptyString(model.etag)) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', `Invalid Model response: ${JSON.stringify(model)}`); } const tmpModel = (0, deep_copy_1.deepCopy)(model); // If tflite Model is specified, it must have a source consisting of // oneof {gcsTfliteUri, automlModel} if (model.tfliteModel && !validator.isNonEmptyString(model.tfliteModel.gcsTfliteUri) && !validator.isNonEmptyString(model.tfliteModel.automlModel)) { // If we have some other source, ignore the whole tfliteModel. delete tmpModel.tfliteModel; } // Remove '@type' field. We don't need it. if (tmpModel['@type']) { delete tmpModel['@type']; } return tmpModel; } } exports.Model = Model; function extractModelId(resourceName) { return resourceName.split('/').pop(); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getMachineLearning = exports.Model = exports.MachineLearning = void 0; /** * Firebase Machine Learning. * * @packageDocumentation */ const app_1 = require("../app"); const machine_learning_1 = require("./machine-learning"); var machine_learning_2 = require("./machine-learning"); Object.defineProperty(exports, "MachineLearning", { enumerable: true, get: function () { return machine_learning_2.MachineLearning; } }); Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return machine_learning_2.Model; } }); /** * Gets the {@link MachineLearning} service for the default app or a given app. * * `getMachineLearning()` can be called with no arguments to access the * default app's `MachineLearning` service or as `getMachineLearning(app)` to access * the `MachineLearning` service associated with a specific app. * * @example * ```javascript * // Get the MachineLearning service for the default app * const defaultMachineLearning = getMachineLearning(); * ``` * * @example * ```javascript * // Get the MachineLearning service for a given app * const otherMachineLearning = getMachineLearning(otherApp); * ``` * * @param app - Optional app whose `MachineLearning` service to * return. If not provided, the default `MachineLearning` service * will be returned. * * @returns The default `MachineLearning` service if no app is provided or the * `MachineLearning` service associated with the provided app. */ function getMachineLearning(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('machineLearning', (app) => new machine_learning_1.MachineLearning(app)); } exports.getMachineLearning = getMachineLearning;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.js
aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning-api-client.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.MachineLearningApiClient = exports.isGcsTfliteModelOptions = void 0; const api_request_1 = require("../utils/api-request"); const error_1 = require("../utils/error"); const utils = require("../utils/index"); const validator = require("../utils/validator"); const machine_learning_utils_1 = require("./machine-learning-utils"); const ML_V1BETA2_API = 'https://firebaseml.googleapis.com/v1beta2'; const FIREBASE_VERSION_HEADER = { 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, }; // Operation polling defaults const POLL_DEFAULT_MAX_TIME_MILLISECONDS = 120000; // Maximum overall 2 minutes const POLL_BASE_WAIT_TIME_MILLISECONDS = 3000; // Start with 3 second delay const POLL_MAX_WAIT_TIME_MILLISECONDS = 30000; // Maximum 30 second delay function isGcsTfliteModelOptions(options) { const gcsUri = options?.tfliteModel?.gcsTfliteUri; return typeof gcsUri !== 'undefined'; } exports.isGcsTfliteModelOptions = isGcsTfliteModelOptions; /** * Class that facilitates sending requests to the Firebase ML backend API. * * @internal */ class MachineLearningApiClient { constructor(app) { this.app = app; if (!validator.isNonNullObject(app) || !('options' in app)) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'First argument passed to admin.machineLearning() must be a valid ' + 'Firebase app instance.'); } this.httpClient = new api_request_1.AuthorizedHttpClient(app); } createModel(model) { if (!validator.isNonNullObject(model) || !validator.isNonEmptyString(model.displayName)) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid model content.'); return Promise.reject(err); } return this.getProjectUrl() .then((url) => { const request = { method: 'POST', url: `${url}/models`, data: model, }; return this.sendRequest(request); }); } updateModel(modelId, model, updateMask) { if (!validator.isNonEmptyString(modelId) || !validator.isNonNullObject(model) || !validator.isNonEmptyArray(updateMask)) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid model or mask content.'); return Promise.reject(err); } return this.getProjectUrl() .then((url) => { const request = { method: 'PATCH', url: `${url}/models/${modelId}?updateMask=${updateMask.join()}`, data: model, }; return this.sendRequest(request); }); } getModel(modelId) { return Promise.resolve() .then(() => { return this.getModelName(modelId); }) .then((modelName) => { return this.getResourceWithShortName(modelName); }); } getOperation(operationName) { return Promise.resolve() .then(() => { return this.getResourceWithFullName(operationName); }); } listModels(options = {}) { if (!validator.isNonNullObject(options)) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid ListModelsOptions'); return Promise.reject(err); } if (typeof options.filter !== 'undefined' && !validator.isNonEmptyString(options.filter)) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid list filter.'); return Promise.reject(err); } if (typeof options.pageSize !== 'undefined') { if (!validator.isNumber(options.pageSize)) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid page size.'); return Promise.reject(err); } if (options.pageSize < 1 || options.pageSize > 100) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Page size must be between 1 and 100.'); return Promise.reject(err); } } if (typeof options.pageToken !== 'undefined' && !validator.isNonEmptyString(options.pageToken)) { const err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Next page token must be a non-empty string.'); return Promise.reject(err); } return this.getProjectUrl() .then((url) => { const request = { method: 'GET', url: `${url}/models`, data: options, }; return this.sendRequest(request); }); } deleteModel(modelId) { return this.getProjectUrl() .then((url) => { const modelName = this.getModelName(modelId); const request = { method: 'DELETE', url: `${url}/${modelName}`, }; return this.sendRequest(request); }); } /** * Handles a Long Running Operation coming back from the server. * * @param op - The operation to handle * @param options - The options for polling */ handleOperation(op, options) { if (op.done) { if (op.response) { return Promise.resolve(op.response); } else if (op.error) { const err = machine_learning_utils_1.FirebaseMachineLearningError.fromOperationError(op.error.code, op.error.message); return Promise.reject(err); } // Done operations must have either a response or an error. throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', 'Invalid operation response.'); } // Operation is not done if (options?.wait) { return this.pollOperationWithExponentialBackoff(op.name, options); } const metadata = op.metadata || {}; const metadataType = metadata['@type'] || ''; if (!metadataType.includes('ModelOperationMetadata')) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', `Unknown Metadata type: ${JSON.stringify(metadata)}`); } return this.getModel(extractModelId(metadata.name)); } // baseWaitMillis and maxWaitMillis should only ever be modified by unit tests to run faster. pollOperationWithExponentialBackoff(opName, options) { const maxTimeMilliseconds = options?.maxTimeMillis ?? POLL_DEFAULT_MAX_TIME_MILLISECONDS; const baseWaitMillis = options?.baseWaitMillis ?? POLL_BASE_WAIT_TIME_MILLISECONDS; const maxWaitMillis = options?.maxWaitMillis ?? POLL_MAX_WAIT_TIME_MILLISECONDS; const poller = new api_request_1.ExponentialBackoffPoller(baseWaitMillis, maxWaitMillis, maxTimeMilliseconds); return poller.poll(() => { return this.getOperation(opName) .then((responseData) => { if (!responseData.done) { return null; } if (responseData.error) { const err = machine_learning_utils_1.FirebaseMachineLearningError.fromOperationError(responseData.error.code, responseData.error.message); throw err; } return responseData.response; }); }); } /** * Gets the specified resource from the ML API. Resource names must be the short names without project * ID prefix (e.g. `models/123456789`). * * @param {string} name Short name of the resource to get. e.g. 'models/12345' * @returns {Promise<T>} A promise that fulfills with the resource. */ getResourceWithShortName(name) { return this.getProjectUrl() .then((url) => { const request = { method: 'GET', url: `${url}/${name}`, }; return this.sendRequest(request); }); } /** * Gets the specified resource from the ML API. Resource names must be the full names including project * number prefix. * @param fullName - Full resource name of the resource to get. e.g. projects/123465/operations/987654 * @returns {Promise<T>} A promise that fulfulls with the resource. */ getResourceWithFullName(fullName) { const request = { method: 'GET', url: `${ML_V1BETA2_API}/${fullName}` }; return this.sendRequest(request); } sendRequest(request) { request.headers = FIREBASE_VERSION_HEADER; return this.httpClient.send(request) .then((resp) => { return resp.data; }) .catch((err) => { throw this.toFirebaseError(err); }); } toFirebaseError(err) { if (err instanceof error_1.PrefixedFirebaseError) { return err; } const response = err.response; if (!response.isJson()) { return new machine_learning_utils_1.FirebaseMachineLearningError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); } const error = response.data.error || {}; let code = 'unknown-error'; if (error.status && error.status in ERROR_CODE_MAPPING) { code = ERROR_CODE_MAPPING[error.status]; } const message = error.message || `Unknown server error: ${response.text}`; return new machine_learning_utils_1.FirebaseMachineLearningError(code, message); } getProjectUrl() { return this.getProjectIdPrefix() .then((projectIdPrefix) => { return `${ML_V1BETA2_API}/${projectIdPrefix}`; }); } getProjectIdPrefix() { if (this.projectIdPrefix) { return Promise.resolve(this.projectIdPrefix); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + 'environment variable.'); } this.projectIdPrefix = `projects/${projectId}`; return this.projectIdPrefix; }); } getModelName(modelId) { if (!validator.isNonEmptyString(modelId)) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Model ID must be a non-empty string.'); } if (modelId.indexOf('/') !== -1) { throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Model ID must not contain any "/" characters.'); } return `models/${modelId}`; } } exports.MachineLearningApiClient = MachineLearningApiClient; const ERROR_CODE_MAPPING = { INVALID_ARGUMENT: 'invalid-argument', NOT_FOUND: 'not-found', RESOURCE_EXHAUSTED: 'resource-exhausted', UNAUTHENTICATED: 'authentication-error', UNKNOWN: 'unknown-error', }; function extractModelId(resourceName) { return resourceName.split('/').pop(); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/machine-learning/machine-learning-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/storage/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/storage/index.js
import mod from "../../storage/index.js"; export const Storage = mod.Storage; export const getStorage = mod.getStorage;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/auth/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/auth/index.js
import mod from "../../auth/index.js"; export const Auth = mod.Auth; export const BaseAuth = mod.BaseAuth; export const MultiFactorInfo = mod.MultiFactorInfo; export const MultiFactorSettings = mod.MultiFactorSettings; export const PhoneMultiFactorInfo = mod.PhoneMultiFactorInfo; export const Tenant = mod.Tenant; export const TenantAwareAuth = mod.TenantAwareAuth; export const TenantManager = mod.TenantManager; export const UserInfo = mod.UserInfo; export const UserMetadata = mod.UserMetadata; export const UserRecord = mod.UserRecord; export const getAuth = mod.getAuth;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/project-management/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/project-management/index.js
import mod from "../../project-management/index.js"; export const AndroidApp = mod.AndroidApp; export const AppPlatform = mod.AppPlatform; export const IosApp = mod.IosApp; export const ProjectManagement = mod.ProjectManagement; export const ShaCertificate = mod.ShaCertificate; export const getProjectManagement = mod.getProjectManagement;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/app/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/app/index.js
import mod from "../../app/index.js"; export const SDK_VERSION = mod.SDK_VERSION; export const applicationDefault = mod.applicationDefault; export const cert = mod.cert; export const deleteApp = mod.deleteApp; export const getApp = mod.getApp; export const getApps = mod.getApps; export const initializeApp = mod.initializeApp; export const refreshToken = mod.refreshToken;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/instance-id/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/instance-id/index.js
import mod from "../../instance-id/index.js"; export const InstanceId = mod.InstanceId; export const getInstanceId = mod.getInstanceId;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/machine-learning/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/machine-learning/index.js
import mod from "../../machine-learning/index.js"; export const MachineLearning = mod.MachineLearning; export const Model = mod.Model; export const getMachineLearning = mod.getMachineLearning;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/installations/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/installations/index.js
import mod from "../../installations/index.js"; export const Installations = mod.Installations; export const getInstallations = mod.getInstallations;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/remote-config/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/remote-config/index.js
import mod from "../../remote-config/index.js"; export const RemoteConfig = mod.RemoteConfig; export const getRemoteConfig = mod.getRemoteConfig;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/messaging/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/messaging/index.js
import mod from "../../messaging/index.js"; export const Messaging = mod.Messaging; export const getMessaging = mod.getMessaging;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/eventarc/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/eventarc/index.js
import mod from "../../eventarc/index.js"; export const Channel = mod.Channel; export const Eventarc = mod.Eventarc; export const getEventarc = mod.getEventarc;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/security-rules/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/security-rules/index.js
import mod from "../../security-rules/index.js"; export const Ruleset = mod.Ruleset; export const RulesetMetadataList = mod.RulesetMetadataList; export const SecurityRules = mod.SecurityRules; export const getSecurityRules = mod.getSecurityRules;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/app-check/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/app-check/index.js
import mod from "../../app-check/index.js"; export const AppCheck = mod.AppCheck; export const getAppCheck = mod.getAppCheck;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/firestore/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/firestore/index.js
import mod from "../../firestore/index.js"; export const BulkWriter = mod.BulkWriter; export const BundleBuilder = mod.BundleBuilder; export const CollectionGroup = mod.CollectionGroup; export const CollectionReference = mod.CollectionReference; export const DocumentReference = mod.DocumentReference; export const DocumentSnapshot = mod.DocumentSnapshot; export const FieldPath = mod.FieldPath; export const FieldValue = mod.FieldValue; export const Firestore = mod.Firestore; export const GeoPoint = mod.GeoPoint; export const GrpcStatus = mod.GrpcStatus; export const Query = mod.Query; export const QueryDocumentSnapshot = mod.QueryDocumentSnapshot; export const QueryPartition = mod.QueryPartition; export const QuerySnapshot = mod.QuerySnapshot; export const Timestamp = mod.Timestamp; export const Transaction = mod.Transaction; export const WriteBatch = mod.WriteBatch; export const WriteResult = mod.WriteResult; export const getFirestore = mod.getFirestore; export const setLogFunction = mod.setLogFunction; export const v1 = mod.v1;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/functions/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/functions/index.js
import mod from "../../functions/index.js"; export const Functions = mod.Functions; export const TaskQueue = mod.TaskQueue; export const getFunctions = mod.getFunctions;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/esm/database/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/esm/database/index.js
import mod from "../../database/index.js"; export const ServerValue = mod.ServerValue; export const enableLogging = mod.enableLogging; export const getDatabase = mod.getDatabase; export const getDatabaseWithUrl = mod.getDatabaseWithUrl;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/installations/installations.js
aws/lti-middleware/node_modules/firebase-admin/lib/installations/installations.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Installations = void 0; const error_1 = require("../utils/error"); const installations_request_handler_1 = require("./installations-request-handler"); const validator = require("../utils/validator"); /** * The `Installations` service for the current app. */ class Installations { /** * @param app - The app for this Installations service. * @constructor * @internal */ constructor(app) { if (!validator.isNonNullObject(app) || !('options' in app)) { throw new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.INVALID_ARGUMENT, 'First argument passed to admin.installations() must be a valid Firebase app instance.'); } this.app_ = app; this.requestHandler = new installations_request_handler_1.FirebaseInstallationsRequestHandler(app); } /** * Deletes the specified installation ID and the associated data from Firebase. * * @param fid - The Firebase installation ID to be deleted. * * @returns A promise fulfilled when the installation ID is deleted. */ deleteInstallation(fid) { return this.requestHandler.deleteInstallation(fid); } /** * Returns the app associated with this Installations instance. * * @returns The app associated with this Installations instance. */ get app() { return this.app_; } } exports.Installations = Installations;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/installations/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/installations/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getInstallations = exports.Installations = void 0; /** * Firebase Instance ID service. * * @packageDocumentation */ const index_1 = require("../app/index"); const installations_1 = require("./installations"); Object.defineProperty(exports, "Installations", { enumerable: true, get: function () { return installations_1.Installations; } }); /** * Gets the {@link Installations} service for the default app or a given app. * * `getInstallations()` can be called with no arguments to access the default * app's `Installations` service or as `getInstallations(app)` to access the * `Installations` service associated with a specific app. * * @example * ```javascript * // Get the Installations service for the default app * const defaultInstallations = getInstallations(); * ``` * * @example * ```javascript * // Get the Installations service for a given app * const otherInstallations = getInstallations(otherApp); *``` * * @param app - Optional app whose `Installations` service to * return. If not provided, the default `Installations` service will be * returned. * * @returns The default `Installations` service if * no app is provided or the `Installations` service associated with the * provided app. */ function getInstallations(app) { if (typeof app === 'undefined') { app = (0, index_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('installations', (app) => new installations_1.Installations(app)); } exports.getInstallations = getInstallations;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/installations/installations-request-handler.js
aws/lti-middleware/node_modules/firebase-admin/lib/installations/installations-request-handler.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebaseInstallationsRequestHandler = void 0; const error_1 = require("../utils/error"); const api_request_1 = require("../utils/api-request"); const utils = require("../utils/index"); const validator = require("../utils/validator"); /** Firebase IID backend host. */ const FIREBASE_IID_HOST = 'console.firebase.google.com'; /** Firebase IID backend path. */ const FIREBASE_IID_PATH = '/v1/'; /** Firebase IID request timeout duration in milliseconds. */ const FIREBASE_IID_TIMEOUT = 10000; /** HTTP error codes raised by the backend server. */ const ERROR_CODES = { 400: 'Malformed installation ID argument.', 401: 'Request not authorized.', 403: 'Project does not match installation ID or the client does not have sufficient privileges.', 404: 'Failed to find the installation ID.', 409: 'Already deleted.', 429: 'Request throttled out by the backend server.', 500: 'Internal server error.', 503: 'Backend servers are over capacity. Try again later.', }; /** * Class that provides mechanism to send requests to the FIS backend endpoints. */ class FirebaseInstallationsRequestHandler { /** * @param app - The app used to fetch access tokens to sign API requests. * * @constructor */ constructor(app) { this.app = app; this.host = FIREBASE_IID_HOST; this.timeout = FIREBASE_IID_TIMEOUT; this.httpClient = new api_request_1.AuthorizedHttpClient(app); } deleteInstallation(fid) { if (!validator.isNonEmptyString(fid)) { return Promise.reject(new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.INVALID_INSTALLATION_ID, 'Installation ID must be a non-empty string.')); } return this.invokeRequestHandler(new api_request_1.ApiSettings(fid, 'DELETE')); } /** * Invokes the request handler based on the API settings object passed. * * @param apiSettings - The API endpoint settings to apply to request and response. * @returns A promise that resolves when the request is complete. */ invokeRequestHandler(apiSettings) { return this.getPathPrefix() .then((path) => { const req = { url: `https://${this.host}${path}${apiSettings.getEndpoint()}`, method: apiSettings.getHttpMethod(), timeout: this.timeout, }; return this.httpClient.send(req); }) .then(() => { // return nothing on success }) .catch((err) => { if (err instanceof api_request_1.HttpError) { const response = err.response; const errorMessage = (response.isJson() && 'error' in response.data) ? response.data.error : response.text; const template = ERROR_CODES[response.status]; const message = template ? `Installation ID "${apiSettings.getEndpoint()}": ${template}` : errorMessage; throw new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.API_ERROR, message); } // In case of timeouts and other network errors, the HttpClient returns a // FirebaseError wrapped in the response. Simply throw it here. throw err; }); } getPathPrefix() { if (this.path) { return Promise.resolve(this.path); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { // Assert for an explicit projct ID (either via AppOptions or the cert itself). throw new error_1.FirebaseInstallationsError(error_1.InstallationsClientErrorCode.INVALID_PROJECT_ID, 'Failed to determine project ID for Installations. Initialize the ' + 'SDK with service account credentials or set project ID as an app option. ' + 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.'); } this.path = FIREBASE_IID_PATH + `project/${projectId}/instanceId/`; return this.path; }); } } exports.FirebaseInstallationsRequestHandler = FirebaseInstallationsRequestHandler;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/installations/installations-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/installations/installations-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/api-request.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/api-request.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ExponentialBackoffPoller = exports.ApiSettings = exports.AuthorizedHttpClient = exports.parseHttpResponse = exports.HttpClient = exports.defaultRetryConfig = exports.HttpError = void 0; const error_1 = require("./error"); const validator = require("./validator"); const http = require("http"); const https = require("https"); const url = require("url"); const events_1 = require("events"); class DefaultHttpResponse { /** * Constructs a new HttpResponse from the given LowLevelResponse. */ constructor(resp) { this.status = resp.status; this.headers = resp.headers; this.text = resp.data; try { if (!resp.data) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'HTTP response missing data.'); } this.parsedData = JSON.parse(resp.data); } catch (err) { this.parsedData = undefined; this.parseError = err; } this.request = `${resp.config.method} ${resp.config.url}`; } get data() { if (this.isJson()) { return this.parsedData; } throw new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, `Error while parsing response data: "${this.parseError.toString()}". Raw server ` + `response: "${this.text}". Status code: "${this.status}". Outgoing ` + `request: "${this.request}."`); } isJson() { return typeof this.parsedData !== 'undefined'; } } /** * Represents a multipart HTTP response. Parts that constitute the response body can be accessed * via the multipart getter. Getters for text and data throw errors. */ class MultipartHttpResponse { constructor(resp) { this.status = resp.status; this.headers = resp.headers; this.multipart = resp.multipart; } get text() { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, 'Unable to parse multipart payload as text'); } get data() { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, 'Unable to parse multipart payload as JSON'); } isJson() { return false; } } class HttpError extends Error { constructor(response) { super(`Server responded with status ${response.status}.`); this.response = response; // Set the prototype so that instanceof checks will work correctly. // See: https://github.com/Microsoft/TypeScript/issues/13965 Object.setPrototypeOf(this, HttpError.prototype); } } exports.HttpError = HttpError; /** * Default retry configuration for HTTP requests. Retries up to 4 times on connection reset and timeout errors * as well as HTTP 503 errors. Exposed as a function to ensure that every HttpClient gets its own RetryConfig * instance. */ function defaultRetryConfig() { return { maxRetries: 4, statusCodes: [503], ioErrorCodes: ['ECONNRESET', 'ETIMEDOUT'], backOffFactor: 0.5, maxDelayInMillis: 60 * 1000, }; } exports.defaultRetryConfig = defaultRetryConfig; /** * Ensures that the given RetryConfig object is valid. * * @param retry - The configuration to be validated. */ function validateRetryConfig(retry) { if (!validator.isNumber(retry.maxRetries) || retry.maxRetries < 0) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'maxRetries must be a non-negative integer'); } if (typeof retry.backOffFactor !== 'undefined') { if (!validator.isNumber(retry.backOffFactor) || retry.backOffFactor < 0) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'backOffFactor must be a non-negative number'); } } if (!validator.isNumber(retry.maxDelayInMillis) || retry.maxDelayInMillis < 0) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'maxDelayInMillis must be a non-negative integer'); } if (typeof retry.statusCodes !== 'undefined' && !validator.isArray(retry.statusCodes)) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'statusCodes must be an array'); } if (typeof retry.ioErrorCodes !== 'undefined' && !validator.isArray(retry.ioErrorCodes)) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_ARGUMENT, 'ioErrorCodes must be an array'); } } class HttpClient { constructor(retry = defaultRetryConfig()) { this.retry = retry; if (this.retry) { validateRetryConfig(this.retry); } } /** * Sends an HTTP request to a remote server. If the server responds with a successful response (2xx), the returned * promise resolves with an HttpResponse. If the server responds with an error (3xx, 4xx, 5xx), the promise rejects * with an HttpError. In case of all other errors, the promise rejects with a FirebaseAppError. If a request fails * due to a low-level network error, transparently retries the request once before rejecting the promise. * * If the request data is specified as an object, it will be serialized into a JSON string. The application/json * content-type header will also be automatically set in this case. For all other payload types, the content-type * header should be explicitly set by the caller. To send a JSON leaf value (e.g. "foo", 5), parse it into JSON, * and pass as a string or a Buffer along with the appropriate content-type header. * * @param config - HTTP request to be sent. * @returns A promise that resolves with the response details. */ send(config) { return this.sendWithRetry(config); } /** * Sends an HTTP request. In the event of an error, retries the HTTP request according to the * RetryConfig set on the HttpClient. * * @param config - HTTP request to be sent. * @param retryAttempts - Number of retries performed up to now. * @returns A promise that resolves with the response details. */ sendWithRetry(config, retryAttempts = 0) { return AsyncHttpCall.invoke(config) .then((resp) => { return this.createHttpResponse(resp); }) .catch((err) => { const [delayMillis, canRetry] = this.getRetryDelayMillis(retryAttempts, err); if (canRetry && this.retry && delayMillis <= this.retry.maxDelayInMillis) { return this.waitForRetry(delayMillis).then(() => { return this.sendWithRetry(config, retryAttempts + 1); }); } if (err.response) { throw new HttpError(this.createHttpResponse(err.response)); } if (err.code === 'ETIMEDOUT') { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_TIMEOUT, `Error while making request: ${err.message}.`); } throw new error_1.FirebaseAppError(error_1.AppErrorCodes.NETWORK_ERROR, `Error while making request: ${err.message}. Error code: ${err.code}`); }); } createHttpResponse(resp) { if (resp.multipart) { return new MultipartHttpResponse(resp); } return new DefaultHttpResponse(resp); } waitForRetry(delayMillis) { if (delayMillis > 0) { return new Promise((resolve) => { setTimeout(resolve, delayMillis); }); } return Promise.resolve(); } /** * Checks if a failed request is eligible for a retry, and if so returns the duration to wait before initiating * the retry. * * @param retryAttempts - Number of retries completed up to now. * @param err - The last encountered error. * @returns A 2-tuple where the 1st element is the duration to wait before another retry, and the * 2nd element is a boolean indicating whether the request is eligible for a retry or not. */ getRetryDelayMillis(retryAttempts, err) { if (!this.isRetryEligible(retryAttempts, err)) { return [0, false]; } const response = err.response; if (response && response.headers['retry-after']) { const delayMillis = this.parseRetryAfterIntoMillis(response.headers['retry-after']); if (delayMillis > 0) { return [delayMillis, true]; } } return [this.backOffDelayMillis(retryAttempts), true]; } isRetryEligible(retryAttempts, err) { if (!this.retry) { return false; } if (retryAttempts >= this.retry.maxRetries) { return false; } if (err.response) { const statusCodes = this.retry.statusCodes || []; return statusCodes.indexOf(err.response.status) !== -1; } if (err.code) { const retryCodes = this.retry.ioErrorCodes || []; return retryCodes.indexOf(err.code) !== -1; } return false; } /** * Parses the Retry-After HTTP header as a milliseconds value. Return value is negative if the Retry-After header * contains an expired timestamp or otherwise malformed. */ parseRetryAfterIntoMillis(retryAfter) { const delaySeconds = parseInt(retryAfter, 10); if (!isNaN(delaySeconds)) { return delaySeconds * 1000; } const date = new Date(retryAfter); if (!isNaN(date.getTime())) { return date.getTime() - Date.now(); } return -1; } backOffDelayMillis(retryAttempts) { if (retryAttempts === 0) { return 0; } if (!this.retry) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Expected this.retry to exist.'); } const backOffFactor = this.retry.backOffFactor || 0; const delayInSeconds = (2 ** retryAttempts) * backOffFactor; return Math.min(delayInSeconds * 1000, this.retry.maxDelayInMillis); } } exports.HttpClient = HttpClient; /** * Parses a full HTTP response message containing both a header and a body. * * @param response - The HTTP response to be parsed. * @param config - The request configuration that resulted in the HTTP response. * @returns An object containing the parsed HTTP status, headers and the body. */ function parseHttpResponse(response, config) { const responseText = validator.isBuffer(response) ? response.toString('utf-8') : response; const endOfHeaderPos = responseText.indexOf('\r\n\r\n'); const headerLines = responseText.substring(0, endOfHeaderPos).split('\r\n'); const statusLine = headerLines[0]; const status = statusLine.trim().split(/\s/)[1]; const headers = {}; headerLines.slice(1).forEach((line) => { const colonPos = line.indexOf(':'); const name = line.substring(0, colonPos).trim().toLowerCase(); const value = line.substring(colonPos + 1).trim(); headers[name] = value; }); let data = responseText.substring(endOfHeaderPos + 4); if (data.endsWith('\n')) { data = data.slice(0, -1); } if (data.endsWith('\r')) { data = data.slice(0, -1); } const lowLevelResponse = { status: parseInt(status, 10), headers, data, config, request: null, }; if (!validator.isNumber(lowLevelResponse.status)) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Malformed HTTP status line.'); } return new DefaultHttpResponse(lowLevelResponse); } exports.parseHttpResponse = parseHttpResponse; /** * A helper class for sending HTTP requests over the wire. This is a wrapper around the standard * http and https packages of Node.js, providing content processing, timeouts and error handling. * It also wraps the callback API of the Node.js standard library in a more flexible Promise API. */ class AsyncHttpCall { constructor(config) { try { this.config = new HttpRequestConfigImpl(config); this.options = this.config.buildRequestOptions(); this.entity = this.config.buildEntity(this.options.headers); this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; this.execute(); }); } catch (err) { this.promise = Promise.reject(this.enhanceError(err, null)); } } /** * Sends an HTTP request based on the provided configuration. */ static invoke(config) { return new AsyncHttpCall(config).promise; } execute() { const transport = this.options.protocol === 'https:' ? https : http; const req = transport.request(this.options, (res) => { this.handleResponse(res, req); }); // Handle errors req.on('error', (err) => { if (req.aborted) { return; } this.enhanceAndReject(err, null, req); }); const timeout = this.config.timeout; const timeoutCallback = () => { req.abort(); this.rejectWithError(`timeout of ${timeout}ms exceeded`, 'ETIMEDOUT', req); }; if (timeout) { // Listen to timeouts and throw an error. req.setTimeout(timeout, timeoutCallback); req.on('socket', (socket) => { socket.setTimeout(timeout, timeoutCallback); }); } // Send the request req.end(this.entity); } handleResponse(res, req) { if (req.aborted) { return; } if (!res.statusCode) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Expected a statusCode on the response from a ClientRequest'); } const response = { status: res.statusCode, headers: res.headers, request: req, data: undefined, config: this.config, }; const boundary = this.getMultipartBoundary(res.headers); const respStream = this.uncompressResponse(res); if (boundary) { this.handleMultipartResponse(response, respStream, boundary); } else { this.handleRegularResponse(response, respStream); } } /** * Extracts multipart boundary from the HTTP header. The content-type header of a multipart * response has the form 'multipart/subtype; boundary=string'. * * If the content-type header does not exist, or does not start with * 'multipart/', then null will be returned. */ getMultipartBoundary(headers) { const contentType = headers['content-type']; if (!contentType || !contentType.startsWith('multipart/')) { return null; } const segments = contentType.split(';'); const emptyObject = {}; const headerParams = segments.slice(1) .map((segment) => segment.trim().split('=')) .reduce((curr, params) => { // Parse key=value pairs in the content-type header into properties of an object. if (params.length === 2) { const keyValuePair = {}; keyValuePair[params[0]] = params[1]; return Object.assign(curr, keyValuePair); } return curr; }, emptyObject); return headerParams.boundary; } uncompressResponse(res) { // Uncompress the response body transparently if required. let respStream = res; const encodings = ['gzip', 'compress', 'deflate']; if (res.headers['content-encoding'] && encodings.indexOf(res.headers['content-encoding']) !== -1) { // Add the unzipper to the body stream processing pipeline. const zlib = require('zlib'); // eslint-disable-line @typescript-eslint/no-var-requires respStream = respStream.pipe(zlib.createUnzip()); // Remove the content-encoding in order to not confuse downstream operations. delete res.headers['content-encoding']; } return respStream; } handleMultipartResponse(response, respStream, boundary) { const busboy = require('@fastify/busboy'); // eslint-disable-line @typescript-eslint/no-var-requires const multipartParser = new busboy.Dicer({ boundary }); const responseBuffer = []; multipartParser.on('part', (part) => { const tempBuffers = []; part.on('data', (partData) => { tempBuffers.push(partData); }); part.on('end', () => { responseBuffer.push(Buffer.concat(tempBuffers)); }); }); multipartParser.on('finish', () => { response.data = undefined; response.multipart = responseBuffer; this.finalizeResponse(response); }); respStream.pipe(multipartParser); } handleRegularResponse(response, respStream) { const responseBuffer = []; respStream.on('data', (chunk) => { responseBuffer.push(chunk); }); respStream.on('error', (err) => { const req = response.request; if (req && req.aborted) { return; } this.enhanceAndReject(err, null, req); }); respStream.on('end', () => { response.data = Buffer.concat(responseBuffer).toString(); this.finalizeResponse(response); }); } /** * Finalizes the current HTTP call in-flight by either resolving or rejecting the associated * promise. In the event of an error, adds additional useful information to the returned error. */ finalizeResponse(response) { if (response.status >= 200 && response.status < 300) { this.resolve(response); } else { this.rejectWithError('Request failed with status code ' + response.status, null, response.request, response); } } /** * Creates a new error from the given message, and enhances it with other information available. * Then the promise associated with this HTTP call is rejected with the resulting error. */ rejectWithError(message, code, request, response) { const error = new Error(message); this.enhanceAndReject(error, code, request, response); } enhanceAndReject(error, code, request, response) { this.reject(this.enhanceError(error, code, request, response)); } /** * Enhances the given error by adding more information to it. Specifically, the HttpRequestConfig, * the underlying request and response will be attached to the error. */ enhanceError(error, code, request, response) { error.config = this.config; if (code) { error.code = code; } error.request = request; error.response = response; return error; } } /** * An adapter class for extracting options and entity data from an HttpRequestConfig. */ class HttpRequestConfigImpl { constructor(config) { this.config = config; } get method() { return this.config.method; } get url() { return this.config.url; } get headers() { return this.config.headers; } get data() { return this.config.data; } get timeout() { return this.config.timeout; } get httpAgent() { return this.config.httpAgent; } buildRequestOptions() { const parsed = this.buildUrl(); const protocol = parsed.protocol; let port = parsed.port; if (!port) { const isHttps = protocol === 'https:'; port = isHttps ? '443' : '80'; } return { protocol, hostname: parsed.hostname, port, path: parsed.path, method: this.method, agent: this.httpAgent, headers: Object.assign({}, this.headers), }; } buildEntity(headers) { let data; if (!this.hasEntity() || !this.isEntityEnclosingRequest()) { return data; } if (validator.isBuffer(this.data)) { data = this.data; } else if (validator.isObject(this.data)) { data = Buffer.from(JSON.stringify(this.data), 'utf-8'); if (typeof headers['content-type'] === 'undefined') { headers['content-type'] = 'application/json;charset=utf-8'; } } else if (validator.isString(this.data)) { data = Buffer.from(this.data, 'utf-8'); } else { throw new Error('Request data must be a string, a Buffer or a json serializable object'); } // Add Content-Length header if data exists. headers['Content-Length'] = data.length.toString(); return data; } buildUrl() { const fullUrl = this.urlWithProtocol(); if (!this.hasEntity() || this.isEntityEnclosingRequest()) { return url.parse(fullUrl); } if (!validator.isObject(this.data)) { throw new Error(`${this.method} requests cannot have a body`); } // Parse URL and append data to query string. const parsedUrl = new url.URL(fullUrl); const dataObj = this.data; for (const key in dataObj) { if (Object.prototype.hasOwnProperty.call(dataObj, key)) { parsedUrl.searchParams.append(key, dataObj[key]); } } return url.parse(parsedUrl.toString()); } urlWithProtocol() { const fullUrl = this.url; if (fullUrl.startsWith('http://') || fullUrl.startsWith('https://')) { return fullUrl; } return `https://${fullUrl}`; } hasEntity() { return !!this.data; } isEntityEnclosingRequest() { // GET and HEAD requests do not support entity (body) in request. return this.method !== 'GET' && this.method !== 'HEAD'; } } class AuthorizedHttpClient extends HttpClient { constructor(app) { super(); this.app = app; } send(request) { return this.getToken().then((token) => { const requestCopy = Object.assign({}, request); requestCopy.headers = Object.assign({}, request.headers); const authHeader = 'Authorization'; requestCopy.headers[authHeader] = `Bearer ${token}`; if (!requestCopy.httpAgent && this.app.options.httpAgent) { requestCopy.httpAgent = this.app.options.httpAgent; } return super.send(requestCopy); }); } getToken() { return this.app.INTERNAL.getToken() .then((accessTokenObj) => { return accessTokenObj.accessToken; }); } } exports.AuthorizedHttpClient = AuthorizedHttpClient; /** * Class that defines all the settings for the backend API endpoint. * * @param endpoint - The Firebase Auth backend endpoint. * @param httpMethod - The http method for that endpoint. * @constructor */ class ApiSettings { constructor(endpoint, httpMethod = 'POST') { this.endpoint = endpoint; this.httpMethod = httpMethod; this.setRequestValidator(null) .setResponseValidator(null); } /** @returns The backend API endpoint. */ getEndpoint() { return this.endpoint; } /** @returns The request HTTP method. */ getHttpMethod() { return this.httpMethod; } /** * @param requestValidator - The request validator. * @returns The current API settings instance. */ setRequestValidator(requestValidator) { const nullFunction = () => undefined; this.requestValidator = requestValidator || nullFunction; return this; } /** @returns The request validator. */ getRequestValidator() { return this.requestValidator; } /** * @param responseValidator - The response validator. * @returns The current API settings instance. */ setResponseValidator(responseValidator) { const nullFunction = () => undefined; this.responseValidator = responseValidator || nullFunction; return this; } /** @returns The response validator. */ getResponseValidator() { return this.responseValidator; } } exports.ApiSettings = ApiSettings; /** * Class used for polling an endpoint with exponential backoff. * * Example usage: * ``` * const poller = new ExponentialBackoffPoller(); * poller * .poll(() => { * return myRequestToPoll() * .then((responseData: any) => { * if (!isValid(responseData)) { * // Continue polling. * return null; * } * * // Polling complete. Resolve promise with final response data. * return responseData; * }); * }) * .then((responseData: any) => { * console.log(`Final response: ${responseData}`); * }); * ``` */ class ExponentialBackoffPoller extends events_1.EventEmitter { constructor(initialPollingDelayMillis = 1000, maxPollingDelayMillis = 10000, masterTimeoutMillis = 60000) { super(); this.initialPollingDelayMillis = initialPollingDelayMillis; this.maxPollingDelayMillis = maxPollingDelayMillis; this.masterTimeoutMillis = masterTimeoutMillis; this.numTries = 0; this.completed = false; } /** * Poll the provided callback with exponential backoff. * * @param callback - The callback to be called for each poll. If the * callback resolves to a falsey value, polling will continue. Otherwise, the truthy * resolution will be used to resolve the promise returned by this method. * @returns A Promise which resolves to the truthy value returned by the provided * callback when polling is complete. */ poll(callback) { if (this.pollCallback) { throw new Error('poll() can only be called once per instance of ExponentialBackoffPoller'); } this.pollCallback = callback; this.on('poll', this.repoll); this.masterTimer = setTimeout(() => { if (this.completed) { return; } this.markCompleted(); this.reject(new Error('ExponentialBackoffPoller deadline exceeded - Master timeout reached')); }, this.masterTimeoutMillis); return new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; this.repoll(); }); } repoll() { this.pollCallback() .then((result) => { if (this.completed) { return; } if (!result) { this.repollTimer = setTimeout(() => this.emit('poll'), this.getPollingDelayMillis()); this.numTries++; return; } this.markCompleted(); this.resolve(result); }) .catch((err) => { if (this.completed) { return; } this.markCompleted(); this.reject(err); }); } getPollingDelayMillis() { const increasedPollingDelay = Math.pow(2, this.numTries) * this.initialPollingDelayMillis; return Math.min(increasedPollingDelay, this.maxPollingDelayMillis); } markCompleted() { this.completed = true; if (this.masterTimer) { clearTimeout(this.masterTimer); } if (this.repollTimer) { clearTimeout(this.repollTimer); } } } exports.ExponentialBackoffPoller = ExponentialBackoffPoller;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/deep-copy.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/deep-copy.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.deepExtend = exports.deepCopy = void 0; /** * Returns a deep copy of an object or array. * * @param value - The object or array to deep copy. * @returns A deep copy of the provided object or array. */ function deepCopy(value) { return deepExtend(undefined, value); } exports.deepCopy = deepCopy; /** * Copies properties from source to target (recursively allows extension of objects and arrays). * Scalar values in the target are over-written. If target is undefined, an object of the * appropriate type will be created (and returned). * * We recursively copy all child properties of plain objects in the source - so that namespace-like * objects are merged. * * Note that the target can be a function, in which case the properties in the source object are * copied onto it as static properties of the function. * * @param target - The value which is being extended. * @param source - The value whose properties are extending the target. * @returns The target value. */ function deepExtend(target, source) { if (!(source instanceof Object)) { return source; } switch (source.constructor) { case Date: { // Treat Dates like scalars; if the target date object had any child // properties - they will be lost! const dateValue = source; return new Date(dateValue.getTime()); } case Object: if (target === undefined) { target = {}; } break; case Array: // Always copy the array source and overwrite the target. target = []; break; default: // Not a plain Object - treat it as a scalar. return source; } for (const prop in source) { if (!Object.prototype.hasOwnProperty.call(source, prop)) { continue; } target[prop] = deepExtend(target[prop], source[prop]); } return target; } exports.deepExtend = deepExtend;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/jwt.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/jwt.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.JwtErrorCode = exports.JwtError = exports.decodeJwt = exports.verifyJwtSignature = exports.EmulatorSignatureVerifier = exports.PublicKeySignatureVerifier = exports.UrlKeyFetcher = exports.JwksFetcher = exports.ALGORITHM_RS256 = void 0; const validator = require("./validator"); const jwt = require("jsonwebtoken"); const jwks = require("jwks-rsa"); const api_request_1 = require("../utils/api-request"); exports.ALGORITHM_RS256 = 'RS256'; // `jsonwebtoken` converts errors from the `getKey` callback to its own `JsonWebTokenError` type // and prefixes the error message with the following. Use the prefix to identify errors thrown // from the key provider callback. // https://github.com/auth0/node-jsonwebtoken/blob/d71e383862fc735991fd2e759181480f066bf138/verify.js#L96 const JWT_CALLBACK_ERROR_PREFIX = 'error in secret or public key callback: '; const NO_MATCHING_KID_ERROR_MESSAGE = 'no-matching-kid-error'; const NO_KID_IN_HEADER_ERROR_MESSAGE = 'no-kid-in-header-error'; const HOUR_IN_SECONDS = 3600; class JwksFetcher { constructor(jwksUrl) { this.publicKeysExpireAt = 0; if (!validator.isURL(jwksUrl)) { throw new Error('The provided JWKS URL is not a valid URL.'); } this.client = jwks({ jwksUri: jwksUrl, cache: false, // disable jwks-rsa LRU cache as the keys are always cached for 6 hours. }); } fetchPublicKeys() { if (this.shouldRefresh()) { return this.refresh(); } return Promise.resolve(this.publicKeys); } shouldRefresh() { return !this.publicKeys || this.publicKeysExpireAt <= Date.now(); } refresh() { return this.client.getSigningKeys() .then((signingKeys) => { // reset expire at from previous set of keys. this.publicKeysExpireAt = 0; const newKeys = signingKeys.reduce((map, signingKey) => { map[signingKey.kid] = signingKey.getPublicKey(); return map; }, {}); this.publicKeysExpireAt = Date.now() + (HOUR_IN_SECONDS * 6 * 1000); this.publicKeys = newKeys; return newKeys; }).catch((err) => { throw new Error(`Error fetching Json Web Keys: ${err.message}`); }); } } exports.JwksFetcher = JwksFetcher; /** * Class to fetch public keys from a client certificates URL. */ class UrlKeyFetcher { constructor(clientCertUrl, httpAgent) { this.clientCertUrl = clientCertUrl; this.httpAgent = httpAgent; this.publicKeysExpireAt = 0; if (!validator.isURL(clientCertUrl)) { throw new Error('The provided public client certificate URL is not a valid URL.'); } } /** * Fetches the public keys for the Google certs. * * @returns A promise fulfilled with public keys for the Google certs. */ fetchPublicKeys() { if (this.shouldRefresh()) { return this.refresh(); } return Promise.resolve(this.publicKeys); } /** * Checks if the cached public keys need to be refreshed. * * @returns Whether the keys should be fetched from the client certs url or not. */ shouldRefresh() { return !this.publicKeys || this.publicKeysExpireAt <= Date.now(); } refresh() { const client = new api_request_1.HttpClient(); const request = { method: 'GET', url: this.clientCertUrl, httpAgent: this.httpAgent, }; return client.send(request).then((resp) => { if (!resp.isJson() || resp.data.error) { // Treat all non-json messages and messages with an 'error' field as // error responses. throw new api_request_1.HttpError(resp); } // reset expire at from previous set of keys. this.publicKeysExpireAt = 0; if (Object.prototype.hasOwnProperty.call(resp.headers, 'cache-control')) { const cacheControlHeader = resp.headers['cache-control']; const parts = cacheControlHeader.split(','); parts.forEach((part) => { const subParts = part.trim().split('='); if (subParts[0] === 'max-age') { const maxAge = +subParts[1]; this.publicKeysExpireAt = Date.now() + (maxAge * 1000); } }); } this.publicKeys = resp.data; return resp.data; }).catch((err) => { if (err instanceof api_request_1.HttpError) { let errorMessage = 'Error fetching public keys for Google certs: '; const resp = err.response; if (resp.isJson() && resp.data.error) { errorMessage += `${resp.data.error}`; if (resp.data.error_description) { errorMessage += ' (' + resp.data.error_description + ')'; } } else { errorMessage += `${resp.text}`; } throw new Error(errorMessage); } throw err; }); } } exports.UrlKeyFetcher = UrlKeyFetcher; /** * Class for verifying JWT signature with a public key. */ class PublicKeySignatureVerifier { constructor(keyFetcher) { this.keyFetcher = keyFetcher; if (!validator.isNonNullObject(keyFetcher)) { throw new Error('The provided key fetcher is not an object or null.'); } } static withCertificateUrl(clientCertUrl, httpAgent) { return new PublicKeySignatureVerifier(new UrlKeyFetcher(clientCertUrl, httpAgent)); } static withJwksUrl(jwksUrl) { return new PublicKeySignatureVerifier(new JwksFetcher(jwksUrl)); } verify(token) { if (!validator.isString(token)) { return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.')); } return verifyJwtSignature(token, getKeyCallback(this.keyFetcher), { algorithms: [exports.ALGORITHM_RS256] }) .catch((error) => { if (error.code === JwtErrorCode.NO_KID_IN_HEADER) { // No kid in JWT header. Try with all the public keys. return this.verifyWithoutKid(token); } throw error; }); } verifyWithoutKid(token) { return this.keyFetcher.fetchPublicKeys() .then(publicKeys => this.verifyWithAllKeys(token, publicKeys)); } verifyWithAllKeys(token, keys) { const promises = []; Object.values(keys).forEach((key) => { const result = verifyJwtSignature(token, key) .then(() => true) .catch((error) => { if (error.code === JwtErrorCode.TOKEN_EXPIRED) { throw error; } return false; }); promises.push(result); }); return Promise.all(promises) .then((result) => { if (result.every((r) => r === false)) { throw new JwtError(JwtErrorCode.INVALID_SIGNATURE, 'Invalid token signature.'); } }); } } exports.PublicKeySignatureVerifier = PublicKeySignatureVerifier; /** * Class for verifying unsigned (emulator) JWTs. */ class EmulatorSignatureVerifier { verify(token) { // Signature checks skipped for emulator; no need to fetch public keys. return verifyJwtSignature(token, ''); } } exports.EmulatorSignatureVerifier = EmulatorSignatureVerifier; /** * Provides a callback to fetch public keys. * * @param fetcher - KeyFetcher to fetch the keys from. * @returns A callback function that can be used to get keys in `jsonwebtoken`. */ function getKeyCallback(fetcher) { return (header, callback) => { if (!header.kid) { callback(new Error(NO_KID_IN_HEADER_ERROR_MESSAGE)); } const kid = header.kid || ''; fetcher.fetchPublicKeys().then((publicKeys) => { if (!Object.prototype.hasOwnProperty.call(publicKeys, kid)) { callback(new Error(NO_MATCHING_KID_ERROR_MESSAGE)); } else { callback(null, publicKeys[kid]); } }) .catch(error => { callback(error); }); }; } /** * Verifies the signature of a JWT using the provided secret or a function to fetch * the secret or public key. * * @param token - The JWT to be verified. * @param secretOrPublicKey - The secret or a function to fetch the secret or public key. * @param options - JWT verification options. * @returns A Promise resolving for a token with a valid signature. */ function verifyJwtSignature(token, secretOrPublicKey, options) { if (!validator.isString(token)) { return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.')); } return new Promise((resolve, reject) => { jwt.verify(token, secretOrPublicKey, options, (error) => { if (!error) { return resolve(); } if (error.name === 'TokenExpiredError') { return reject(new JwtError(JwtErrorCode.TOKEN_EXPIRED, 'The provided token has expired. Get a fresh token from your ' + 'client app and try again.')); } else if (error.name === 'JsonWebTokenError') { if (error.message && error.message.includes(JWT_CALLBACK_ERROR_PREFIX)) { const message = error.message.split(JWT_CALLBACK_ERROR_PREFIX).pop() || 'Error fetching public keys.'; let code = JwtErrorCode.KEY_FETCH_ERROR; if (message === NO_MATCHING_KID_ERROR_MESSAGE) { code = JwtErrorCode.NO_MATCHING_KID; } else if (message === NO_KID_IN_HEADER_ERROR_MESSAGE) { code = JwtErrorCode.NO_KID_IN_HEADER; } return reject(new JwtError(code, message)); } } return reject(new JwtError(JwtErrorCode.INVALID_SIGNATURE, error.message)); }); }); } exports.verifyJwtSignature = verifyJwtSignature; /** * Decodes general purpose Firebase JWTs. * * @param jwtToken - JWT token to be decoded. * @returns Decoded token containing the header and payload. */ function decodeJwt(jwtToken) { if (!validator.isString(jwtToken)) { return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.')); } const fullDecodedToken = jwt.decode(jwtToken, { complete: true, }); if (!fullDecodedToken) { return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'Decoding token failed.')); } const header = fullDecodedToken?.header; const payload = fullDecodedToken?.payload; return Promise.resolve({ header, payload }); } exports.decodeJwt = decodeJwt; /** * Jwt error code structure. * * @param code - The error code. * @param message - The error message. * @constructor */ class JwtError extends Error { constructor(code, message) { super(message); this.code = code; this.message = message; this.__proto__ = JwtError.prototype; } } exports.JwtError = JwtError; /** * JWT error codes. */ var JwtErrorCode; (function (JwtErrorCode) { JwtErrorCode["INVALID_ARGUMENT"] = "invalid-argument"; JwtErrorCode["INVALID_CREDENTIAL"] = "invalid-credential"; JwtErrorCode["TOKEN_EXPIRED"] = "token-expired"; JwtErrorCode["INVALID_SIGNATURE"] = "invalid-token"; JwtErrorCode["NO_MATCHING_KID"] = "no-matching-kid-error"; JwtErrorCode["NO_KID_IN_HEADER"] = "no-kid-error"; JwtErrorCode["KEY_FETCH_ERROR"] = "key-fetch-error"; })(JwtErrorCode = exports.JwtErrorCode || (exports.JwtErrorCode = {}));
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.parseResourceName = exports.transformMillisecondsToSecondsString = exports.generateUpdateMask = exports.formatString = exports.toWebSafeBase64 = exports.findServiceAccountEmail = exports.getExplicitServiceAccountEmail = exports.findProjectId = exports.getExplicitProjectId = exports.addReadonlyGetter = exports.renameProperties = exports.getSdkVersion = void 0; const credential_internal_1 = require("../app/credential-internal"); const validator = require("./validator"); let sdkVersion; // TODO: Move to firebase-admin/app as an internal member. function getSdkVersion() { if (!sdkVersion) { const { version } = require('../../package.json'); // eslint-disable-line @typescript-eslint/no-var-requires sdkVersion = version; } return sdkVersion; } exports.getSdkVersion = getSdkVersion; /** * Renames properties on an object given a mapping from old to new property names. * * For example, this can be used to map underscore_cased properties to camelCase. * * @param obj - The object whose properties to rename. * @param keyMap - The mapping from old to new property names. */ function renameProperties(obj, keyMap) { Object.keys(keyMap).forEach((oldKey) => { if (oldKey in obj) { const newKey = keyMap[oldKey]; // The old key's value takes precedence over the new key's value. obj[newKey] = obj[oldKey]; delete obj[oldKey]; } }); } exports.renameProperties = renameProperties; /** * Defines a new read-only property directly on an object and returns the object. * * @param obj - The object on which to define the property. * @param prop - The name of the property to be defined or modified. * @param value - The value associated with the property. */ function addReadonlyGetter(obj, prop, value) { Object.defineProperty(obj, prop, { value, // Make this property read-only. writable: false, // Include this property during enumeration of obj's properties. enumerable: true, }); } exports.addReadonlyGetter = addReadonlyGetter; /** * Returns the Google Cloud project ID associated with a Firebase app, if it's explicitly * specified in either the Firebase app options, credentials or the local environment. * Otherwise returns null. * * @param app - A Firebase app to get the project ID from. * * @returns A project ID string or null. */ function getExplicitProjectId(app) { const options = app.options; if (validator.isNonEmptyString(options.projectId)) { return options.projectId; } const credential = app.options.credential; if (credential instanceof credential_internal_1.ServiceAccountCredential) { return credential.projectId; } const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT; if (validator.isNonEmptyString(projectId)) { return projectId; } return null; } exports.getExplicitProjectId = getExplicitProjectId; /** * Determines the Google Cloud project ID associated with a Firebase app. This method * first checks if a project ID is explicitly specified in either the Firebase app options, * credentials or the local environment in that order. If no explicit project ID is * configured, but the SDK has been initialized with ComputeEngineCredentials, this * method attempts to discover the project ID from the local metadata service. * * @param app - A Firebase app to get the project ID from. * * @returns A project ID string or null. */ function findProjectId(app) { const projectId = getExplicitProjectId(app); if (projectId) { return Promise.resolve(projectId); } const credential = app.options.credential; if (credential instanceof credential_internal_1.ComputeEngineCredential) { return credential.getProjectId(); } return Promise.resolve(null); } exports.findProjectId = findProjectId; /** * Returns the service account email associated with a Firebase app, if it's explicitly * specified in either the Firebase app options, credentials or the local environment. * Otherwise returns null. * * @param app - A Firebase app to get the service account email from. * * @returns A service account email string or null. */ function getExplicitServiceAccountEmail(app) { const options = app.options; if (validator.isNonEmptyString(options.serviceAccountId)) { return options.serviceAccountId; } const credential = app.options.credential; if (credential instanceof credential_internal_1.ServiceAccountCredential) { return credential.clientEmail; } return null; } exports.getExplicitServiceAccountEmail = getExplicitServiceAccountEmail; /** * Determines the service account email associated with a Firebase app. This method first * checks if a service account email is explicitly specified in either the Firebase app options, * credentials or the local environment in that order. If no explicit service account email is * configured, but the SDK has been initialized with ComputeEngineCredentials, this * method attempts to discover the service account email from the local metadata service. * * @param app - A Firebase app to get the service account email from. * * @returns A service account email ID string or null. */ function findServiceAccountEmail(app) { const accountId = getExplicitServiceAccountEmail(app); if (accountId) { return Promise.resolve(accountId); } const credential = app.options.credential; if (credential instanceof credential_internal_1.ComputeEngineCredential) { return credential.getServiceAccountEmail(); } return Promise.resolve(null); } exports.findServiceAccountEmail = findServiceAccountEmail; /** * Encodes data using web-safe-base64. * * @param data - The raw data byte input. * @returns The base64-encoded result. */ function toWebSafeBase64(data) { return data.toString('base64').replace(/\//g, '_').replace(/\+/g, '-'); } exports.toWebSafeBase64 = toWebSafeBase64; /** * Formats a string of form 'project/{projectId}/{api}' and replaces * with corresponding arguments {projectId: '1234', api: 'resource'} * and returns output: 'project/1234/resource'. * * @param str - The original string where the param need to be * replaced. * @param params - The optional parameters to replace in the * string. * @returns The resulting formatted string. */ function formatString(str, params) { let formatted = str; Object.keys(params || {}).forEach((key) => { formatted = formatted.replace(new RegExp('{' + key + '}', 'g'), params[key]); }); return formatted; } exports.formatString = formatString; /** * Generates the update mask for the provided object. * Note this will ignore the last key with value undefined. * * @param obj - The object to generate the update mask for. * @param terminalPaths - The optional map of keys for maximum paths to traverse. * Nested objects beyond that path will be ignored. This is useful for * keys with variable object values. * @param root - The path so far. * @returns The computed update mask list. */ function generateUpdateMask(obj, terminalPaths = [], root = '') { const updateMask = []; if (!validator.isNonNullObject(obj)) { return updateMask; } for (const key in obj) { if (typeof obj[key] !== 'undefined') { const nextPath = root ? `${root}.${key}` : key; // We hit maximum path. // Consider switching to Set<string> if the list grows too large. if (terminalPaths.indexOf(nextPath) !== -1) { // Add key and stop traversing this branch. updateMask.push(key); } else { const maskList = generateUpdateMask(obj[key], terminalPaths, nextPath); if (maskList.length > 0) { maskList.forEach((mask) => { updateMask.push(`${key}.${mask}`); }); } else { updateMask.push(key); } } } } return updateMask; } exports.generateUpdateMask = generateUpdateMask; /** * Transforms milliseconds to a protobuf Duration type string. * Returns the duration in seconds with up to nine fractional * digits, terminated by 's'. Example: "3 seconds 0 nano seconds as 3s, * 3 seconds 1 nano seconds as 3.000000001s". * * @param milliseconds - The duration in milliseconds. * @returns The resulting formatted string in seconds with up to nine fractional * digits, terminated by 's'. */ function transformMillisecondsToSecondsString(milliseconds) { let duration; const seconds = Math.floor(milliseconds / 1000); const nanos = Math.floor((milliseconds - seconds * 1000) * 1000000); if (nanos > 0) { let nanoString = nanos.toString(); while (nanoString.length < 9) { nanoString = '0' + nanoString; } duration = `${seconds}.${nanoString}s`; } else { duration = `${seconds}s`; } return duration; } exports.transformMillisecondsToSecondsString = transformMillisecondsToSecondsString; /** * Parses the top level resources of a given resource name. * Supports both full and partial resources names, example: * `locations/{location}/functions/{functionName}`, * `projects/{project}/locations/{location}/functions/{functionName}`, or {functionName} * Does not support deeply nested resource names. * * @param resourceName - The resource name string. * @param resourceIdKey - The key of the resource name to be parsed. * @returns A parsed resource name object. */ function parseResourceName(resourceName, resourceIdKey) { if (!resourceName.includes('/')) { return { resourceId: resourceName }; } const CHANNEL_NAME_REGEX = new RegExp(`^(projects/([^/]+)/)?locations/([^/]+)/${resourceIdKey}/([^/]+)$`); const match = CHANNEL_NAME_REGEX.exec(resourceName); if (match === null) { throw new Error('Invalid resource name format.'); } const projectId = match[2]; const locationId = match[3]; const resourceId = match[4]; return { projectId, locationId, resourceId }; } exports.parseResourceName = parseResourceName;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/error.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/error.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.InstanceIdClientErrorCode = exports.InstallationsClientErrorCode = exports.MessagingClientErrorCode = exports.AuthClientErrorCode = exports.AppErrorCodes = exports.FirebaseProjectManagementError = exports.FirebaseMessagingError = exports.FirebaseInstallationsError = exports.FirebaseInstanceIdError = exports.FirebaseFirestoreError = exports.FirebaseDatabaseError = exports.FirebaseAuthError = exports.FirebaseAppError = exports.PrefixedFirebaseError = exports.FirebaseError = void 0; const deep_copy_1 = require("../utils/deep-copy"); /** * Firebase error code structure. This extends Error. * * @param errorInfo - The error information (code and message). * @constructor */ class FirebaseError extends Error { constructor(errorInfo) { super(errorInfo.message); this.errorInfo = errorInfo; /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = FirebaseError.prototype; } /** @returns The error code. */ get code() { return this.errorInfo.code; } /** @returns The error message. */ get message() { return this.errorInfo.message; } /** @returns The object representation of the error. */ toJSON() { return { code: this.code, message: this.message, }; } } exports.FirebaseError = FirebaseError; /** * A FirebaseError with a prefix in front of the error code. * * @param codePrefix - The prefix to apply to the error code. * @param code - The error code. * @param message - The error message. * @constructor */ class PrefixedFirebaseError extends FirebaseError { constructor(codePrefix, code, message) { super({ code: `${codePrefix}/${code}`, message, }); this.codePrefix = codePrefix; /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = PrefixedFirebaseError.prototype; } /** * Allows the error type to be checked without needing to know implementation details * of the code prefixing. * * @param code - The non-prefixed error code to test against. * @returns True if the code matches, false otherwise. */ hasCode(code) { return `${this.codePrefix}/${code}` === this.code; } } exports.PrefixedFirebaseError = PrefixedFirebaseError; /** * Firebase App error code structure. This extends PrefixedFirebaseError. * * @param code - The error code. * @param message - The error message. * @constructor */ class FirebaseAppError extends PrefixedFirebaseError { constructor(code, message) { super('app', code, message); /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = FirebaseAppError.prototype; } } exports.FirebaseAppError = FirebaseAppError; /** * Firebase Auth error code structure. This extends PrefixedFirebaseError. * * @param info - The error code info. * @param [message] The error message. This will override the default * message if provided. * @constructor */ class FirebaseAuthError extends PrefixedFirebaseError { /** * Creates the developer-facing error corresponding to the backend error code. * * @param serverErrorCode - The server error code. * @param [message] The error message. The default message is used * if not provided. * @param [rawServerResponse] The error's raw server response. * @returns The corresponding developer-facing error. */ static fromServerError(serverErrorCode, message, rawServerResponse) { // serverErrorCode could contain additional details: // ERROR_CODE : Detailed message which can also contain colons const colonSeparator = (serverErrorCode || '').indexOf(':'); let customMessage = null; if (colonSeparator !== -1) { customMessage = serverErrorCode.substring(colonSeparator + 1).trim(); serverErrorCode = serverErrorCode.substring(0, colonSeparator).trim(); } // If not found, default to internal error. const clientCodeKey = AUTH_SERVER_TO_CLIENT_CODE[serverErrorCode] || 'INTERNAL_ERROR'; const error = (0, deep_copy_1.deepCopy)(AuthClientErrorCode[clientCodeKey]); // Server detailed message should have highest priority. error.message = customMessage || message || error.message; if (clientCodeKey === 'INTERNAL_ERROR' && typeof rawServerResponse !== 'undefined') { try { error.message += ` Raw server response: "${JSON.stringify(rawServerResponse)}"`; } catch (e) { // Ignore JSON parsing error. } } return new FirebaseAuthError(error); } constructor(info, message) { // Override default message if custom message provided. super('auth', info.code, message || info.message); /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = FirebaseAuthError.prototype; } } exports.FirebaseAuthError = FirebaseAuthError; /** * Firebase Database error code structure. This extends FirebaseError. * * @param info - The error code info. * @param [message] The error message. This will override the default * message if provided. * @constructor */ class FirebaseDatabaseError extends FirebaseError { constructor(info, message) { // Override default message if custom message provided. super({ code: 'database/' + info.code, message: message || info.message }); } } exports.FirebaseDatabaseError = FirebaseDatabaseError; /** * Firebase Firestore error code structure. This extends FirebaseError. * * @param info - The error code info. * @param [message] The error message. This will override the default * message if provided. * @constructor */ class FirebaseFirestoreError extends FirebaseError { constructor(info, message) { // Override default message if custom message provided. super({ code: 'firestore/' + info.code, message: message || info.message }); } } exports.FirebaseFirestoreError = FirebaseFirestoreError; /** * Firebase instance ID error code structure. This extends FirebaseError. * * @param info - The error code info. * @param [message] The error message. This will override the default * message if provided. * @constructor */ class FirebaseInstanceIdError extends FirebaseError { constructor(info, message) { // Override default message if custom message provided. super({ code: 'instance-id/' + info.code, message: message || info.message }); this.__proto__ = FirebaseInstanceIdError.prototype; } } exports.FirebaseInstanceIdError = FirebaseInstanceIdError; /** * Firebase Installations service error code structure. This extends `FirebaseError`. * * @param info - The error code info. * @param message - The error message. This will override the default * message if provided. * @constructor */ class FirebaseInstallationsError extends FirebaseError { constructor(info, message) { // Override default message if custom message provided. super({ code: 'installations/' + info.code, message: message || info.message }); this.__proto__ = FirebaseInstallationsError.prototype; } } exports.FirebaseInstallationsError = FirebaseInstallationsError; /** * Firebase Messaging error code structure. This extends PrefixedFirebaseError. * * @param info - The error code info. * @param [message] The error message. This will override the default message if provided. * @constructor */ class FirebaseMessagingError extends PrefixedFirebaseError { /** * Creates the developer-facing error corresponding to the backend error code. * * @param serverErrorCode - The server error code. * @param [message] The error message. The default message is used * if not provided. * @param [rawServerResponse] The error's raw server response. * @returns The corresponding developer-facing error. */ static fromServerError(serverErrorCode, message, rawServerResponse) { // If not found, default to unknown error. let clientCodeKey = 'UNKNOWN_ERROR'; if (serverErrorCode && serverErrorCode in MESSAGING_SERVER_TO_CLIENT_CODE) { clientCodeKey = MESSAGING_SERVER_TO_CLIENT_CODE[serverErrorCode]; } const error = (0, deep_copy_1.deepCopy)(MessagingClientErrorCode[clientCodeKey]); error.message = message || error.message; if (clientCodeKey === 'UNKNOWN_ERROR' && typeof rawServerResponse !== 'undefined') { try { error.message += ` Raw server response: "${JSON.stringify(rawServerResponse)}"`; } catch (e) { // Ignore JSON parsing error. } } return new FirebaseMessagingError(error); } static fromTopicManagementServerError(serverErrorCode, message, rawServerResponse) { // If not found, default to unknown error. const clientCodeKey = TOPIC_MGT_SERVER_TO_CLIENT_CODE[serverErrorCode] || 'UNKNOWN_ERROR'; const error = (0, deep_copy_1.deepCopy)(MessagingClientErrorCode[clientCodeKey]); error.message = message || error.message; if (clientCodeKey === 'UNKNOWN_ERROR' && typeof rawServerResponse !== 'undefined') { try { error.message += ` Raw server response: "${JSON.stringify(rawServerResponse)}"`; } catch (e) { // Ignore JSON parsing error. } } return new FirebaseMessagingError(error); } constructor(info, message) { // Override default message if custom message provided. super('messaging', info.code, message || info.message); /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = FirebaseMessagingError.prototype; } } exports.FirebaseMessagingError = FirebaseMessagingError; /** * Firebase project management error code structure. This extends PrefixedFirebaseError. * * @param code - The error code. * @param message - The error message. * @constructor */ class FirebaseProjectManagementError extends PrefixedFirebaseError { constructor(code, message) { super('project-management', code, message); /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = FirebaseProjectManagementError.prototype; } } exports.FirebaseProjectManagementError = FirebaseProjectManagementError; /** * App client error codes and their default messages. */ class AppErrorCodes { } exports.AppErrorCodes = AppErrorCodes; AppErrorCodes.APP_DELETED = 'app-deleted'; AppErrorCodes.DUPLICATE_APP = 'duplicate-app'; AppErrorCodes.INVALID_ARGUMENT = 'invalid-argument'; AppErrorCodes.INTERNAL_ERROR = 'internal-error'; AppErrorCodes.INVALID_APP_NAME = 'invalid-app-name'; AppErrorCodes.INVALID_APP_OPTIONS = 'invalid-app-options'; AppErrorCodes.INVALID_CREDENTIAL = 'invalid-credential'; AppErrorCodes.NETWORK_ERROR = 'network-error'; AppErrorCodes.NETWORK_TIMEOUT = 'network-timeout'; AppErrorCodes.NO_APP = 'no-app'; AppErrorCodes.UNABLE_TO_PARSE_RESPONSE = 'unable-to-parse-response'; /** * Auth client error codes and their default messages. */ class AuthClientErrorCode { } exports.AuthClientErrorCode = AuthClientErrorCode; AuthClientErrorCode.AUTH_BLOCKING_TOKEN_EXPIRED = { code: 'auth-blocking-token-expired', message: 'The provided Firebase Auth Blocking token is expired.', }; AuthClientErrorCode.BILLING_NOT_ENABLED = { code: 'billing-not-enabled', message: 'Feature requires billing to be enabled.', }; AuthClientErrorCode.CLAIMS_TOO_LARGE = { code: 'claims-too-large', message: 'Developer claims maximum payload size exceeded.', }; AuthClientErrorCode.CONFIGURATION_EXISTS = { code: 'configuration-exists', message: 'A configuration already exists with the provided identifier.', }; AuthClientErrorCode.CONFIGURATION_NOT_FOUND = { code: 'configuration-not-found', message: 'There is no configuration corresponding to the provided identifier.', }; AuthClientErrorCode.ID_TOKEN_EXPIRED = { code: 'id-token-expired', message: 'The provided Firebase ID token is expired.', }; AuthClientErrorCode.INVALID_ARGUMENT = { code: 'argument-error', message: 'Invalid argument provided.', }; AuthClientErrorCode.INVALID_CONFIG = { code: 'invalid-config', message: 'The provided configuration is invalid.', }; AuthClientErrorCode.EMAIL_ALREADY_EXISTS = { code: 'email-already-exists', message: 'The email address is already in use by another account.', }; AuthClientErrorCode.EMAIL_NOT_FOUND = { code: 'email-not-found', message: 'There is no user record corresponding to the provided email.', }; AuthClientErrorCode.FORBIDDEN_CLAIM = { code: 'reserved-claim', message: 'The specified developer claim is reserved and cannot be specified.', }; AuthClientErrorCode.INVALID_ID_TOKEN = { code: 'invalid-id-token', message: 'The provided ID token is not a valid Firebase ID token.', }; AuthClientErrorCode.ID_TOKEN_REVOKED = { code: 'id-token-revoked', message: 'The Firebase ID token has been revoked.', }; AuthClientErrorCode.INTERNAL_ERROR = { code: 'internal-error', message: 'An internal error has occurred.', }; AuthClientErrorCode.INVALID_CLAIMS = { code: 'invalid-claims', message: 'The provided custom claim attributes are invalid.', }; AuthClientErrorCode.INVALID_CONTINUE_URI = { code: 'invalid-continue-uri', message: 'The continue URL must be a valid URL string.', }; AuthClientErrorCode.INVALID_CREATION_TIME = { code: 'invalid-creation-time', message: 'The creation time must be a valid UTC date string.', }; AuthClientErrorCode.INVALID_CREDENTIAL = { code: 'invalid-credential', message: 'Invalid credential object provided.', }; AuthClientErrorCode.INVALID_DISABLED_FIELD = { code: 'invalid-disabled-field', message: 'The disabled field must be a boolean.', }; AuthClientErrorCode.INVALID_DISPLAY_NAME = { code: 'invalid-display-name', message: 'The displayName field must be a valid string.', }; AuthClientErrorCode.INVALID_DYNAMIC_LINK_DOMAIN = { code: 'invalid-dynamic-link-domain', message: 'The provided dynamic link domain is not configured or authorized ' + 'for the current project.', }; AuthClientErrorCode.INVALID_EMAIL_VERIFIED = { code: 'invalid-email-verified', message: 'The emailVerified field must be a boolean.', }; AuthClientErrorCode.INVALID_EMAIL = { code: 'invalid-email', message: 'The email address is improperly formatted.', }; AuthClientErrorCode.INVALID_NEW_EMAIL = { code: 'invalid-new-email', message: 'The new email address is improperly formatted.', }; AuthClientErrorCode.INVALID_ENROLLED_FACTORS = { code: 'invalid-enrolled-factors', message: 'The enrolled factors must be a valid array of MultiFactorInfo objects.', }; AuthClientErrorCode.INVALID_ENROLLMENT_TIME = { code: 'invalid-enrollment-time', message: 'The second factor enrollment time must be a valid UTC date string.', }; AuthClientErrorCode.INVALID_HASH_ALGORITHM = { code: 'invalid-hash-algorithm', message: 'The hash algorithm must match one of the strings in the list of ' + 'supported algorithms.', }; AuthClientErrorCode.INVALID_HASH_BLOCK_SIZE = { code: 'invalid-hash-block-size', message: 'The hash block size must be a valid number.', }; AuthClientErrorCode.INVALID_HASH_DERIVED_KEY_LENGTH = { code: 'invalid-hash-derived-key-length', message: 'The hash derived key length must be a valid number.', }; AuthClientErrorCode.INVALID_HASH_KEY = { code: 'invalid-hash-key', message: 'The hash key must a valid byte buffer.', }; AuthClientErrorCode.INVALID_HASH_MEMORY_COST = { code: 'invalid-hash-memory-cost', message: 'The hash memory cost must be a valid number.', }; AuthClientErrorCode.INVALID_HASH_PARALLELIZATION = { code: 'invalid-hash-parallelization', message: 'The hash parallelization must be a valid number.', }; AuthClientErrorCode.INVALID_HASH_ROUNDS = { code: 'invalid-hash-rounds', message: 'The hash rounds must be a valid number.', }; AuthClientErrorCode.INVALID_HASH_SALT_SEPARATOR = { code: 'invalid-hash-salt-separator', message: 'The hashing algorithm salt separator field must be a valid byte buffer.', }; AuthClientErrorCode.INVALID_LAST_SIGN_IN_TIME = { code: 'invalid-last-sign-in-time', message: 'The last sign-in time must be a valid UTC date string.', }; AuthClientErrorCode.INVALID_NAME = { code: 'invalid-name', message: 'The resource name provided is invalid.', }; AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID = { code: 'invalid-oauth-client-id', message: 'The provided OAuth client ID is invalid.', }; AuthClientErrorCode.INVALID_PAGE_TOKEN = { code: 'invalid-page-token', message: 'The page token must be a valid non-empty string.', }; AuthClientErrorCode.INVALID_PASSWORD = { code: 'invalid-password', message: 'The password must be a string with at least 6 characters.', }; AuthClientErrorCode.INVALID_PASSWORD_HASH = { code: 'invalid-password-hash', message: 'The password hash must be a valid byte buffer.', }; AuthClientErrorCode.INVALID_PASSWORD_SALT = { code: 'invalid-password-salt', message: 'The password salt must be a valid byte buffer.', }; AuthClientErrorCode.INVALID_PHONE_NUMBER = { code: 'invalid-phone-number', message: 'The phone number must be a non-empty E.164 standard compliant identifier ' + 'string.', }; AuthClientErrorCode.INVALID_PHOTO_URL = { code: 'invalid-photo-url', message: 'The photoURL field must be a valid URL.', }; AuthClientErrorCode.INVALID_PROJECT_ID = { code: 'invalid-project-id', message: 'Invalid parent project. Either parent project doesn\'t exist or didn\'t enable multi-tenancy.', }; AuthClientErrorCode.INVALID_PROVIDER_DATA = { code: 'invalid-provider-data', message: 'The providerData must be a valid array of UserInfo objects.', }; AuthClientErrorCode.INVALID_PROVIDER_ID = { code: 'invalid-provider-id', message: 'The providerId must be a valid supported provider identifier string.', }; AuthClientErrorCode.INVALID_PROVIDER_UID = { code: 'invalid-provider-uid', message: 'The providerUid must be a valid provider uid string.', }; AuthClientErrorCode.INVALID_OAUTH_RESPONSETYPE = { code: 'invalid-oauth-responsetype', message: 'Only exactly one OAuth responseType should be set to true.', }; AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION = { code: 'invalid-session-cookie-duration', message: 'The session cookie duration must be a valid number in milliseconds ' + 'between 5 minutes and 2 weeks.', }; AuthClientErrorCode.INVALID_TENANT_ID = { code: 'invalid-tenant-id', message: 'The tenant ID must be a valid non-empty string.', }; AuthClientErrorCode.INVALID_TENANT_TYPE = { code: 'invalid-tenant-type', message: 'Tenant type must be either "full_service" or "lightweight".', }; AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER = { code: 'invalid-testing-phone-number', message: 'Invalid testing phone number or invalid test code provided.', }; AuthClientErrorCode.INVALID_UID = { code: 'invalid-uid', message: 'The uid must be a non-empty string with at most 128 characters.', }; AuthClientErrorCode.INVALID_USER_IMPORT = { code: 'invalid-user-import', message: 'The user record to import is invalid.', }; AuthClientErrorCode.INVALID_TOKENS_VALID_AFTER_TIME = { code: 'invalid-tokens-valid-after-time', message: 'The tokensValidAfterTime must be a valid UTC number in seconds.', }; AuthClientErrorCode.MISMATCHING_TENANT_ID = { code: 'mismatching-tenant-id', message: 'User tenant ID does not match with the current TenantAwareAuth tenant ID.', }; AuthClientErrorCode.MISSING_ANDROID_PACKAGE_NAME = { code: 'missing-android-pkg-name', message: 'An Android Package Name must be provided if the Android App is ' + 'required to be installed.', }; AuthClientErrorCode.MISSING_CONFIG = { code: 'missing-config', message: 'The provided configuration is missing required attributes.', }; AuthClientErrorCode.MISSING_CONTINUE_URI = { code: 'missing-continue-uri', message: 'A valid continue URL must be provided in the request.', }; AuthClientErrorCode.MISSING_DISPLAY_NAME = { code: 'missing-display-name', message: 'The resource being created or edited is missing a valid display name.', }; AuthClientErrorCode.MISSING_EMAIL = { code: 'missing-email', message: 'The email is required for the specified action. For example, a multi-factor user ' + 'requires a verified email.', }; AuthClientErrorCode.MISSING_IOS_BUNDLE_ID = { code: 'missing-ios-bundle-id', message: 'The request is missing an iOS Bundle ID.', }; AuthClientErrorCode.MISSING_ISSUER = { code: 'missing-issuer', message: 'The OAuth/OIDC configuration issuer must not be empty.', }; AuthClientErrorCode.MISSING_HASH_ALGORITHM = { code: 'missing-hash-algorithm', message: 'Importing users with password hashes requires that the hashing ' + 'algorithm and its parameters be provided.', }; AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID = { code: 'missing-oauth-client-id', message: 'The OAuth/OIDC configuration client ID must not be empty.', }; AuthClientErrorCode.MISSING_OAUTH_CLIENT_SECRET = { code: 'missing-oauth-client-secret', message: 'The OAuth configuration client secret is required to enable OIDC code flow.', }; AuthClientErrorCode.MISSING_PROVIDER_ID = { code: 'missing-provider-id', message: 'A valid provider ID must be provided in the request.', }; AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG = { code: 'missing-saml-relying-party-config', message: 'The SAML configuration provided is missing a relying party configuration.', }; AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED = { code: 'test-phone-number-limit-exceeded', message: 'The maximum allowed number of test phone number / code pairs has been exceeded.', }; AuthClientErrorCode.MAXIMUM_USER_COUNT_EXCEEDED = { code: 'maximum-user-count-exceeded', message: 'The maximum allowed number of users to import has been exceeded.', }; AuthClientErrorCode.MISSING_UID = { code: 'missing-uid', message: 'A uid identifier is required for the current operation.', }; AuthClientErrorCode.OPERATION_NOT_ALLOWED = { code: 'operation-not-allowed', message: 'The given sign-in provider is disabled for this Firebase project. ' + 'Enable it in the Firebase console, under the sign-in method tab of the ' + 'Auth section.', }; AuthClientErrorCode.PHONE_NUMBER_ALREADY_EXISTS = { code: 'phone-number-already-exists', message: 'The user with the provided phone number already exists.', }; AuthClientErrorCode.PROJECT_NOT_FOUND = { code: 'project-not-found', message: 'No Firebase project was found for the provided credential.', }; AuthClientErrorCode.INSUFFICIENT_PERMISSION = { code: 'insufficient-permission', message: 'Credential implementation provided to initializeApp() via the "credential" property ' + 'has insufficient permission to access the requested resource. See ' + 'https://firebase.google.com/docs/admin/setup for details on how to authenticate this SDK ' + 'with appropriate permissions.', }; AuthClientErrorCode.QUOTA_EXCEEDED = { code: 'quota-exceeded', message: 'The project quota for the specified operation has been exceeded.', }; AuthClientErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED = { code: 'second-factor-limit-exceeded', message: 'The maximum number of allowed second factors on a user has been exceeded.', }; AuthClientErrorCode.SECOND_FACTOR_UID_ALREADY_EXISTS = { code: 'second-factor-uid-already-exists', message: 'The specified second factor "uid" already exists.', }; AuthClientErrorCode.SESSION_COOKIE_EXPIRED = { code: 'session-cookie-expired', message: 'The Firebase session cookie is expired.', }; AuthClientErrorCode.SESSION_COOKIE_REVOKED = { code: 'session-cookie-revoked', message: 'The Firebase session cookie has been revoked.', }; AuthClientErrorCode.TENANT_NOT_FOUND = { code: 'tenant-not-found', message: 'There is no tenant corresponding to the provided identifier.', }; AuthClientErrorCode.UID_ALREADY_EXISTS = { code: 'uid-already-exists', message: 'The user with the provided uid already exists.', }; AuthClientErrorCode.UNAUTHORIZED_DOMAIN = { code: 'unauthorized-continue-uri', message: 'The domain of the continue URL is not whitelisted. Whitelist the domain in the ' + 'Firebase console.', }; AuthClientErrorCode.UNSUPPORTED_FIRST_FACTOR = { code: 'unsupported-first-factor', message: 'A multi-factor user requires a supported first factor.', }; AuthClientErrorCode.UNSUPPORTED_SECOND_FACTOR = { code: 'unsupported-second-factor', message: 'The request specified an unsupported type of second factor.', }; AuthClientErrorCode.UNSUPPORTED_TENANT_OPERATION = { code: 'unsupported-tenant-operation', message: 'This operation is not supported in a multi-tenant context.', }; AuthClientErrorCode.UNVERIFIED_EMAIL = { code: 'unverified-email', message: 'A verified email is required for the specified action. For example, a multi-factor user ' + 'requires a verified email.', }; AuthClientErrorCode.USER_NOT_FOUND = { code: 'user-not-found', message: 'There is no user record corresponding to the provided identifier.', }; AuthClientErrorCode.NOT_FOUND = { code: 'not-found', message: 'The requested resource was not found.', }; AuthClientErrorCode.USER_DISABLED = { code: 'user-disabled', message: 'The user record is disabled.', }; AuthClientErrorCode.USER_NOT_DISABLED = { code: 'user-not-disabled', message: 'The user must be disabled in order to bulk delete it (or you must pass force=true).', }; /** * Messaging client error codes and their default messages. */ class MessagingClientErrorCode { } exports.MessagingClientErrorCode = MessagingClientErrorCode; MessagingClientErrorCode.INVALID_ARGUMENT = { code: 'invalid-argument', message: 'Invalid argument provided.', }; MessagingClientErrorCode.INVALID_RECIPIENT = { code: 'invalid-recipient', message: 'Invalid message recipient provided.', }; MessagingClientErrorCode.INVALID_PAYLOAD = { code: 'invalid-payload', message: 'Invalid message payload provided.', }; MessagingClientErrorCode.INVALID_DATA_PAYLOAD_KEY = { code: 'invalid-data-payload-key', message: 'The data message payload contains an invalid key. See the reference documentation ' + 'for the DataMessagePayload type for restricted keys.', }; MessagingClientErrorCode.PAYLOAD_SIZE_LIMIT_EXCEEDED = { code: 'payload-size-limit-exceeded', message: 'The provided message payload exceeds the FCM size limits. See the error documentation ' + 'for more details.', }; MessagingClientErrorCode.INVALID_OPTIONS = { code: 'invalid-options', message: 'Invalid message options provided.', }; MessagingClientErrorCode.INVALID_REGISTRATION_TOKEN = { code: 'invalid-registration-token', message: 'Invalid registration token provided. Make sure it matches the registration token ' + 'the client app receives from registering with FCM.', }; MessagingClientErrorCode.REGISTRATION_TOKEN_NOT_REGISTERED = { code: 'registration-token-not-registered', message: 'The provided registration token is not registered. A previously valid registration ' + 'token can be unregistered for a variety of reasons. See the error documentation for more ' + 'details. Remove this registration token and stop using it to send messages.', }; MessagingClientErrorCode.MISMATCHED_CREDENTIAL = { code: 'mismatched-credential', message: 'The credential used to authenticate this SDK does not have permission to send ' + 'messages to the device corresponding to the provided registration token. Make sure the ' + 'credential and registration token both belong to the same Firebase project.', }; MessagingClientErrorCode.INVALID_PACKAGE_NAME = { code: 'invalid-package-name', message: 'The message was addressed to a registration token whose package name does not match ' + 'the provided "restrictedPackageName" option.', }; MessagingClientErrorCode.DEVICE_MESSAGE_RATE_EXCEEDED = { code: 'device-message-rate-exceeded', message: 'The rate of messages to a particular device is too high. Reduce the number of ' + 'messages sent to this device and do not immediately retry sending to this device.', }; MessagingClientErrorCode.TOPICS_MESSAGE_RATE_EXCEEDED = { code: 'topics-message-rate-exceeded', message: 'The rate of messages to subscribers to a particular topic is too high. Reduce the ' + 'number of messages sent for this topic, and do not immediately retry sending to this topic.', }; MessagingClientErrorCode.MESSAGE_RATE_EXCEEDED = { code: 'message-rate-exceeded', message: 'Sending limit exceeded for the message target.', }; MessagingClientErrorCode.THIRD_PARTY_AUTH_ERROR = { code: 'third-party-auth-error', message: 'A message targeted to an iOS device could not be sent because the required APNs ' + 'SSL certificate was not uploaded or has expired. Check the validity of your development ' + 'and production certificates.', }; MessagingClientErrorCode.TOO_MANY_TOPICS = { code: 'too-many-topics', message: 'The maximum number of topics the provided registration token can be subscribed to ' + 'has been exceeded.', }; MessagingClientErrorCode.AUTHENTICATION_ERROR = { code: 'authentication-error', message: 'An error occurred when trying to authenticate to the FCM servers. Make sure the ' + 'credential used to authenticate this SDK has the proper permissions. See ' + 'https://firebase.google.com/docs/admin/setup for setup instructions.', }; MessagingClientErrorCode.SERVER_UNAVAILABLE = { code: 'server-unavailable', message: 'The FCM server could not process the request in time. See the error documentation ' + 'for more details.', }; MessagingClientErrorCode.INTERNAL_ERROR = { code: 'internal-error',
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/crypto-signer.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/crypto-signer.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.CryptoSignerErrorCode = exports.CryptoSignerError = exports.cryptoSignerFromApp = exports.IAMSigner = exports.ServiceAccountSigner = void 0; const credential_internal_1 = require("../app/credential-internal"); const api_request_1 = require("./api-request"); const validator = require("../utils/validator"); const ALGORITHM_RS256 = 'RS256'; /** * A CryptoSigner implementation that uses an explicitly specified service account private key to * sign data. Performs all operations locally, and does not make any RPC calls. */ class ServiceAccountSigner { /** * Creates a new CryptoSigner instance from the given service account credential. * * @param credential - A service account credential. */ constructor(credential) { this.credential = credential; this.algorithm = ALGORITHM_RS256; if (!credential) { throw new CryptoSignerError({ code: CryptoSignerErrorCode.INVALID_CREDENTIAL, message: 'INTERNAL ASSERT: Must provide a service account credential to initialize ServiceAccountSigner.', }); } } /** * @inheritDoc */ sign(buffer) { const crypto = require('crypto'); // eslint-disable-line @typescript-eslint/no-var-requires const sign = crypto.createSign('RSA-SHA256'); sign.update(buffer); return Promise.resolve(sign.sign(this.credential.privateKey)); } /** * @inheritDoc */ getAccountId() { return Promise.resolve(this.credential.clientEmail); } } exports.ServiceAccountSigner = ServiceAccountSigner; /** * A CryptoSigner implementation that uses the remote IAM service to sign data. If initialized without * a service account ID, attempts to discover a service account ID by consulting the local Metadata * service. This will succeed in managed environments like Google Cloud Functions and App Engine. * * @see https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob * @see https://cloud.google.com/compute/docs/storing-retrieving-metadata */ class IAMSigner { constructor(httpClient, serviceAccountId) { this.algorithm = ALGORITHM_RS256; if (!httpClient) { throw new CryptoSignerError({ code: CryptoSignerErrorCode.INVALID_ARGUMENT, message: 'INTERNAL ASSERT: Must provide a HTTP client to initialize IAMSigner.', }); } if (typeof serviceAccountId !== 'undefined' && !validator.isNonEmptyString(serviceAccountId)) { throw new CryptoSignerError({ code: CryptoSignerErrorCode.INVALID_ARGUMENT, message: 'INTERNAL ASSERT: Service account ID must be undefined or a non-empty string.', }); } this.httpClient = httpClient; this.serviceAccountId = serviceAccountId; } /** * @inheritDoc */ sign(buffer) { return this.getAccountId().then((serviceAccount) => { const request = { method: 'POST', url: `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${serviceAccount}:signBlob`, data: { payload: buffer.toString('base64') }, }; return this.httpClient.send(request); }).then((response) => { // Response from IAM is base64 encoded. Decode it into a buffer and return. return Buffer.from(response.data.signedBlob, 'base64'); }).catch((err) => { if (err instanceof api_request_1.HttpError) { throw new CryptoSignerError({ code: CryptoSignerErrorCode.SERVER_ERROR, message: err.message, cause: err }); } throw err; }); } /** * @inheritDoc */ getAccountId() { if (validator.isNonEmptyString(this.serviceAccountId)) { return Promise.resolve(this.serviceAccountId); } const request = { method: 'GET', url: 'http://metadata/computeMetadata/v1/instance/service-accounts/default/email', headers: { 'Metadata-Flavor': 'Google', }, }; const client = new api_request_1.HttpClient(); return client.send(request).then((response) => { if (!response.text) { throw new CryptoSignerError({ code: CryptoSignerErrorCode.INTERNAL_ERROR, message: 'HTTP Response missing payload', }); } this.serviceAccountId = response.text; return response.text; }).catch((err) => { throw new CryptoSignerError({ code: CryptoSignerErrorCode.INVALID_CREDENTIAL, message: 'Failed to determine service account. Make sure to initialize ' + 'the SDK with a service account credential. Alternatively specify a service ' + `account with iam.serviceAccounts.signBlob permission. Original error: ${err}`, }); }); } } exports.IAMSigner = IAMSigner; /** * Creates a new CryptoSigner instance for the given app. If the app has been initialized with a * service account credential, creates a ServiceAccountSigner. * * @param app - A FirebaseApp instance. * @returns A CryptoSigner instance. */ function cryptoSignerFromApp(app) { const credential = app.options.credential; if (credential instanceof credential_internal_1.ServiceAccountCredential) { return new ServiceAccountSigner(credential); } return new IAMSigner(new api_request_1.AuthorizedHttpClient(app), app.options.serviceAccountId); } exports.cryptoSignerFromApp = cryptoSignerFromApp; /** * CryptoSigner error code structure. * * @param errorInfo - The error information (code and message). * @constructor */ class CryptoSignerError extends Error { constructor(errorInfo) { super(errorInfo.message); this.errorInfo = errorInfo; /* tslint:disable:max-line-length */ // Set the prototype explicitly. See the following link for more details: // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work /* tslint:enable:max-line-length */ this.__proto__ = CryptoSignerError.prototype; } /** @returns The error code. */ get code() { return this.errorInfo.code; } /** @returns The error message. */ get message() { return this.errorInfo.message; } /** @returns The error data. */ get cause() { return this.errorInfo.cause; } } exports.CryptoSignerError = CryptoSignerError; /** * Crypto Signer error codes and their default messages. */ class CryptoSignerErrorCode { } exports.CryptoSignerErrorCode = CryptoSignerErrorCode; CryptoSignerErrorCode.INVALID_ARGUMENT = 'invalid-argument'; CryptoSignerErrorCode.INTERNAL_ERROR = 'internal-error'; CryptoSignerErrorCode.INVALID_CREDENTIAL = 'invalid-credential'; CryptoSignerErrorCode.SERVER_ERROR = 'server-error';
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/utils/validator.js
aws/lti-middleware/node_modules/firebase-admin/lib/utils/validator.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.isTopic = exports.isURL = exports.isUTCDateString = exports.isISODateString = exports.isPhoneNumber = exports.isEmail = exports.isPassword = exports.isUid = exports.isNonNullObject = exports.isObject = exports.isNonEmptyString = exports.isBase64String = exports.isString = exports.isNumber = exports.isBoolean = exports.isNonEmptyArray = exports.isArray = exports.isBuffer = void 0; const url = require("url"); /** * Validates that a value is a byte buffer. * * @param value - The value to validate. * @returns Whether the value is byte buffer or not. */ function isBuffer(value) { return value instanceof Buffer; } exports.isBuffer = isBuffer; /** * Validates that a value is an array. * * @param value - The value to validate. * @returns Whether the value is an array or not. */ function isArray(value) { return Array.isArray(value); } exports.isArray = isArray; /** * Validates that a value is a non-empty array. * * @param value - The value to validate. * @returns Whether the value is a non-empty array or not. */ function isNonEmptyArray(value) { return isArray(value) && value.length !== 0; } exports.isNonEmptyArray = isNonEmptyArray; /** * Validates that a value is a boolean. * * @param value - The value to validate. * @returns Whether the value is a boolean or not. */ function isBoolean(value) { return typeof value === 'boolean'; } exports.isBoolean = isBoolean; /** * Validates that a value is a number. * * @param value - The value to validate. * @returns Whether the value is a number or not. */ function isNumber(value) { return typeof value === 'number' && !isNaN(value); } exports.isNumber = isNumber; /** * Validates that a value is a string. * * @param value - The value to validate. * @returns Whether the value is a string or not. */ function isString(value) { return typeof value === 'string'; } exports.isString = isString; /** * Validates that a value is a base64 string. * * @param value - The value to validate. * @returns Whether the value is a base64 string or not. */ function isBase64String(value) { if (!isString(value)) { return false; } return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value); } exports.isBase64String = isBase64String; /** * Validates that a value is a non-empty string. * * @param value - The value to validate. * @returns Whether the value is a non-empty string or not. */ function isNonEmptyString(value) { return isString(value) && value !== ''; } exports.isNonEmptyString = isNonEmptyString; /** * Validates that a value is a nullable object. * * @param value - The value to validate. * @returns Whether the value is an object or not. */ function isObject(value) { return typeof value === 'object' && !isArray(value); } exports.isObject = isObject; /** * Validates that a value is a non-null object. * * @param value - The value to validate. * @returns Whether the value is a non-null object or not. */ function isNonNullObject(value) { return isObject(value) && value !== null; } exports.isNonNullObject = isNonNullObject; /** * Validates that a string is a valid Firebase Auth uid. * * @param uid - The string to validate. * @returns Whether the string is a valid Firebase Auth uid. */ function isUid(uid) { return typeof uid === 'string' && uid.length > 0 && uid.length <= 128; } exports.isUid = isUid; /** * Validates that a string is a valid Firebase Auth password. * * @param password - The password string to validate. * @returns Whether the string is a valid Firebase Auth password. */ function isPassword(password) { // A password must be a string of at least 6 characters. return typeof password === 'string' && password.length >= 6; } exports.isPassword = isPassword; /** * Validates that a string is a valid email. * * @param email - The string to validate. * @returns Whether the string is valid email or not. */ function isEmail(email) { if (typeof email !== 'string') { return false; } // There must at least one character before the @ symbol and another after. const re = /^[^@]+@[^@]+$/; return re.test(email); } exports.isEmail = isEmail; /** * Validates that a string is a valid phone number. * * @param phoneNumber - The string to validate. * @returns Whether the string is a valid phone number or not. */ function isPhoneNumber(phoneNumber) { if (typeof phoneNumber !== 'string') { return false; } // Phone number validation is very lax here. Backend will enforce E.164 // spec compliance and will normalize accordingly. // The phone number string must be non-empty and starts with a plus sign. const re1 = /^\+/; // The phone number string must contain at least one alphanumeric character. const re2 = /[\da-zA-Z]+/; return re1.test(phoneNumber) && re2.test(phoneNumber); } exports.isPhoneNumber = isPhoneNumber; /** * Validates that a string is a valid ISO date string. * * @param dateString - The string to validate. * @returns Whether the string is a valid ISO date string. */ function isISODateString(dateString) { try { return isNonEmptyString(dateString) && (new Date(dateString).toISOString() === dateString); } catch (e) { return false; } } exports.isISODateString = isISODateString; /** * Validates that a string is a valid UTC date string. * * @param dateString - The string to validate. * @returns Whether the string is a valid UTC date string. */ function isUTCDateString(dateString) { try { return isNonEmptyString(dateString) && (new Date(dateString).toUTCString() === dateString); } catch (e) { return false; } } exports.isUTCDateString = isUTCDateString; /** * Validates that a string is a valid web URL. * * @param urlStr - The string to validate. * @returns Whether the string is valid web URL or not. */ function isURL(urlStr) { if (typeof urlStr !== 'string') { return false; } // Lookup illegal characters. const re = /[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i; if (re.test(urlStr)) { return false; } try { const uri = url.parse(urlStr); const scheme = uri.protocol; const slashes = uri.slashes; const hostname = uri.hostname; const pathname = uri.pathname; if ((scheme !== 'http:' && scheme !== 'https:') || !slashes) { return false; } // Validate hostname: Can contain letters, numbers, underscore and dashes separated by a dot. // Each zone must not start with a hyphen or underscore. if (!hostname || !/^[a-zA-Z0-9]+[\w-]*([.]?[a-zA-Z0-9]+[\w-]*)*$/.test(hostname)) { return false; } // Allow for pathnames: (/chars+)*/? // Where chars can be a combination of: a-z A-Z 0-9 - _ . ~ ! $ & ' ( ) * + , ; = : @ % const pathnameRe = /^(\/[\w\-.~!$'()*+,;=:@%]+)*\/?$/; // Validate pathname. if (pathname && pathname !== '/' && !pathnameRe.test(pathname)) { return false; } // Allow any query string and hash as long as no invalid character is used. } catch (e) { return false; } return true; } exports.isURL = isURL; /** * Validates that the provided topic is a valid FCM topic name. * * @param topic - The topic to validate. * @returns Whether the provided topic is a valid FCM topic name. */ function isTopic(topic) { if (typeof topic !== 'string') { return false; } const VALID_TOPIC_REGEX = /^(\/topics\/)?(private\/)?[a-zA-Z0-9-_.~%]+$/; return VALID_TOPIC_REGEX.test(topic); } exports.isTopic = isTopic;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getRemoteConfig = exports.RemoteConfig = void 0; /** * Firebase Remote Config. * * @packageDocumentation */ const app_1 = require("../app"); const remote_config_1 = require("./remote-config"); var remote_config_2 = require("./remote-config"); Object.defineProperty(exports, "RemoteConfig", { enumerable: true, get: function () { return remote_config_2.RemoteConfig; } }); /** * Gets the {@link RemoteConfig} service for the default app or a given app. * * `getRemoteConfig()` can be called with no arguments to access the default * app's `RemoteConfig` service or as `getRemoteConfig(app)` to access the * `RemoteConfig` service associated with a specific app. * * @example * ```javascript * // Get the `RemoteConfig` service for the default app * const defaultRemoteConfig = getRemoteConfig(); * ``` * * @example * ```javascript * // Get the `RemoteConfig` service for a given app * const otherRemoteConfig = getRemoteConfig(otherApp); * ``` * * @param app - Optional app for which to return the `RemoteConfig` service. * If not provided, the default `RemoteConfig` service is returned. * * @returns The default `RemoteConfig` service if no * app is provided, or the `RemoteConfig` service associated with the provided * app. */ function getRemoteConfig(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('remoteConfig', (app) => new remote_config_1.RemoteConfig(app)); } exports.getRemoteConfig = getRemoteConfig;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config-api.js
aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config-api.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config-api-client-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebaseRemoteConfigError = exports.RemoteConfigApiClient = void 0; const api_request_1 = require("../utils/api-request"); const error_1 = require("../utils/error"); const utils = require("../utils/index"); const validator = require("../utils/validator"); const deep_copy_1 = require("../utils/deep-copy"); // Remote Config backend constants const FIREBASE_REMOTE_CONFIG_V1_API = 'https://firebaseremoteconfig.googleapis.com/v1'; const FIREBASE_REMOTE_CONFIG_HEADERS = { 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, // There is a known issue in which the ETag is not properly returned in cases where the request // does not specify a compression type. Currently, it is required to include the header // `Accept-Encoding: gzip` or equivalent in all requests. // https://firebase.google.com/docs/remote-config/use-config-rest#etag_usage_and_forced_updates 'Accept-Encoding': 'gzip', }; /** * Class that facilitates sending requests to the Firebase Remote Config backend API. * * @internal */ class RemoteConfigApiClient { constructor(app) { this.app = app; if (!validator.isNonNullObject(app) || !('options' in app)) { throw new FirebaseRemoteConfigError('invalid-argument', 'First argument passed to admin.remoteConfig() must be a valid Firebase app instance.'); } this.httpClient = new api_request_1.AuthorizedHttpClient(app); } getTemplate() { return this.getUrl() .then((url) => { const request = { method: 'GET', url: `${url}/remoteConfig`, headers: FIREBASE_REMOTE_CONFIG_HEADERS }; return this.httpClient.send(request); }) .then((resp) => { return this.toRemoteConfigTemplate(resp); }) .catch((err) => { throw this.toFirebaseError(err); }); } getTemplateAtVersion(versionNumber) { const data = { versionNumber: this.validateVersionNumber(versionNumber) }; return this.getUrl() .then((url) => { const request = { method: 'GET', url: `${url}/remoteConfig`, headers: FIREBASE_REMOTE_CONFIG_HEADERS, data }; return this.httpClient.send(request); }) .then((resp) => { return this.toRemoteConfigTemplate(resp); }) .catch((err) => { throw this.toFirebaseError(err); }); } validateTemplate(template) { template = this.validateInputRemoteConfigTemplate(template); return this.sendPutRequest(template, template.etag, true) .then((resp) => { // validating a template returns an etag with the suffix -0 means that your update // was successfully validated. We set the etag back to the original etag of the template // to allow future operations. this.validateEtag(resp.headers['etag']); return this.toRemoteConfigTemplate(resp, template.etag); }) .catch((err) => { throw this.toFirebaseError(err); }); } publishTemplate(template, options) { template = this.validateInputRemoteConfigTemplate(template); let ifMatch = template.etag; if (options && options.force == true) { // setting `If-Match: *` forces the Remote Config template to be updated // and circumvent the ETag, and the protection from that it provides. ifMatch = '*'; } return this.sendPutRequest(template, ifMatch) .then((resp) => { return this.toRemoteConfigTemplate(resp); }) .catch((err) => { throw this.toFirebaseError(err); }); } rollback(versionNumber) { const data = { versionNumber: this.validateVersionNumber(versionNumber) }; return this.getUrl() .then((url) => { const request = { method: 'POST', url: `${url}/remoteConfig:rollback`, headers: FIREBASE_REMOTE_CONFIG_HEADERS, data }; return this.httpClient.send(request); }) .then((resp) => { return this.toRemoteConfigTemplate(resp); }) .catch((err) => { throw this.toFirebaseError(err); }); } listVersions(options) { if (typeof options !== 'undefined') { options = this.validateListVersionsOptions(options); } return this.getUrl() .then((url) => { const request = { method: 'GET', url: `${url}/remoteConfig:listVersions`, headers: FIREBASE_REMOTE_CONFIG_HEADERS, data: options }; return this.httpClient.send(request); }) .then((resp) => { return resp.data; }) .catch((err) => { throw this.toFirebaseError(err); }); } sendPutRequest(template, etag, validateOnly) { let path = 'remoteConfig'; if (validateOnly) { path += '?validate_only=true'; } return this.getUrl() .then((url) => { const request = { method: 'PUT', url: `${url}/${path}`, headers: { ...FIREBASE_REMOTE_CONFIG_HEADERS, 'If-Match': etag }, data: { conditions: template.conditions, parameters: template.parameters, parameterGroups: template.parameterGroups, version: template.version, } }; return this.httpClient.send(request); }); } getUrl() { return this.getProjectIdPrefix() .then((projectIdPrefix) => { return `${FIREBASE_REMOTE_CONFIG_V1_API}/${projectIdPrefix}`; }); } getProjectIdPrefix() { if (this.projectIdPrefix) { return Promise.resolve(this.projectIdPrefix); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new FirebaseRemoteConfigError('unknown-error', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + 'environment variable.'); } this.projectIdPrefix = `projects/${projectId}`; return this.projectIdPrefix; }); } toFirebaseError(err) { if (err instanceof error_1.PrefixedFirebaseError) { return err; } const response = err.response; if (!response.isJson()) { return new FirebaseRemoteConfigError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); } const error = response.data.error || {}; let code = 'unknown-error'; if (error.status && error.status in ERROR_CODE_MAPPING) { code = ERROR_CODE_MAPPING[error.status]; } const message = error.message || `Unknown server error: ${response.text}`; return new FirebaseRemoteConfigError(code, message); } /** * Creates a RemoteConfigTemplate from the API response. * If provided, customEtag is used instead of the etag returned in the API response. * * @param {HttpResponse} resp API response object. * @param {string} customEtag A custom etag to replace the etag fom the API response (Optional). */ toRemoteConfigTemplate(resp, customEtag) { const etag = (typeof customEtag == 'undefined') ? resp.headers['etag'] : customEtag; this.validateEtag(etag); return { conditions: resp.data.conditions, parameters: resp.data.parameters, parameterGroups: resp.data.parameterGroups, etag, version: resp.data.version, }; } /** * Checks if the given RemoteConfigTemplate object is valid. * The object must have valid parameters, parameter groups, conditions, and an etag. * Removes output only properties from version metadata. * * @param {RemoteConfigTemplate} template A RemoteConfigTemplate object to be validated. * * @returns {RemoteConfigTemplate} The validated RemoteConfigTemplate object. */ validateInputRemoteConfigTemplate(template) { const templateCopy = (0, deep_copy_1.deepCopy)(template); if (!validator.isNonNullObject(templateCopy)) { throw new FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config template: ${JSON.stringify(templateCopy)}`); } if (!validator.isNonEmptyString(templateCopy.etag)) { throw new FirebaseRemoteConfigError('invalid-argument', 'ETag must be a non-empty string.'); } if (!validator.isNonNullObject(templateCopy.parameters)) { throw new FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameters must be a non-null object'); } if (!validator.isNonNullObject(templateCopy.parameterGroups)) { throw new FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameter groups must be a non-null object'); } if (!validator.isArray(templateCopy.conditions)) { throw new FirebaseRemoteConfigError('invalid-argument', 'Remote Config conditions must be an array'); } if (typeof templateCopy.version !== 'undefined') { // exclude output only properties and keep the only input property: description templateCopy.version = { description: templateCopy.version.description }; } return templateCopy; } /** * Checks if a given version number is valid. * A version number must be an integer or a string in int64 format. * If valid, returns the string representation of the provided version number. * * @param {string|number} versionNumber A version number to be validated. * * @returns {string} The validated version number as a string. */ validateVersionNumber(versionNumber, propertyName = 'versionNumber') { if (!validator.isNonEmptyString(versionNumber) && !validator.isNumber(versionNumber)) { throw new FirebaseRemoteConfigError('invalid-argument', `${propertyName} must be a non-empty string in int64 format or a number`); } if (!Number.isInteger(Number(versionNumber))) { throw new FirebaseRemoteConfigError('invalid-argument', `${propertyName} must be an integer or a string in int64 format`); } return versionNumber.toString(); } validateEtag(etag) { if (!validator.isNonEmptyString(etag)) { throw new FirebaseRemoteConfigError('invalid-argument', 'ETag header is not present in the server response.'); } } /** * Checks if a given `ListVersionsOptions` object is valid. If successful, creates a copy of the * options object and convert `startTime` and `endTime` to RFC3339 UTC "Zulu" format, if present. * * @param {ListVersionsOptions} options An options object to be validated. * * @returns {ListVersionsOptions} A copy of the provided options object with timestamps converted * to UTC Zulu format. */ validateListVersionsOptions(options) { const optionsCopy = (0, deep_copy_1.deepCopy)(options); if (!validator.isNonNullObject(optionsCopy)) { throw new FirebaseRemoteConfigError('invalid-argument', 'ListVersionsOptions must be a non-null object.'); } if (typeof optionsCopy.pageSize !== 'undefined') { if (!validator.isNumber(optionsCopy.pageSize)) { throw new FirebaseRemoteConfigError('invalid-argument', 'pageSize must be a number.'); } if (optionsCopy.pageSize < 1 || optionsCopy.pageSize > 300) { throw new FirebaseRemoteConfigError('invalid-argument', 'pageSize must be a number between 1 and 300 (inclusive).'); } } if (typeof optionsCopy.pageToken !== 'undefined' && !validator.isNonEmptyString(optionsCopy.pageToken)) { throw new FirebaseRemoteConfigError('invalid-argument', 'pageToken must be a string value.'); } if (typeof optionsCopy.endVersionNumber !== 'undefined') { optionsCopy.endVersionNumber = this.validateVersionNumber(optionsCopy.endVersionNumber, 'endVersionNumber'); } if (typeof optionsCopy.startTime !== 'undefined') { if (!(optionsCopy.startTime instanceof Date) && !validator.isUTCDateString(optionsCopy.startTime)) { throw new FirebaseRemoteConfigError('invalid-argument', 'startTime must be a valid Date object or a UTC date string.'); } // Convert startTime to RFC3339 UTC "Zulu" format. if (optionsCopy.startTime instanceof Date) { optionsCopy.startTime = optionsCopy.startTime.toISOString(); } else { optionsCopy.startTime = new Date(optionsCopy.startTime).toISOString(); } } if (typeof optionsCopy.endTime !== 'undefined') { if (!(optionsCopy.endTime instanceof Date) && !validator.isUTCDateString(optionsCopy.endTime)) { throw new FirebaseRemoteConfigError('invalid-argument', 'endTime must be a valid Date object or a UTC date string.'); } // Convert endTime to RFC3339 UTC "Zulu" format. if (optionsCopy.endTime instanceof Date) { optionsCopy.endTime = optionsCopy.endTime.toISOString(); } else { optionsCopy.endTime = new Date(optionsCopy.endTime).toISOString(); } } // Remove undefined fields from optionsCopy Object.keys(optionsCopy).forEach(key => (typeof optionsCopy[key] === 'undefined') && delete optionsCopy[key]); return optionsCopy; } } exports.RemoteConfigApiClient = RemoteConfigApiClient; const ERROR_CODE_MAPPING = { ABORTED: 'aborted', ALREADY_EXISTS: 'already-exists', INVALID_ARGUMENT: 'invalid-argument', INTERNAL: 'internal-error', FAILED_PRECONDITION: 'failed-precondition', NOT_FOUND: 'not-found', OUT_OF_RANGE: 'out-of-range', PERMISSION_DENIED: 'permission-denied', RESOURCE_EXHAUSTED: 'resource-exhausted', UNAUTHENTICATED: 'unauthenticated', UNKNOWN: 'unknown-error', }; /** * Firebase Remote Config error code structure. This extends PrefixedFirebaseError. * * @param {RemoteConfigErrorCode} code The error code. * @param {string} message The error message. * @constructor */ class FirebaseRemoteConfigError extends error_1.PrefixedFirebaseError { constructor(code, message) { super('remote-config', code, message); } } exports.FirebaseRemoteConfigError = FirebaseRemoteConfigError;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config.js
aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoteConfig = void 0; const validator = require("../utils/validator"); const remote_config_api_client_internal_1 = require("./remote-config-api-client-internal"); /** * The Firebase `RemoteConfig` service interface. */ class RemoteConfig { /** * @param app - The app for this RemoteConfig service. * @constructor * @internal */ constructor(app) { this.app = app; this.client = new remote_config_api_client_internal_1.RemoteConfigApiClient(app); } /** * Gets the current active version of the {@link RemoteConfigTemplate} of the project. * * @returns A promise that fulfills with a `RemoteConfigTemplate`. */ getTemplate() { return this.client.getTemplate() .then((templateResponse) => { return new RemoteConfigTemplateImpl(templateResponse); }); } /** * Gets the requested version of the {@link RemoteConfigTemplate} of the project. * * @param versionNumber - Version number of the Remote Config template to look up. * * @returns A promise that fulfills with a `RemoteConfigTemplate`. */ getTemplateAtVersion(versionNumber) { return this.client.getTemplateAtVersion(versionNumber) .then((templateResponse) => { return new RemoteConfigTemplateImpl(templateResponse); }); } /** * Validates a {@link RemoteConfigTemplate}. * * @param template - The Remote Config template to be validated. * @returns A promise that fulfills with the validated `RemoteConfigTemplate`. */ validateTemplate(template) { return this.client.validateTemplate(template) .then((templateResponse) => { return new RemoteConfigTemplateImpl(templateResponse); }); } /** * Publishes a Remote Config template. * * @param template - The Remote Config template to be published. * @param options - Optional options object when publishing a Remote Config template: * - `force`: Setting this to `true` forces the Remote Config template to * be updated and circumvent the ETag. This approach is not recommended * because it risks causing the loss of updates to your Remote Config * template if multiple clients are updating the Remote Config template. * See {@link https://firebase.google.com/docs/remote-config/use-config-rest#etag_usage_and_forced_updates | * ETag usage and forced updates}. * * @returns A Promise that fulfills with the published `RemoteConfigTemplate`. */ publishTemplate(template, options) { return this.client.publishTemplate(template, options) .then((templateResponse) => { return new RemoteConfigTemplateImpl(templateResponse); }); } /** * Rolls back a project's published Remote Config template to the specified version. * A rollback is equivalent to getting a previously published Remote Config * template and re-publishing it using a force update. * * @param versionNumber - The version number of the Remote Config template to roll back to. * The specified version number must be lower than the current version number, and not have * been deleted due to staleness. Only the last 300 versions are stored. * All versions that correspond to non-active Remote Config templates (that is, all except the * template that is being fetched by clients) are also deleted if they are more than 90 days old. * @returns A promise that fulfills with the published `RemoteConfigTemplate`. */ rollback(versionNumber) { return this.client.rollback(versionNumber) .then((templateResponse) => { return new RemoteConfigTemplateImpl(templateResponse); }); } /** * Gets a list of Remote Config template versions that have been published, sorted in reverse * chronological order. Only the last 300 versions are stored. * All versions that correspond to non-active Remote Config templates (i.e., all except the * template that is being fetched by clients) are also deleted if they are older than 90 days. * * @param options - Optional options object for getting a list of versions. * @returns A promise that fulfills with a `ListVersionsResult`. */ listVersions(options) { return this.client.listVersions(options) .then((listVersionsResponse) => { return { versions: listVersionsResponse.versions?.map(version => new VersionImpl(version)) ?? [], nextPageToken: listVersionsResponse.nextPageToken, }; }); } /** * Creates and returns a new Remote Config template from a JSON string. * * @param json - The JSON string to populate a Remote Config template. * * @returns A new template instance. */ createTemplateFromJSON(json) { if (!validator.isNonEmptyString(json)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'JSON string must be a valid non-empty string'); } let template; try { template = JSON.parse(json); } catch (e) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Failed to parse the JSON string: ${json}. ` + e); } return new RemoteConfigTemplateImpl(template); } } exports.RemoteConfig = RemoteConfig; /** * Remote Config template internal implementation. */ class RemoteConfigTemplateImpl { constructor(config) { if (!validator.isNonNullObject(config) || !validator.isNonEmptyString(config.etag)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config template: ${JSON.stringify(config)}`); } this.etagInternal = config.etag; if (typeof config.parameters !== 'undefined') { if (!validator.isNonNullObject(config.parameters)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameters must be a non-null object'); } this.parameters = config.parameters; } else { this.parameters = {}; } if (typeof config.parameterGroups !== 'undefined') { if (!validator.isNonNullObject(config.parameterGroups)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config parameter groups must be a non-null object'); } this.parameterGroups = config.parameterGroups; } else { this.parameterGroups = {}; } if (typeof config.conditions !== 'undefined') { if (!validator.isArray(config.conditions)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Remote Config conditions must be an array'); } this.conditions = config.conditions; } else { this.conditions = []; } if (typeof config.version !== 'undefined') { this.version = new VersionImpl(config.version); } } /** * Gets the ETag of the template. * * @returns The ETag of the Remote Config template. */ get etag() { return this.etagInternal; } /** * Returns a JSON-serializable representation of this object. * * @returns A JSON-serializable representation of this object. */ toJSON() { return { conditions: this.conditions, parameters: this.parameters, parameterGroups: this.parameterGroups, etag: this.etag, version: this.version, }; } } /** * Remote Config Version internal implementation. */ class VersionImpl { constructor(version) { if (!validator.isNonNullObject(version)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', `Invalid Remote Config version instance: ${JSON.stringify(version)}`); } if (typeof version.versionNumber !== 'undefined') { if (!validator.isNonEmptyString(version.versionNumber) && !validator.isNumber(version.versionNumber)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version number must be a non-empty string in int64 format or a number'); } if (!Number.isInteger(Number(version.versionNumber))) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version number must be an integer or a string in int64 format'); } this.versionNumber = version.versionNumber; } if (typeof version.updateOrigin !== 'undefined') { if (!validator.isNonEmptyString(version.updateOrigin)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update origin must be a non-empty string'); } this.updateOrigin = version.updateOrigin; } if (typeof version.updateType !== 'undefined') { if (!validator.isNonEmptyString(version.updateType)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update type must be a non-empty string'); } this.updateType = version.updateType; } if (typeof version.updateUser !== 'undefined') { if (!validator.isNonNullObject(version.updateUser)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update user must be a non-null object'); } this.updateUser = version.updateUser; } if (typeof version.description !== 'undefined') { if (!validator.isNonEmptyString(version.description)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version description must be a non-empty string'); } this.description = version.description; } if (typeof version.rollbackSource !== 'undefined') { if (!validator.isNonEmptyString(version.rollbackSource)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version rollback source must be a non-empty string'); } this.rollbackSource = version.rollbackSource; } if (typeof version.isLegacy !== 'undefined') { if (!validator.isBoolean(version.isLegacy)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version.isLegacy must be a boolean'); } this.isLegacy = version.isLegacy; } // The backend API provides timestamps in ISO date strings. The Admin SDK exposes timestamps // in UTC date strings. If a developer uses a previously obtained template with UTC timestamps // we could still validate it below. if (typeof version.updateTime !== 'undefined') { if (!this.isValidTimestamp(version.updateTime)) { throw new remote_config_api_client_internal_1.FirebaseRemoteConfigError('invalid-argument', 'Version update time must be a valid date string'); } this.updateTime = new Date(version.updateTime).toUTCString(); } } /** * @returns A JSON-serializable representation of this object. */ toJSON() { return { versionNumber: this.versionNumber, updateOrigin: this.updateOrigin, updateType: this.updateType, updateUser: this.updateUser, description: this.description, rollbackSource: this.rollbackSource, isLegacy: this.isLegacy, updateTime: this.updateTime, }; } isValidTimestamp(timestamp) { // This validation fails for timestamps earlier than January 1, 1970 and considers strings // such as "1.2" as valid timestamps. return validator.isNonEmptyString(timestamp) && (new Date(timestamp)).getTime() > 0; } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/remote-config/remote-config-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.validateMessage = exports.BLACKLISTED_OPTIONS_KEYS = exports.BLACKLISTED_DATA_PAYLOAD_KEYS = void 0; const index_1 = require("../utils/index"); const error_1 = require("../utils/error"); const validator = require("../utils/validator"); // Keys which are not allowed in the messaging data payload object. exports.BLACKLISTED_DATA_PAYLOAD_KEYS = ['from']; // Keys which are not allowed in the messaging options object. exports.BLACKLISTED_OPTIONS_KEYS = [ 'condition', 'data', 'notification', 'registrationIds', 'registration_ids', 'to', ]; /** * Checks if the given Message object is valid. Recursively validates all the child objects * included in the message (android, apns, data etc.). If successful, transforms the message * in place by renaming the keys to what's expected by the remote FCM service. * * @param {Message} Message An object to be validated. */ function validateMessage(message) { if (!validator.isNonNullObject(message)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Message must be a non-null object'); } const anyMessage = message; if (anyMessage.topic) { // If the topic name is prefixed, remove it. if (anyMessage.topic.startsWith('/topics/')) { anyMessage.topic = anyMessage.topic.replace(/^\/topics\//, ''); } // Checks for illegal characters and empty string. if (!/^[a-zA-Z0-9-_.~%]+$/.test(anyMessage.topic)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Malformed topic name'); } } const targets = [anyMessage.token, anyMessage.topic, anyMessage.condition]; if (targets.filter((v) => validator.isNonEmptyString(v)).length !== 1) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Exactly one of topic, token or condition is required'); } validateStringMap(message.data, 'data'); validateAndroidConfig(message.android); validateWebpushConfig(message.webpush); validateApnsConfig(message.apns); validateFcmOptions(message.fcmOptions); validateNotification(message.notification); } exports.validateMessage = validateMessage; /** * Checks if the given object only contains strings as child values. * * @param {object} map An object to be validated. * @param {string} label A label to be included in the errors thrown. */ function validateStringMap(map, label) { if (typeof map === 'undefined') { return; } else if (!validator.isNonNullObject(map)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `${label} must be a non-null object`); } Object.keys(map).forEach((key) => { if (!validator.isString(map[key])) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `${label} must only contain string values`); } }); } /** * Checks if the given WebpushConfig object is valid. The object must have valid headers and data. * * @param {WebpushConfig} config An object to be validated. */ function validateWebpushConfig(config) { if (typeof config === 'undefined') { return; } else if (!validator.isNonNullObject(config)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'webpush must be a non-null object'); } validateStringMap(config.headers, 'webpush.headers'); validateStringMap(config.data, 'webpush.data'); } /** * Checks if the given ApnsConfig object is valid. The object must have valid headers and a * payload. * * @param {ApnsConfig} config An object to be validated. */ function validateApnsConfig(config) { if (typeof config === 'undefined') { return; } else if (!validator.isNonNullObject(config)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns must be a non-null object'); } validateStringMap(config.headers, 'apns.headers'); validateApnsPayload(config.payload); validateApnsFcmOptions(config.fcmOptions); } /** * Checks if the given ApnsFcmOptions object is valid. * * @param {ApnsFcmOptions} fcmOptions An object to be validated. */ function validateApnsFcmOptions(fcmOptions) { if (typeof fcmOptions === 'undefined') { return; } else if (!validator.isNonNullObject(fcmOptions)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'fcmOptions must be a non-null object'); } if (typeof fcmOptions.imageUrl !== 'undefined' && !validator.isURL(fcmOptions.imageUrl)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'imageUrl must be a valid URL string'); } if (typeof fcmOptions.analyticsLabel !== 'undefined' && !validator.isString(fcmOptions.analyticsLabel)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'analyticsLabel must be a string value'); } const propertyMappings = { imageUrl: 'image', }; Object.keys(propertyMappings).forEach((key) => { if (key in fcmOptions && propertyMappings[key] in fcmOptions) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Multiple specifications for ${key} in ApnsFcmOptions`); } }); (0, index_1.renameProperties)(fcmOptions, propertyMappings); } /** * Checks if the given FcmOptions object is valid. * * @param {FcmOptions} fcmOptions An object to be validated. */ function validateFcmOptions(fcmOptions) { if (typeof fcmOptions === 'undefined') { return; } else if (!validator.isNonNullObject(fcmOptions)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'fcmOptions must be a non-null object'); } if (typeof fcmOptions.analyticsLabel !== 'undefined' && !validator.isString(fcmOptions.analyticsLabel)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'analyticsLabel must be a string value'); } } /** * Checks if the given Notification object is valid. * * @param {Notification} notification An object to be validated. */ function validateNotification(notification) { if (typeof notification === 'undefined') { return; } else if (!validator.isNonNullObject(notification)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'notification must be a non-null object'); } if (typeof notification.imageUrl !== 'undefined' && !validator.isURL(notification.imageUrl)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'notification.imageUrl must be a valid URL string'); } const propertyMappings = { imageUrl: 'image', }; Object.keys(propertyMappings).forEach((key) => { if (key in notification && propertyMappings[key] in notification) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Multiple specifications for ${key} in Notification`); } }); (0, index_1.renameProperties)(notification, propertyMappings); } /** * Checks if the given ApnsPayload object is valid. The object must have a valid aps value. * * @param {ApnsPayload} payload An object to be validated. */ function validateApnsPayload(payload) { if (typeof payload === 'undefined') { return; } else if (!validator.isNonNullObject(payload)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload must be a non-null object'); } validateAps(payload.aps); } /** * Checks if the given Aps object is valid. The object must have a valid alert. If the validation * is successful, transforms the input object by renaming the keys to valid APNS payload keys. * * @param {Aps} aps An object to be validated. */ function validateAps(aps) { if (typeof aps === 'undefined') { return; } else if (!validator.isNonNullObject(aps)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps must be a non-null object'); } validateApsAlert(aps.alert); validateApsSound(aps.sound); const propertyMappings = { contentAvailable: 'content-available', mutableContent: 'mutable-content', threadId: 'thread-id', }; Object.keys(propertyMappings).forEach((key) => { if (key in aps && propertyMappings[key] in aps) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Multiple specifications for ${key} in Aps`); } }); (0, index_1.renameProperties)(aps, propertyMappings); const contentAvailable = aps['content-available']; if (typeof contentAvailable !== 'undefined' && contentAvailable !== 1) { if (contentAvailable === true) { aps['content-available'] = 1; } else { delete aps['content-available']; } } const mutableContent = aps['mutable-content']; if (typeof mutableContent !== 'undefined' && mutableContent !== 1) { if (mutableContent === true) { aps['mutable-content'] = 1; } else { delete aps['mutable-content']; } } } function validateApsSound(sound) { if (typeof sound === 'undefined' || validator.isNonEmptyString(sound)) { return; } else if (!validator.isNonNullObject(sound)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound must be a non-empty string or a non-null object'); } if (!validator.isNonEmptyString(sound.name)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound.name must be a non-empty string'); } const volume = sound.volume; if (typeof volume !== 'undefined') { if (!validator.isNumber(volume)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound.volume must be a number'); } if (volume < 0 || volume > 1) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.sound.volume must be in the interval [0, 1]'); } } const soundObject = sound; const key = 'critical'; const critical = soundObject[key]; if (typeof critical !== 'undefined' && critical !== 1) { if (critical === true) { soundObject[key] = 1; } else { delete soundObject[key]; } } } /** * Checks if the given alert object is valid. Alert could be a string or a complex object. * If specified as an object, it must have valid localization parameters. If successful, transforms * the input object by renaming the keys to valid APNS payload keys. * * @param {string | ApsAlert} alert An alert string or an object to be validated. */ function validateApsAlert(alert) { if (typeof alert === 'undefined' || validator.isString(alert)) { return; } else if (!validator.isNonNullObject(alert)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert must be a string or a non-null object'); } const apsAlert = alert; if (validator.isNonEmptyArray(apsAlert.locArgs) && !validator.isNonEmptyString(apsAlert.locKey)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert.locKey is required when specifying locArgs'); } if (validator.isNonEmptyArray(apsAlert.titleLocArgs) && !validator.isNonEmptyString(apsAlert.titleLocKey)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert.titleLocKey is required when specifying titleLocArgs'); } if (validator.isNonEmptyArray(apsAlert.subtitleLocArgs) && !validator.isNonEmptyString(apsAlert.subtitleLocKey)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'apns.payload.aps.alert.subtitleLocKey is required when specifying subtitleLocArgs'); } const propertyMappings = { locKey: 'loc-key', locArgs: 'loc-args', titleLocKey: 'title-loc-key', titleLocArgs: 'title-loc-args', subtitleLocKey: 'subtitle-loc-key', subtitleLocArgs: 'subtitle-loc-args', actionLocKey: 'action-loc-key', launchImage: 'launch-image', }; (0, index_1.renameProperties)(apsAlert, propertyMappings); } /** * Checks if the given AndroidConfig object is valid. The object must have valid ttl, data, * and notification fields. If successful, transforms the input object by renaming keys to valid * Android keys. Also transforms the ttl value to the format expected by FCM service. * * @param config - An object to be validated. */ function validateAndroidConfig(config) { if (typeof config === 'undefined') { return; } else if (!validator.isNonNullObject(config)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android must be a non-null object'); } if (typeof config.ttl !== 'undefined') { if (!validator.isNumber(config.ttl) || config.ttl < 0) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'TTL must be a non-negative duration in milliseconds'); } const duration = (0, index_1.transformMillisecondsToSecondsString)(config.ttl); config.ttl = duration; } validateStringMap(config.data, 'android.data'); validateAndroidNotification(config.notification); validateAndroidFcmOptions(config.fcmOptions); const propertyMappings = { collapseKey: 'collapse_key', restrictedPackageName: 'restricted_package_name', }; (0, index_1.renameProperties)(config, propertyMappings); } /** * Checks if the given AndroidNotification object is valid. The object must have valid color and * localization parameters. If successful, transforms the input object by renaming keys to valid * Android keys. * * @param {AndroidNotification} notification An object to be validated. */ function validateAndroidNotification(notification) { if (typeof notification === 'undefined') { return; } else if (!validator.isNonNullObject(notification)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification must be a non-null object'); } if (typeof notification.color !== 'undefined' && !/^#[0-9a-fA-F]{6}$/.test(notification.color)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.color must be in the form #RRGGBB'); } if (validator.isNonEmptyArray(notification.bodyLocArgs) && !validator.isNonEmptyString(notification.bodyLocKey)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.bodyLocKey is required when specifying bodyLocArgs'); } if (validator.isNonEmptyArray(notification.titleLocArgs) && !validator.isNonEmptyString(notification.titleLocKey)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.titleLocKey is required when specifying titleLocArgs'); } if (typeof notification.imageUrl !== 'undefined' && !validator.isURL(notification.imageUrl)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.imageUrl must be a valid URL string'); } if (typeof notification.eventTimestamp !== 'undefined') { if (!(notification.eventTimestamp instanceof Date)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.eventTimestamp must be a valid `Date` object'); } // Convert timestamp to RFC3339 UTC "Zulu" format, example "2014-10-02T15:01:23.045123456Z" const zuluTimestamp = notification.eventTimestamp.toISOString(); notification.eventTimestamp = zuluTimestamp; } if (typeof notification.vibrateTimingsMillis !== 'undefined') { if (!validator.isNonEmptyArray(notification.vibrateTimingsMillis)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.vibrateTimingsMillis must be a non-empty array of numbers'); } const vibrateTimings = []; notification.vibrateTimingsMillis.forEach((value) => { if (!validator.isNumber(value) || value < 0) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.vibrateTimingsMillis must be non-negative durations in milliseconds'); } const duration = (0, index_1.transformMillisecondsToSecondsString)(value); vibrateTimings.push(duration); }); notification.vibrateTimingsMillis = vibrateTimings; } if (typeof notification.priority !== 'undefined') { const priority = 'PRIORITY_' + notification.priority.toUpperCase(); notification.priority = priority; } if (typeof notification.visibility !== 'undefined') { const visibility = notification.visibility.toUpperCase(); notification.visibility = visibility; } validateLightSettings(notification.lightSettings); const propertyMappings = { clickAction: 'click_action', bodyLocKey: 'body_loc_key', bodyLocArgs: 'body_loc_args', titleLocKey: 'title_loc_key', titleLocArgs: 'title_loc_args', channelId: 'channel_id', imageUrl: 'image', eventTimestamp: 'event_time', localOnly: 'local_only', priority: 'notification_priority', vibrateTimingsMillis: 'vibrate_timings', defaultVibrateTimings: 'default_vibrate_timings', defaultSound: 'default_sound', lightSettings: 'light_settings', defaultLightSettings: 'default_light_settings', notificationCount: 'notification_count', }; (0, index_1.renameProperties)(notification, propertyMappings); } /** * Checks if the given LightSettings object is valid. The object must have valid color and * light on/off duration parameters. If successful, transforms the input object by renaming * keys to valid Android keys. * * @param {LightSettings} lightSettings An object to be validated. */ function validateLightSettings(lightSettings) { if (typeof lightSettings === 'undefined') { return; } else if (!validator.isNonNullObject(lightSettings)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings must be a non-null object'); } if (!validator.isNumber(lightSettings.lightOnDurationMillis) || lightSettings.lightOnDurationMillis < 0) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings.lightOnDurationMillis must be a non-negative duration in milliseconds'); } const durationOn = (0, index_1.transformMillisecondsToSecondsString)(lightSettings.lightOnDurationMillis); lightSettings.lightOnDurationMillis = durationOn; if (!validator.isNumber(lightSettings.lightOffDurationMillis) || lightSettings.lightOffDurationMillis < 0) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings.lightOffDurationMillis must be a non-negative duration in milliseconds'); } const durationOff = (0, index_1.transformMillisecondsToSecondsString)(lightSettings.lightOffDurationMillis); lightSettings.lightOffDurationMillis = durationOff; if (!validator.isString(lightSettings.color) || (!/^#[0-9a-fA-F]{6}$/.test(lightSettings.color) && !/^#[0-9a-fA-F]{8}$/.test(lightSettings.color))) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'android.notification.lightSettings.color must be in the form #RRGGBB or #RRGGBBAA format'); } const colorString = lightSettings.color.length === 7 ? lightSettings.color + 'FF' : lightSettings.color; const rgb = /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/i.exec(colorString); if (!rgb || rgb.length < 4) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INTERNAL_ERROR, 'regex to extract rgba values from ' + colorString + ' failed.'); } const color = { red: parseInt(rgb[1], 16) / 255.0, green: parseInt(rgb[2], 16) / 255.0, blue: parseInt(rgb[3], 16) / 255.0, alpha: parseInt(rgb[4], 16) / 255.0, }; lightSettings.color = color; const propertyMappings = { lightOnDurationMillis: 'light_on_duration', lightOffDurationMillis: 'light_off_duration', }; (0, index_1.renameProperties)(lightSettings, propertyMappings); } /** * Checks if the given AndroidFcmOptions object is valid. * * @param {AndroidFcmOptions} fcmOptions An object to be validated. */ function validateAndroidFcmOptions(fcmOptions) { if (typeof fcmOptions === 'undefined') { return; } else if (!validator.isNonNullObject(fcmOptions)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'fcmOptions must be a non-null object'); } if (typeof fcmOptions.analyticsLabel !== 'undefined' && !validator.isString(fcmOptions.analyticsLabel)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'analyticsLabel must be a string value'); } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/batch-request-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/batch-request-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.BatchRequestClient = void 0; const api_request_1 = require("../utils/api-request"); const error_1 = require("../utils/error"); const PART_BOUNDARY = '__END_OF_PART__'; const TEN_SECONDS_IN_MILLIS = 10000; /** * An HTTP client that can be used to make batch requests. This client is not tied to any service * (FCM or otherwise). Therefore it can be used to make batch requests to any service that allows * it. If this requirement ever arises we can move this implementation to the utils module * where it can be easily shared among other modules. */ class BatchRequestClient { /** * @param {HttpClient} httpClient The client that will be used to make HTTP calls. * @param {string} batchUrl The URL that accepts batch requests. * @param {object=} commonHeaders Optional headers that will be included in all requests. * * @constructor */ constructor(httpClient, batchUrl, commonHeaders) { this.httpClient = httpClient; this.batchUrl = batchUrl; this.commonHeaders = commonHeaders; } /** * Sends the given array of sub requests as a single batch, and parses the results into an array * of HttpResponse objects. * * @param requests - An array of sub requests to send. * @returns A promise that resolves when the send operation is complete. */ send(requests) { requests = requests.map((req) => { req.headers = Object.assign({}, this.commonHeaders, req.headers); return req; }); const requestHeaders = { 'Content-Type': `multipart/mixed; boundary=${PART_BOUNDARY}`, }; const request = { method: 'POST', url: this.batchUrl, data: this.getMultipartPayload(requests), headers: Object.assign({}, this.commonHeaders, requestHeaders), timeout: TEN_SECONDS_IN_MILLIS, }; return this.httpClient.send(request).then((response) => { if (!response.multipart) { throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INTERNAL_ERROR, 'Expected a multipart response.'); } return response.multipart.map((buff) => { return (0, api_request_1.parseHttpResponse)(buff, request); }); }); } getMultipartPayload(requests) { let buffer = ''; requests.forEach((request, idx) => { buffer += createPart(request, PART_BOUNDARY, idx); }); buffer += `--${PART_BOUNDARY}--\r\n`; return Buffer.from(buffer, 'utf-8'); } } exports.BatchRequestClient = BatchRequestClient; /** * Creates a single part in a multipart HTTP request body. The part consists of several headers * followed by the serialized sub request as the body. As per the requirements of the FCM batch * API, sets the content-type header to application/http, and the content-transfer-encoding to * binary. * * @param request - A sub request that will be used to populate the part. * @param boundary - Multipart boundary string. * @param idx - An index number that is used to set the content-id header. * @returns The part as a string that can be included in the HTTP body. */ function createPart(request, boundary, idx) { const serializedRequest = serializeSubRequest(request); let part = `--${boundary}\r\n`; part += `Content-Length: ${serializedRequest.length}\r\n`; part += 'Content-Type: application/http\r\n'; part += `content-id: ${idx + 1}\r\n`; part += 'content-transfer-encoding: binary\r\n'; part += '\r\n'; part += `${serializedRequest}\r\n`; return part; } /** * Serializes a sub request into a string that can be embedded in a multipart HTTP request. The * format of the string is the wire format of a typical HTTP request, consisting of a header and a * body. * * @param request - The sub request to be serialized. * @returns String representation of the SubRequest. */ function serializeSubRequest(request) { const requestBody = JSON.stringify(request.body); let messagePayload = `POST ${request.url} HTTP/1.1\r\n`; messagePayload += `Content-Length: ${requestBody.length}\r\n`; messagePayload += 'Content-Type: application/json; charset=UTF-8\r\n'; if (request.headers) { Object.keys(request.headers).forEach((key) => { messagePayload += `${key}: ${request.headers[key]}\r\n`; }); } messagePayload += '\r\n'; messagePayload += requestBody; return messagePayload; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getMessaging = exports.Messaging = void 0; /** * Firebase Cloud Messaging (FCM). * * @packageDocumentation */ const app_1 = require("../app"); const messaging_1 = require("./messaging"); var messaging_2 = require("./messaging"); Object.defineProperty(exports, "Messaging", { enumerable: true, get: function () { return messaging_2.Messaging; } }); /** * Gets the {@link Messaging} service for the default app or a given app. * * `admin.messaging()` can be called with no arguments to access the default * app's `Messaging` service or as `admin.messaging(app)` to access the * `Messaging` service associated with aspecific app. * * @example * ```javascript * // Get the Messaging service for the default app * const defaultMessaging = getMessaging(); * ``` * * @example * ```javascript * // Get the Messaging service for a given app * const otherMessaging = getMessaging(otherApp); * ``` * * @param app - Optional app whose `Messaging` service to * return. If not provided, the default `Messaging` service will be returned. * * @returns The default `Messaging` service if no * app is provided or the `Messaging` service associated with the provided * app. */ function getMessaging(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('messaging', (app) => new messaging_1.Messaging(app)); } exports.getMessaging = getMessaging;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Messaging = void 0; const deep_copy_1 = require("../utils/deep-copy"); const error_1 = require("../utils/error"); const utils = require("../utils"); const validator = require("../utils/validator"); const messaging_internal_1 = require("./messaging-internal"); const messaging_api_request_internal_1 = require("./messaging-api-request-internal"); // FCM endpoints const FCM_SEND_HOST = 'fcm.googleapis.com'; const FCM_SEND_PATH = '/fcm/send'; const FCM_TOPIC_MANAGEMENT_HOST = 'iid.googleapis.com'; const FCM_TOPIC_MANAGEMENT_ADD_PATH = '/iid/v1:batchAdd'; const FCM_TOPIC_MANAGEMENT_REMOVE_PATH = '/iid/v1:batchRemove'; // Maximum messages that can be included in a batch request. const FCM_MAX_BATCH_SIZE = 500; // Key renames for the messaging notification payload object. const CAMELCASED_NOTIFICATION_PAYLOAD_KEYS_MAP = { bodyLocArgs: 'body_loc_args', bodyLocKey: 'body_loc_key', clickAction: 'click_action', titleLocArgs: 'title_loc_args', titleLocKey: 'title_loc_key', }; // Key renames for the messaging options object. const CAMELCASE_OPTIONS_KEYS_MAP = { dryRun: 'dry_run', timeToLive: 'time_to_live', collapseKey: 'collapse_key', mutableContent: 'mutable_content', contentAvailable: 'content_available', restrictedPackageName: 'restricted_package_name', }; // Key renames for the MessagingDeviceResult object. const MESSAGING_DEVICE_RESULT_KEYS_MAP = { message_id: 'messageId', registration_id: 'canonicalRegistrationToken', }; // Key renames for the MessagingDevicesResponse object. const MESSAGING_DEVICES_RESPONSE_KEYS_MAP = { canonical_ids: 'canonicalRegistrationTokenCount', failure: 'failureCount', success: 'successCount', multicast_id: 'multicastId', }; // Key renames for the MessagingDeviceGroupResponse object. const MESSAGING_DEVICE_GROUP_RESPONSE_KEYS_MAP = { success: 'successCount', failure: 'failureCount', failed_registration_ids: 'failedRegistrationTokens', }; // Key renames for the MessagingTopicResponse object. const MESSAGING_TOPIC_RESPONSE_KEYS_MAP = { message_id: 'messageId', }; // Key renames for the MessagingConditionResponse object. const MESSAGING_CONDITION_RESPONSE_KEYS_MAP = { message_id: 'messageId', }; /** * Maps a raw FCM server response to a MessagingDevicesResponse object. * * @param response - The raw FCM server response to map. * * @returns The mapped MessagingDevicesResponse object. */ function mapRawResponseToDevicesResponse(response) { // Rename properties on the server response utils.renameProperties(response, MESSAGING_DEVICES_RESPONSE_KEYS_MAP); if ('results' in response) { response.results.forEach((messagingDeviceResult) => { utils.renameProperties(messagingDeviceResult, MESSAGING_DEVICE_RESULT_KEYS_MAP); // Map the FCM server's error strings to actual error objects. if ('error' in messagingDeviceResult) { const newError = error_1.FirebaseMessagingError.fromServerError(messagingDeviceResult.error, /* message */ undefined, messagingDeviceResult.error); messagingDeviceResult.error = newError; } }); } return response; } /** * Maps a raw FCM server response to a MessagingDeviceGroupResponse object. * * @param response - The raw FCM server response to map. * * @returns The mapped MessagingDeviceGroupResponse object. */ function mapRawResponseToDeviceGroupResponse(response) { // Rename properties on the server response utils.renameProperties(response, MESSAGING_DEVICE_GROUP_RESPONSE_KEYS_MAP); // Add the 'failedRegistrationTokens' property if it does not exist on the response, which // it won't when the 'failureCount' property has a value of 0) response.failedRegistrationTokens = response.failedRegistrationTokens || []; return response; } /** * Maps a raw FCM server response to a MessagingTopicManagementResponse object. * * @param {object} response The raw FCM server response to map. * * @returns {MessagingTopicManagementResponse} The mapped MessagingTopicManagementResponse object. */ function mapRawResponseToTopicManagementResponse(response) { // Add the success and failure counts. const result = { successCount: 0, failureCount: 0, errors: [], }; if ('results' in response) { response.results.forEach((tokenManagementResult, index) => { // Map the FCM server's error strings to actual error objects. if ('error' in tokenManagementResult) { result.failureCount += 1; const newError = error_1.FirebaseMessagingError.fromTopicManagementServerError(tokenManagementResult.error, /* message */ undefined, tokenManagementResult.error); result.errors.push({ index, error: newError, }); } else { result.successCount += 1; } }); } return result; } /** * Messaging service bound to the provided app. */ class Messaging { /** * @internal */ constructor(app) { if (!validator.isNonNullObject(app) || !('options' in app)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'First argument passed to admin.messaging() must be a valid Firebase app instance.'); } this.appInternal = app; this.messagingRequestHandler = new messaging_api_request_internal_1.FirebaseMessagingRequestHandler(app); } /** * The {@link firebase-admin.app#App} associated with the current `Messaging` service * instance. * * @example * ```javascript * var app = messaging.app; * ``` */ get app() { return this.appInternal; } /** * Sends the given message via FCM. * * @param message - The message payload. * @param dryRun - Whether to send the message in the dry-run * (validation only) mode. * @returns A promise fulfilled with a unique message ID * string after the message has been successfully handed off to the FCM * service for delivery. */ send(message, dryRun) { const copy = (0, deep_copy_1.deepCopy)(message); (0, messaging_internal_1.validateMessage)(copy); if (typeof dryRun !== 'undefined' && !validator.isBoolean(dryRun)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'dryRun must be a boolean'); } return this.getUrlPath() .then((urlPath) => { const request = { message: copy }; if (dryRun) { request.validate_only = true; } return this.messagingRequestHandler.invokeRequestHandler(FCM_SEND_HOST, urlPath, request); }) .then((response) => { return response.name; }); } /** * Sends all the messages in the given array via Firebase Cloud Messaging. * Employs batching to send the entire list as a single RPC call. Compared * to the `send()` method, this method is a significantly more efficient way * to send multiple messages. * * The responses list obtained from the return value * corresponds to the order of tokens in the `MulticastMessage`. An error * from this method indicates a total failure -- i.e. none of the messages in * the list could be sent. Partial failures are indicated by a `BatchResponse` * return value. * * @param messages - A non-empty array * containing up to 500 messages. * @param dryRun - Whether to send the messages in the dry-run * (validation only) mode. * @returns A Promise fulfilled with an object representing the result of the * send operation. */ sendAll(messages, dryRun) { if (validator.isArray(messages) && messages.constructor !== Array) { // In more recent JS specs, an array-like object might have a constructor that is not of // Array type. Our deepCopy() method doesn't handle them properly. Convert such objects to // a regular array here before calling deepCopy(). See issue #566 for details. messages = Array.from(messages); } const copy = (0, deep_copy_1.deepCopy)(messages); if (!validator.isNonEmptyArray(copy)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'messages must be a non-empty array'); } if (copy.length > FCM_MAX_BATCH_SIZE) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, `messages list must not contain more than ${FCM_MAX_BATCH_SIZE} items`); } if (typeof dryRun !== 'undefined' && !validator.isBoolean(dryRun)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'dryRun must be a boolean'); } return this.getUrlPath() .then((urlPath) => { const requests = copy.map((message) => { (0, messaging_internal_1.validateMessage)(message); const request = { message }; if (dryRun) { request.validate_only = true; } return { url: `https://${FCM_SEND_HOST}${urlPath}`, body: request, }; }); return this.messagingRequestHandler.sendBatchRequest(requests); }); } /** * Sends the given multicast message to all the FCM registration tokens * specified in it. * * This method uses the `sendAll()` API under the hood to send the given * message to all the target recipients. The responses list obtained from the * return value corresponds to the order of tokens in the `MulticastMessage`. * An error from this method indicates a total failure -- i.e. the message was * not sent to any of the tokens in the list. Partial failures are indicated by * a `BatchResponse` return value. * * @param message - A multicast message * containing up to 500 tokens. * @param dryRun - Whether to send the message in the dry-run * (validation only) mode. * @returns A Promise fulfilled with an object representing the result of the * send operation. */ sendMulticast(message, dryRun) { const copy = (0, deep_copy_1.deepCopy)(message); if (!validator.isNonNullObject(copy)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'MulticastMessage must be a non-null object'); } if (!validator.isNonEmptyArray(copy.tokens)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'tokens must be a non-empty array'); } if (copy.tokens.length > FCM_MAX_BATCH_SIZE) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, `tokens list must not contain more than ${FCM_MAX_BATCH_SIZE} items`); } const messages = copy.tokens.map((token) => { return { token, android: copy.android, apns: copy.apns, data: copy.data, notification: copy.notification, webpush: copy.webpush, fcmOptions: copy.fcmOptions, }; }); return this.sendAll(messages, dryRun); } /** * Sends an FCM message to a single device corresponding to the provided * registration token. * * See {@link https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm#send_to_individual_devices | * Send to individual devices} * for code samples and detailed documentation. Takes either a * `registrationToken` to send to a single device or a * `registrationTokens` parameter containing an array of tokens to send * to multiple devices. * * @param registrationToken - A device registration token or an array of * device registration tokens to which the message should be sent. * @param payload - The message payload. * @param options - Optional options to * alter the message. * * @returns A promise fulfilled with the server's response after the message * has been sent. */ sendToDevice(registrationTokenOrTokens, payload, options = {}) { // Validate the input argument types. Since these are common developer errors when getting // started, throw an error instead of returning a rejected promise. this.validateRegistrationTokensType(registrationTokenOrTokens, 'sendToDevice', error_1.MessagingClientErrorCode.INVALID_RECIPIENT); this.validateMessagingPayloadAndOptionsTypes(payload, options); return Promise.resolve() .then(() => { // Validate the contents of the input arguments. Because we are now in a promise, any thrown // error will cause this method to return a rejected promise. this.validateRegistrationTokens(registrationTokenOrTokens, 'sendToDevice', error_1.MessagingClientErrorCode.INVALID_RECIPIENT); const payloadCopy = this.validateMessagingPayload(payload); const optionsCopy = this.validateMessagingOptions(options); const request = (0, deep_copy_1.deepCopy)(payloadCopy); (0, deep_copy_1.deepExtend)(request, optionsCopy); if (validator.isString(registrationTokenOrTokens)) { request.to = registrationTokenOrTokens; } else { request.registration_ids = registrationTokenOrTokens; } return this.messagingRequestHandler.invokeRequestHandler(FCM_SEND_HOST, FCM_SEND_PATH, request); }) .then((response) => { // The sendToDevice() and sendToDeviceGroup() methods both set the `to` query parameter in // the underlying FCM request. If the provided registration token argument is actually a // valid notification key, the response from the FCM server will be a device group response. // If that is the case, we map the response to a MessagingDeviceGroupResponse. // See b/35394951 for more context. if ('multicast_id' in response) { return mapRawResponseToDevicesResponse(response); } else { const groupResponse = mapRawResponseToDeviceGroupResponse(response); return { ...groupResponse, canonicalRegistrationTokenCount: -1, multicastId: -1, results: [], }; } }); } /** * Sends an FCM message to a device group corresponding to the provided * notification key. * * See {@link https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm#send_to_a_device_group | * Send to a device group} for code samples and detailed documentation. * * @param notificationKey - The notification key for the device group to * which to send the message. * @param payload - The message payload. * @param options - Optional options to * alter the message. * * @returns A promise fulfilled with the server's response after the message * has been sent. */ sendToDeviceGroup(notificationKey, payload, options = {}) { if (!validator.isNonEmptyString(notificationKey)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_RECIPIENT, 'Notification key provided to sendToDeviceGroup() must be a non-empty string.'); } else if (notificationKey.indexOf(':') !== -1) { // It is possible the developer provides a registration token instead of a notification key // to this method. We can detect some of those cases by checking to see if the string contains // a colon. Not all registration tokens will contain a colon (only newer ones will), but no // notification keys will contain a colon, so we can use it as a rough heuristic. // See b/35394951 for more context. return Promise.reject(new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_RECIPIENT, 'Notification key provided to sendToDeviceGroup() has the format of a registration token. ' + 'You should use sendToDevice() instead.')); } // Validate the types of the payload and options arguments. Since these are common developer // errors, throw an error instead of returning a rejected promise. this.validateMessagingPayloadAndOptionsTypes(payload, options); return Promise.resolve() .then(() => { // Validate the contents of the payload and options objects. Because we are now in a // promise, any thrown error will cause this method to return a rejected promise. const payloadCopy = this.validateMessagingPayload(payload); const optionsCopy = this.validateMessagingOptions(options); const request = (0, deep_copy_1.deepCopy)(payloadCopy); (0, deep_copy_1.deepExtend)(request, optionsCopy); request.to = notificationKey; return this.messagingRequestHandler.invokeRequestHandler(FCM_SEND_HOST, FCM_SEND_PATH, request); }) .then((response) => { // The sendToDevice() and sendToDeviceGroup() methods both set the `to` query parameter in // the underlying FCM request. If the provided notification key argument has an invalid // format (that is, it is either a registration token or some random string), the response // from the FCM server will default to a devices response (which we detect by looking for // the `multicast_id` property). If that is the case, we either throw an error saying the // provided notification key is invalid (if the message failed to send) or map the response // to a MessagingDevicesResponse (if the message succeeded). // See b/35394951 for more context. if ('multicast_id' in response) { if (response.success === 0) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_RECIPIENT, 'Notification key provided to sendToDeviceGroup() is invalid.'); } else { const devicesResponse = mapRawResponseToDevicesResponse(response); return { ...devicesResponse, failedRegistrationTokens: [], }; } } return mapRawResponseToDeviceGroupResponse(response); }); } /** * Sends an FCM message to a topic. * * See {@link https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm#send_to_a_topic | * Send to a topic} for code samples and detailed documentation. * * @param topic - The topic to which to send the message. * @param payload - The message payload. * @param options - Optional options to * alter the message. * * @returns A promise fulfilled with the server's response after the message * has been sent. */ sendToTopic(topic, payload, options = {}) { // Validate the input argument types. Since these are common developer errors when getting // started, throw an error instead of returning a rejected promise. this.validateTopicType(topic, 'sendToTopic', error_1.MessagingClientErrorCode.INVALID_RECIPIENT); this.validateMessagingPayloadAndOptionsTypes(payload, options); // Prepend the topic with /topics/ if necessary. topic = this.normalizeTopic(topic); return Promise.resolve() .then(() => { // Validate the contents of the payload and options objects. Because we are now in a // promise, any thrown error will cause this method to return a rejected promise. const payloadCopy = this.validateMessagingPayload(payload); const optionsCopy = this.validateMessagingOptions(options); this.validateTopic(topic, 'sendToTopic', error_1.MessagingClientErrorCode.INVALID_RECIPIENT); const request = (0, deep_copy_1.deepCopy)(payloadCopy); (0, deep_copy_1.deepExtend)(request, optionsCopy); request.to = topic; return this.messagingRequestHandler.invokeRequestHandler(FCM_SEND_HOST, FCM_SEND_PATH, request); }) .then((response) => { // Rename properties on the server response utils.renameProperties(response, MESSAGING_TOPIC_RESPONSE_KEYS_MAP); return response; }); } /** * Sends an FCM message to a condition. * * See {@link https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm#send_to_a_condition | * Send to a condition} * for code samples and detailed documentation. * * @param condition - The condition determining to which topics to send * the message. * @param payload - The message payload. * @param options - Optional options to * alter the message. * * @returns A promise fulfilled with the server's response after the message * has been sent. */ sendToCondition(condition, payload, options = {}) { if (!validator.isNonEmptyString(condition)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_RECIPIENT, 'Condition provided to sendToCondition() must be a non-empty string.'); } // Validate the types of the payload and options arguments. Since these are common developer // errors, throw an error instead of returning a rejected promise. this.validateMessagingPayloadAndOptionsTypes(payload, options); // The FCM server rejects conditions which are surrounded in single quotes. When the condition // is stringified over the wire, double quotes in it get converted to \" which the FCM server // does not properly handle. We can get around this by replacing internal double quotes with // single quotes. condition = condition.replace(/"/g, '\''); return Promise.resolve() .then(() => { // Validate the contents of the payload and options objects. Because we are now in a // promise, any thrown error will cause this method to return a rejected promise. const payloadCopy = this.validateMessagingPayload(payload); const optionsCopy = this.validateMessagingOptions(options); const request = (0, deep_copy_1.deepCopy)(payloadCopy); (0, deep_copy_1.deepExtend)(request, optionsCopy); request.condition = condition; return this.messagingRequestHandler.invokeRequestHandler(FCM_SEND_HOST, FCM_SEND_PATH, request); }) .then((response) => { // Rename properties on the server response utils.renameProperties(response, MESSAGING_CONDITION_RESPONSE_KEYS_MAP); return response; }); } /** * Subscribes a device to an FCM topic. * * See {@link https://firebase.google.com/docs/cloud-messaging/manage-topics#suscribe_and_unsubscribe_using_the | * Subscribe to a topic} * for code samples and detailed documentation. Optionally, you can provide an * array of tokens to subscribe multiple devices. * * @param registrationTokens - A token or array of registration tokens * for the devices to subscribe to the topic. * @param topic - The topic to which to subscribe. * * @returns A promise fulfilled with the server's response after the device has been * subscribed to the topic. */ subscribeToTopic(registrationTokenOrTokens, topic) { return this.sendTopicManagementRequest(registrationTokenOrTokens, topic, 'subscribeToTopic', FCM_TOPIC_MANAGEMENT_ADD_PATH); } /** * Unsubscribes a device from an FCM topic. * * See {@link https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#unsubscribe_from_a_topic | * Unsubscribe from a topic} * for code samples and detailed documentation. Optionally, you can provide an * array of tokens to unsubscribe multiple devices. * * @param registrationTokens - A device registration token or an array of * device registration tokens to unsubscribe from the topic. * @param topic - The topic from which to unsubscribe. * * @returns A promise fulfilled with the server's response after the device has been * unsubscribed from the topic. */ unsubscribeFromTopic(registrationTokenOrTokens, topic) { return this.sendTopicManagementRequest(registrationTokenOrTokens, topic, 'unsubscribeFromTopic', FCM_TOPIC_MANAGEMENT_REMOVE_PATH); } getUrlPath() { if (this.urlPath) { return Promise.resolve(this.urlPath); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { // Assert for an explicit project ID (either via AppOptions or the cert itself). throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_ARGUMENT, 'Failed to determine project ID for Messaging. Initialize the ' + 'SDK with service account credentials or set project ID as an app option. ' + 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.'); } this.urlPath = `/v1/projects/${projectId}/messages:send`; return this.urlPath; }); } /** * Helper method which sends and handles topic subscription management requests. * * @param registrationTokenOrTokens - The registration token or an array of * registration tokens to unsubscribe from the topic. * @param topic - The topic to which to subscribe. * @param methodName - The name of the original method called. * @param path - The endpoint path to use for the request. * * @returns A Promise fulfilled with the parsed server * response. */ sendTopicManagementRequest(registrationTokenOrTokens, topic, methodName, path) { this.validateRegistrationTokensType(registrationTokenOrTokens, methodName); this.validateTopicType(topic, methodName); // Prepend the topic with /topics/ if necessary. topic = this.normalizeTopic(topic); return Promise.resolve() .then(() => { // Validate the contents of the input arguments. Because we are now in a promise, any thrown // error will cause this method to return a rejected promise. this.validateRegistrationTokens(registrationTokenOrTokens, methodName); this.validateTopic(topic, methodName); // Ensure the registration token(s) input argument is an array. let registrationTokensArray = registrationTokenOrTokens; if (validator.isString(registrationTokenOrTokens)) { registrationTokensArray = [registrationTokenOrTokens]; } const request = { to: topic, registration_tokens: registrationTokensArray, }; return this.messagingRequestHandler.invokeRequestHandler(FCM_TOPIC_MANAGEMENT_HOST, path, request); }) .then((response) => { return mapRawResponseToTopicManagementResponse(response); }); } /** * Validates the types of the messaging payload and options. If invalid, an error will be thrown. * * @param payload - The messaging payload to validate. * @param options - The messaging options to validate. */ validateMessagingPayloadAndOptionsTypes(payload, options) { // Validate the payload is an object if (!validator.isNonNullObject(payload)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Messaging payload must be an object with at least one of the "data" or "notification" properties.'); } // Validate the options argument is an object if (!validator.isNonNullObject(options)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_OPTIONS, 'Messaging options must be an object.'); } } /** * Validates the messaging payload. If invalid, an error will be thrown. * * @param payload - The messaging payload to validate. * * @returns A copy of the provided payload with whitelisted properties switched * from camelCase to underscore_case. */ validateMessagingPayload(payload) { const payloadCopy = (0, deep_copy_1.deepCopy)(payload); const payloadKeys = Object.keys(payloadCopy); const validPayloadKeys = ['data', 'notification']; let containsDataOrNotificationKey = false; payloadKeys.forEach((payloadKey) => { // Validate the payload does not contain any invalid keys if (validPayloadKeys.indexOf(payloadKey) === -1) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Messaging payload contains an invalid "${payloadKey}" property. Valid properties are ` + '"data" and "notification".'); } else { containsDataOrNotificationKey = true; } }); // Validate the payload contains at least one of the "data" and "notification" keys if (!containsDataOrNotificationKey) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, 'Messaging payload must contain at least one of the "data" or "notification" properties.'); } const validatePayload = (payloadKey, value) => { // Validate each top-level key in the payload is an object if (!validator.isNonNullObject(value)) { throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Messaging payload contains an invalid value for the "${payloadKey}" property. ` + 'Value must be an object.'); } Object.keys(value).forEach((subKey) => { if (!validator.isString(value[subKey])) { // Validate all sub-keys have a string value throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Messaging payload contains an invalid value for the "${payloadKey}.${subKey}" ` + 'property. Values must be strings.'); } else if (payloadKey === 'data' && /^google\./.test(subKey)) { // Validate the data payload does not contain keys which start with 'google.'. throw new error_1.FirebaseMessagingError(error_1.MessagingClientErrorCode.INVALID_PAYLOAD, `Messaging payload contains the blacklisted "data.${subKey}" property.`); } }); }; if (payloadCopy.data !== undefined) { validatePayload('data', payloadCopy.data); } if (payloadCopy.notification !== undefined) { validatePayload('notification', payloadCopy.notification); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebaseMessagingRequestHandler = void 0; const api_request_1 = require("../utils/api-request"); const messaging_errors_internal_1 = require("./messaging-errors-internal"); const batch_request_internal_1 = require("./batch-request-internal"); const index_1 = require("../utils/index"); // FCM backend constants const FIREBASE_MESSAGING_TIMEOUT = 10000; const FIREBASE_MESSAGING_BATCH_URL = 'https://fcm.googleapis.com/batch'; const FIREBASE_MESSAGING_HTTP_METHOD = 'POST'; const FIREBASE_MESSAGING_HEADERS = { 'X-Firebase-Client': `fire-admin-node/${(0, index_1.getSdkVersion)()}`, }; const LEGACY_FIREBASE_MESSAGING_HEADERS = { 'X-Firebase-Client': `fire-admin-node/${(0, index_1.getSdkVersion)()}`, 'access_token_auth': 'true', }; /** * Class that provides a mechanism to send requests to the Firebase Cloud Messaging backend. */ class FirebaseMessagingRequestHandler { /** * @param app - The app used to fetch access tokens to sign API requests. * @constructor */ constructor(app) { this.httpClient = new api_request_1.AuthorizedHttpClient(app); this.batchClient = new batch_request_internal_1.BatchRequestClient(this.httpClient, FIREBASE_MESSAGING_BATCH_URL, FIREBASE_MESSAGING_HEADERS); } /** * Invokes the request handler with the provided request data. * * @param host - The host to which to send the request. * @param path - The path to which to send the request. * @param requestData - The request data. * @returns A promise that resolves with the response. */ invokeRequestHandler(host, path, requestData) { const request = { method: FIREBASE_MESSAGING_HTTP_METHOD, url: `https://${host}${path}`, data: requestData, headers: LEGACY_FIREBASE_MESSAGING_HEADERS, timeout: FIREBASE_MESSAGING_TIMEOUT, }; return this.httpClient.send(request).then((response) => { // Send non-JSON responses to the catch() below where they will be treated as errors. if (!response.isJson()) { throw new api_request_1.HttpError(response); } // Check for backend errors in the response. const errorCode = (0, messaging_errors_internal_1.getErrorCode)(response.data); if (errorCode) { throw new api_request_1.HttpError(response); } // Return entire response. return response.data; }) .catch((err) => { if (err instanceof api_request_1.HttpError) { throw (0, messaging_errors_internal_1.createFirebaseError)(err); } // Re-throw the error if it already has the proper format. throw err; }); } /** * Sends the given array of sub requests as a single batch to FCM, and parses the result into * a BatchResponse object. * * @param requests - An array of sub requests to send. * @returns A promise that resolves when the send operation is complete. */ sendBatchRequest(requests) { return this.batchClient.send(requests) .then((responses) => { return responses.map((part) => { return this.buildSendResponse(part); }); }).then((responses) => { const successCount = responses.filter((resp) => resp.success).length; return { responses, successCount, failureCount: responses.length - successCount, }; }).catch((err) => { if (err instanceof api_request_1.HttpError) { throw (0, messaging_errors_internal_1.createFirebaseError)(err); } // Re-throw the error if it already has the proper format. throw err; }); } buildSendResponse(response) { const result = { success: response.status === 200, }; if (result.success) { result.messageId = response.data.name; } else { result.error = (0, messaging_errors_internal_1.createFirebaseError)(new api_request_1.HttpError(response)); } return result; } } exports.FirebaseMessagingRequestHandler = FirebaseMessagingRequestHandler;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-api.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-api.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getErrorCode = exports.createFirebaseError = void 0; const error_1 = require("../utils/error"); const validator = require("../utils/validator"); /** * Creates a new FirebaseMessagingError by extracting the error code, message and other relevant * details from an HTTP error response. * * @param err - The HttpError to convert into a Firebase error * @returns A Firebase error that can be returned to the user. */ function createFirebaseError(err) { if (err.response.isJson()) { // For JSON responses, map the server response to a client-side error. const json = err.response.data; const errorCode = getErrorCode(json); const errorMessage = getErrorMessage(json); return error_1.FirebaseMessagingError.fromServerError(errorCode, errorMessage, json); } // Non-JSON response let error; switch (err.response.status) { case 400: error = error_1.MessagingClientErrorCode.INVALID_ARGUMENT; break; case 401: case 403: error = error_1.MessagingClientErrorCode.AUTHENTICATION_ERROR; break; case 500: error = error_1.MessagingClientErrorCode.INTERNAL_ERROR; break; case 503: error = error_1.MessagingClientErrorCode.SERVER_UNAVAILABLE; break; default: // Treat non-JSON responses with unexpected status codes as unknown errors. error = error_1.MessagingClientErrorCode.UNKNOWN_ERROR; } return new error_1.FirebaseMessagingError({ code: error.code, message: `${error.message} Raw server response: "${err.response.text}". Status code: ` + `${err.response.status}.`, }); } exports.createFirebaseError = createFirebaseError; /** * @param response - The response to check for errors. * @returns The error code if present; null otherwise. */ function getErrorCode(response) { if (validator.isNonNullObject(response) && 'error' in response) { const error = response.error; if (validator.isString(error)) { return error; } if (validator.isArray(error.details)) { const fcmErrorType = 'type.googleapis.com/google.firebase.fcm.v1.FcmError'; for (const element of error.details) { if (element['@type'] === fcmErrorType) { return element.errorCode; } } } if ('status' in error) { return error.status; } else { return error.message; } } return null; } exports.getErrorCode = getErrorCode; /** * Extracts error message from the given response object. * * @param response - The response to check for errors. * @returns The error message if present; null otherwise. */ function getErrorMessage(response) { if (validator.isNonNullObject(response) && 'error' in response && validator.isNonEmptyString(response.error.message)) { return response.error.message; } return null; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getEventarc = exports.Channel = exports.Eventarc = void 0; /** * Firebase Eventarc. * * @packageDocumentation */ const app_1 = require("../app"); const eventarc_1 = require("./eventarc"); var eventarc_2 = require("./eventarc"); Object.defineProperty(exports, "Eventarc", { enumerable: true, get: function () { return eventarc_2.Eventarc; } }); Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return eventarc_2.Channel; } }); /** * Gets the {@link Eventarc} service for the default app or a given app. * * `getEventarc()` can be called with no arguments to access the default * app's `Eventarc` service or as `getEventarc(app)` to access the * `Eventarc` service associated with specific app. * * @example * ```javascript * // Get the Eventarc service for the default app * const defaultEventarc = getEventarc(); * ``` * * @example * ```javascript * // Get the Eventarc service for a given app * const otherEventarc = getEventarc(otherApp); * ``` * * @param app - Optional app whose `Eventarc` service will be returned. * If not provided, the default `Eventarc` service will be returned. * * @returns The default `Eventarc` service if no * app is provided or the `Eventarc` service associated with the provided * app. */ function getEventarc(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('eventarc', (app) => new eventarc_1.Eventarc(app)); } exports.getEventarc = getEventarc;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/eventarc.js
aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/eventarc.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Channel = exports.Eventarc = void 0; const validator = require("../utils/validator"); const eventarc_utils_1 = require("./eventarc-utils"); const eventarc_client_internal_1 = require("./eventarc-client-internal"); /** * Eventarc service bound to the provided app. */ class Eventarc { /** * @internal */ constructor(app) { if (!validator.isNonNullObject(app) || !('options' in app)) { throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Eventarc() must be a valid Firebase app instance.'); } this.appInternal = app; } /** * The {@link firebase-admin.app#App} associated with the current Eventarc service * instance. * * @example * ```javascript * var app = eventarc.app; * ``` */ get app() { return this.appInternal; } channel(nameOrOptions, options) { let channel; let opts; if (validator.isNonEmptyString(nameOrOptions)) { channel = nameOrOptions; } else { channel = 'locations/us-central1/channels/firebase'; } if (validator.isNonNullObject(nameOrOptions)) { opts = nameOrOptions; } else { opts = options; } let allowedEventTypes = undefined; if (typeof opts?.allowedEventTypes === 'string') { allowedEventTypes = opts.allowedEventTypes.split(','); } else if (validator.isArray(opts?.allowedEventTypes)) { allowedEventTypes = opts?.allowedEventTypes; } else if (typeof opts?.allowedEventTypes !== 'undefined') { throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'AllowedEventTypes must be either an array of strings or a comma separated string.'); } return new Channel(this, channel, allowedEventTypes); } } exports.Eventarc = Eventarc; /** * Eventarc Channel. */ class Channel { /** * @internal */ constructor(eventarc, name, allowedEventTypes) { if (!validator.isNonNullObject(eventarc)) { throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Channel() must be a valid Eventarc service instance.'); } if (!validator.isNonEmptyString(name)) { throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'name is required.'); } this.nameInternal = name; this.eventarcInternal = eventarc; this.allowedEventTypes = allowedEventTypes; this.client = new eventarc_client_internal_1.EventarcApiClient(eventarc.app, this); } /** * The {@link firebase-admin.eventarc#Eventarc} service instance associated with the current `Channel`. * * @example * ```javascript * var app = channel.eventarc; * ``` */ get eventarc() { return this.eventarcInternal; } /** * The channel name as provided during channel creation. If it was not specifed, the default channel name is returned * ('locations/us-central1/channels/firebase'). */ get name() { return this.nameInternal; } /** * Publishes provided events to this channel. If channel was created with `allowedEventTypes` and event type is not * on that list, the event is ignored. * * @param events - CloudEvent to publish to the channel. */ publish(events) { return this.client.publish(events); } } exports.Channel = Channel;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/cloudevent.js
aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/cloudevent.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/eventarc-client-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.EventarcApiClient = void 0; const validator = require("../utils/validator"); const eventarc_utils_1 = require("./eventarc-utils"); const api_request_1 = require("../utils/api-request"); const utils = require("../utils"); const error_1 = require("../utils/error"); const EVENTARC_API = 'https://eventarcpublishing.googleapis.com/v1'; const FIREBASE_VERSION_HEADER = { 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, }; const CHANNEL_NAME_REGEX = /^(projects\/([^/]+)\/)?locations\/([^/]+)\/channels\/([^/]+)$/; const DEFAULT_CHANNEL_REGION = 'us-central1'; /** * Class that facilitates sending requests to the Eventarc backend API. * * @internal */ class EventarcApiClient { constructor(app, channel) { this.app = app; this.channel = channel; if (!validator.isNonNullObject(app) || !('options' in app)) { throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Channel() must be a valid Eventarc service instance.'); } this.httpClient = new api_request_1.AuthorizedHttpClient(app); this.resolvedChannelName = this.resolveChannelName(channel.name); } getProjectId() { if (this.projectId) { return Promise.resolve(this.projectId); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new eventarc_utils_1.FirebaseEventarcError('unknown-error', 'Failed to determine project ID. Initialize the ' + 'SDK with service account credentials or set project ID as an app option. ' + 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.'); } this.projectId = projectId; return projectId; }); } /** * Publishes provided events to this channel. If channel was created with `allowedEventsTypes` and event type * is not on that list, the event is ignored. * * The following CloudEvent fields are auto-populated if not set: * * specversion - `1.0` * * id - uuidv4() * * source - populated with `process.env.EVENTARC_CLOUD_EVENT_SOURCE` and * if not set an error is thrown. * * @param events - CloudEvent to publish to the channel. */ async publish(events) { if (!Array.isArray(events)) { events = [events]; } return this.publishToEventarcApi(await this.resolvedChannelName, events .filter(e => typeof this.channel.allowedEventTypes === 'undefined' || this.channel.allowedEventTypes.includes(e.type)) .map(eventarc_utils_1.toCloudEventProtoFormat)); } async publishToEventarcApi(channel, events) { if (events.length === 0) { return; } const request = { method: 'POST', url: `${this.getEventarcHost()}/${channel}:publishEvents`, data: JSON.stringify({ events }), }; return this.sendRequest(request); } sendRequest(request) { request.headers = FIREBASE_VERSION_HEADER; return this.httpClient.send(request) .then(() => undefined) .catch((err) => { throw this.toFirebaseError(err); }); } toFirebaseError(err) { if (err instanceof error_1.PrefixedFirebaseError) { return err; } const response = err.response; return new eventarc_utils_1.FirebaseEventarcError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); } resolveChannelName(name) { if (!name.includes('/')) { const location = DEFAULT_CHANNEL_REGION; const channelId = name; return this.resolveChannelNameProjectId(location, channelId); } else { const match = CHANNEL_NAME_REGEX.exec(name); if (match === null || match.length < 4) { throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'Invalid channel name format.'); } const projectId = match[2]; const location = match[3]; const channelId = match[4]; if (validator.isNonEmptyString(projectId)) { return Promise.resolve(`projects/${projectId}/locations/${location}/channels/${channelId}`); } else { return this.resolveChannelNameProjectId(location, channelId); } } } async resolveChannelNameProjectId(location, channelId) { const projectId = await this.getProjectId(); return `projects/${projectId}/locations/${location}/channels/${channelId}`; } getEventarcHost() { return process.env.CLOUD_EVENTARC_EMULATOR_HOST ?? EVENTARC_API; } } exports.EventarcApiClient = EventarcApiClient;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/eventarc-utils.js
aws/lti-middleware/node_modules/firebase-admin/lib/eventarc/eventarc-utils.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * @license * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.toCloudEventProtoFormat = exports.FirebaseEventarcError = void 0; const error_1 = require("../utils/error"); const uuid_1 = require("uuid"); const validator = require("../utils/validator"); // List of CloudEvent properties that are handled "by hand" and should be skipped by // automatic attribute copy. const TOP_LEVEL_CE_ATTRS = ['id', 'type', 'specversion', 'source', 'data', 'time', 'datacontenttype', 'subject']; /** * Firebase Eventarc error code structure. This extends PrefixedFirebaseError. * * @param code - The error code. * @param message - The error message. * @constructor */ class FirebaseEventarcError extends error_1.PrefixedFirebaseError { constructor(code, message) { super('eventarc', code, message); } } exports.FirebaseEventarcError = FirebaseEventarcError; function toCloudEventProtoFormat(ce) { const source = ce.source ?? process.env.EVENTARC_CLOUD_EVENT_SOURCE; if (typeof source === 'undefined' || !validator.isNonEmptyString(source)) { throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'source' is required."); } if (!validator.isNonEmptyString(ce.type)) { throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'type' is required."); } const out = { '@type': 'type.googleapis.com/io.cloudevents.v1.CloudEvent', 'id': ce.id ?? (0, uuid_1.v4)(), 'type': ce.type, 'specVersion': ce.specversion ?? '1.0', 'source': source }; if (typeof ce.time !== 'undefined') { if (!validator.isISODateString(ce.time)) { throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'tyme' must be in ISO date format."); } setAttribute(out, 'time', { 'ceTimestamp': ce.time }); } else { setAttribute(out, 'time', { 'ceTimestamp': new Date().toISOString() }); } if (typeof ce.datacontenttype !== 'undefined') { if (!validator.isNonEmptyString(ce.datacontenttype)) { throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'datacontenttype' if specified must be non-empty string."); } setAttribute(out, 'datacontenttype', { 'ceString': ce.datacontenttype }); } if (ce.subject) { if (!validator.isNonEmptyString(ce.subject)) { throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'subject' if specified must be non-empty string."); } setAttribute(out, 'subject', { 'ceString': ce.subject }); } if (typeof ce.data === 'undefined') { throw new FirebaseEventarcError('invalid-argument', "CloudEvent 'data' is required."); } if (validator.isObject(ce.data)) { out['textData'] = JSON.stringify(ce.data); if (!ce.datacontenttype) { setAttribute(out, 'datacontenttype', { 'ceString': 'application/json' }); } } else if (validator.isNonEmptyString(ce.data)) { out['textData'] = ce.data; if (!ce.datacontenttype) { setAttribute(out, 'datacontenttype', { 'ceString': 'text/plain' }); } } else { throw new FirebaseEventarcError('invalid-argument', `CloudEvent 'data' must be string or an object (which are converted to JSON), got '${typeof ce.data}'.`); } for (const attr in ce) { if (TOP_LEVEL_CE_ATTRS.includes(attr)) { continue; } if (!validator.isNonEmptyString(ce[attr])) { throw new FirebaseEventarcError('invalid-argument', `CloudEvent extension attributes ('${attr}') must be string.`); } setAttribute(out, attr, { 'ceString': ce[attr] }); } return out; } exports.toCloudEventProtoFormat = toCloudEventProtoFormat; function setAttribute(event, attr, value) { if (!Object.prototype.hasOwnProperty.call(event, 'attributes')) { event.attributes = {}; } event['attributes'][attr] = value; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules-api-client-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.SecurityRulesApiClient = void 0; const api_request_1 = require("../utils/api-request"); const error_1 = require("../utils/error"); const security_rules_internal_1 = require("./security-rules-internal"); const utils = require("../utils/index"); const validator = require("../utils/validator"); const RULES_V1_API = 'https://firebaserules.googleapis.com/v1'; const FIREBASE_VERSION_HEADER = { 'X-Firebase-Client': `fire-admin-node/${utils.getSdkVersion()}`, }; /** * Class that facilitates sending requests to the Firebase security rules backend API. * * @private */ class SecurityRulesApiClient { constructor(app) { this.app = app; if (!validator.isNonNullObject(app) || !('options' in app)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'First argument passed to admin.securityRules() must be a valid Firebase app ' + 'instance.'); } this.httpClient = new api_request_1.AuthorizedHttpClient(app); } getRuleset(name) { return Promise.resolve() .then(() => { return this.getRulesetName(name); }) .then((rulesetName) => { return this.getResource(rulesetName); }); } createRuleset(ruleset) { if (!validator.isNonNullObject(ruleset) || !validator.isNonNullObject(ruleset.source) || !validator.isNonEmptyArray(ruleset.source.files)) { const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Invalid rules content.'); return Promise.reject(err); } for (const rf of ruleset.source.files) { if (!validator.isNonNullObject(rf) || !validator.isNonEmptyString(rf.name) || !validator.isNonEmptyString(rf.content)) { const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', `Invalid rules file argument: ${JSON.stringify(rf)}`); return Promise.reject(err); } } return this.getUrl() .then((url) => { const request = { method: 'POST', url: `${url}/rulesets`, data: ruleset, }; return this.sendRequest(request); }); } deleteRuleset(name) { return this.getUrl() .then((url) => { const rulesetName = this.getRulesetName(name); const request = { method: 'DELETE', url: `${url}/${rulesetName}`, }; return this.sendRequest(request); }); } listRulesets(pageSize = 100, pageToken) { if (!validator.isNumber(pageSize)) { const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Invalid page size.'); return Promise.reject(err); } if (pageSize < 1 || pageSize > 100) { const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Page size must be between 1 and 100.'); return Promise.reject(err); } if (typeof pageToken !== 'undefined' && !validator.isNonEmptyString(pageToken)) { const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Next page token must be a non-empty string.'); return Promise.reject(err); } const data = { pageSize, pageToken, }; if (!pageToken) { delete data.pageToken; } return this.getUrl() .then((url) => { const request = { method: 'GET', url: `${url}/rulesets`, data, }; return this.sendRequest(request); }); } getRelease(name) { return this.getResource(`releases/${name}`); } updateRelease(name, rulesetName) { return this.getUrl() .then((url) => { return this.getReleaseDescription(name, rulesetName) .then((release) => { const request = { method: 'PATCH', url: `${url}/releases/${name}`, data: { release }, }; return this.sendRequest(request); }); }); } getUrl() { return this.getProjectIdPrefix() .then((projectIdPrefix) => { return `${RULES_V1_API}/${projectIdPrefix}`; }); } getProjectIdPrefix() { if (this.projectIdPrefix) { return Promise.resolve(this.projectIdPrefix); } return utils.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' + 'environment variable.'); } this.projectIdPrefix = `projects/${projectId}`; return this.projectIdPrefix; }); } /** * Gets the specified resource from the rules API. Resource names must be the short names without project * ID prefix (e.g. `rulesets/ruleset-name`). * * @param {string} name Full qualified name of the resource to get. * @returns {Promise<T>} A promise that fulfills with the resource. */ getResource(name) { return this.getUrl() .then((url) => { const request = { method: 'GET', url: `${url}/${name}`, }; return this.sendRequest(request); }); } getReleaseDescription(name, rulesetName) { return this.getProjectIdPrefix() .then((projectIdPrefix) => { return { name: `${projectIdPrefix}/releases/${name}`, rulesetName: `${projectIdPrefix}/${this.getRulesetName(rulesetName)}`, }; }); } getRulesetName(name) { if (!validator.isNonEmptyString(name)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Ruleset name must be a non-empty string.'); } if (name.indexOf('/') !== -1) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Ruleset name must not contain any "/" characters.'); } return `rulesets/${name}`; } sendRequest(request) { request.headers = FIREBASE_VERSION_HEADER; return this.httpClient.send(request) .then((resp) => { return resp.data; }) .catch((err) => { throw this.toFirebaseError(err); }); } toFirebaseError(err) { if (err instanceof error_1.PrefixedFirebaseError) { return err; } const response = err.response; if (!response.isJson()) { return new security_rules_internal_1.FirebaseSecurityRulesError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`); } const error = response.data.error || {}; let code = 'unknown-error'; if (error.status && error.status in ERROR_CODE_MAPPING) { code = ERROR_CODE_MAPPING[error.status]; } const message = error.message || `Unknown server error: ${response.text}`; return new security_rules_internal_1.FirebaseSecurityRulesError(code, message); } } exports.SecurityRulesApiClient = SecurityRulesApiClient; const ERROR_CODE_MAPPING = { INVALID_ARGUMENT: 'invalid-argument', NOT_FOUND: 'not-found', RESOURCE_EXHAUSTED: 'resource-exhausted', UNAUTHENTICATED: 'authentication-error', UNKNOWN: 'unknown-error', };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules.js
aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.SecurityRules = exports.Ruleset = exports.RulesetMetadataList = void 0; const validator = require("../utils/validator"); const security_rules_api_client_internal_1 = require("./security-rules-api-client-internal"); const security_rules_internal_1 = require("./security-rules-internal"); /** * A page of ruleset metadata. */ class RulesetMetadataList { /** * @internal */ constructor(response) { if (!validator.isNonNullObject(response) || !validator.isArray(response.rulesets)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', `Invalid ListRulesets response: ${JSON.stringify(response)}`); } this.rulesets = response.rulesets.map((rs) => { return { name: stripProjectIdPrefix(rs.name), createTime: new Date(rs.createTime).toUTCString(), }; }); if (response.nextPageToken) { this.nextPageToken = response.nextPageToken; } } } exports.RulesetMetadataList = RulesetMetadataList; /** * A set of Firebase security rules. */ class Ruleset { /** * @internal */ constructor(ruleset) { if (!validator.isNonNullObject(ruleset) || !validator.isNonEmptyString(ruleset.name) || !validator.isNonEmptyString(ruleset.createTime) || !validator.isNonNullObject(ruleset.source)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', `Invalid Ruleset response: ${JSON.stringify(ruleset)}`); } this.name = stripProjectIdPrefix(ruleset.name); this.createTime = new Date(ruleset.createTime).toUTCString(); this.source = ruleset.source.files || []; } } exports.Ruleset = Ruleset; /** * The Firebase `SecurityRules` service interface. */ class SecurityRules { /** * @param app - The app for this SecurityRules service. * @constructor * @internal */ constructor(app) { this.app = app; this.client = new security_rules_api_client_internal_1.SecurityRulesApiClient(app); } /** * Gets the {@link Ruleset} identified by the given * name. The input name should be the short name string without the project ID * prefix. For example, to retrieve the `projects/project-id/rulesets/my-ruleset`, * pass the short name "my-ruleset". Rejects with a `not-found` error if the * specified `Ruleset` cannot be found. * * @param name - Name of the `Ruleset` to retrieve. * @returns A promise that fulfills with the specified `Ruleset`. */ getRuleset(name) { return this.client.getRuleset(name) .then((rulesetResponse) => { return new Ruleset(rulesetResponse); }); } /** * Gets the {@link Ruleset} currently applied to * Cloud Firestore. Rejects with a `not-found` error if no ruleset is applied * on Firestore. * * @returns A promise that fulfills with the Firestore ruleset. */ getFirestoreRuleset() { return this.getRulesetForRelease(SecurityRules.CLOUD_FIRESTORE); } /** * Creates a new {@link Ruleset} from the given * source, and applies it to Cloud Firestore. * * @param source - Rules source to apply. * @returns A promise that fulfills when the ruleset is created and released. */ releaseFirestoreRulesetFromSource(source) { return Promise.resolve() .then(() => { const rulesFile = this.createRulesFileFromSource('firestore.rules', source); return this.createRuleset(rulesFile); }) .then((ruleset) => { return this.releaseFirestoreRuleset(ruleset) .then(() => { return ruleset; }); }); } /** * Applies the specified {@link Ruleset} ruleset * to Cloud Firestore. * * @param ruleset - Name of the ruleset to apply or a `RulesetMetadata` object * containing the name. * @returns A promise that fulfills when the ruleset is released. */ releaseFirestoreRuleset(ruleset) { return this.releaseRuleset(ruleset, SecurityRules.CLOUD_FIRESTORE); } /** * Gets the {@link Ruleset} currently applied to a * Cloud Storage bucket. Rejects with a `not-found` error if no ruleset is applied * on the bucket. * * @param bucket - Optional name of the Cloud Storage bucket to be retrieved. If not * specified, retrieves the ruleset applied on the default bucket configured via * `AppOptions`. * @returns A promise that fulfills with the Cloud Storage ruleset. */ getStorageRuleset(bucket) { return Promise.resolve() .then(() => { return this.getBucketName(bucket); }) .then((bucketName) => { return this.getRulesetForRelease(`${SecurityRules.FIREBASE_STORAGE}/${bucketName}`); }); } /** * Creates a new {@link Ruleset} from the given * source, and applies it to a Cloud Storage bucket. * * @param source - Rules source to apply. * @param bucket - Optional name of the Cloud Storage bucket to apply the rules on. If * not specified, applies the ruleset on the default bucket configured via * {@link firebase-admin.app#AppOptions}. * @returns A promise that fulfills when the ruleset is created and released. */ releaseStorageRulesetFromSource(source, bucket) { return Promise.resolve() .then(() => { // Bucket name is not required until the last step. But since there's a createRuleset step // before then, make sure to run this check and fail early if the bucket name is invalid. this.getBucketName(bucket); const rulesFile = this.createRulesFileFromSource('storage.rules', source); return this.createRuleset(rulesFile); }) .then((ruleset) => { return this.releaseStorageRuleset(ruleset, bucket) .then(() => { return ruleset; }); }); } /** * Applies the specified {@link Ruleset} ruleset * to a Cloud Storage bucket. * * @param ruleset - Name of the ruleset to apply or a `RulesetMetadata` object * containing the name. * @param bucket - Optional name of the Cloud Storage bucket to apply the rules on. If * not specified, applies the ruleset on the default bucket configured via * {@link firebase-admin.app#AppOptions}. * @returns A promise that fulfills when the ruleset is released. */ releaseStorageRuleset(ruleset, bucket) { return Promise.resolve() .then(() => { return this.getBucketName(bucket); }) .then((bucketName) => { return this.releaseRuleset(ruleset, `${SecurityRules.FIREBASE_STORAGE}/${bucketName}`); }); } /** * Creates a {@link RulesFile} with the given name * and source. Throws an error if any of the arguments are invalid. This is a local * operation, and does not involve any network API calls. * * @example * ```javascript * const source = '// Some rules source'; * const rulesFile = admin.securityRules().createRulesFileFromSource( * 'firestore.rules', source); * ``` * * @param name - Name to assign to the rules file. This is usually a short file name that * helps identify the file in a ruleset. * @param source - Contents of the rules file. * @returns A new rules file instance. */ createRulesFileFromSource(name, source) { if (!validator.isNonEmptyString(name)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Name must be a non-empty string.'); } let content; if (validator.isNonEmptyString(source)) { content = source; } else if (validator.isBuffer(source)) { content = source.toString('utf-8'); } else { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Source must be a non-empty string or a Buffer.'); } return { name, content, }; } /** * Creates a new {@link Ruleset} from the given {@link RulesFile}. * * @param file - Rules file to include in the new `Ruleset`. * @returns A promise that fulfills with the newly created `Ruleset`. */ createRuleset(file) { const ruleset = { source: { files: [file], }, }; return this.client.createRuleset(ruleset) .then((rulesetResponse) => { return new Ruleset(rulesetResponse); }); } /** * Deletes the {@link Ruleset} identified by the given * name. The input name should be the short name string without the project ID * prefix. For example, to delete the `projects/project-id/rulesets/my-ruleset`, * pass the short name "my-ruleset". Rejects with a `not-found` error if the * specified `Ruleset` cannot be found. * * @param name - Name of the `Ruleset` to delete. * @returns A promise that fulfills when the `Ruleset` is deleted. */ deleteRuleset(name) { return this.client.deleteRuleset(name); } /** * Retrieves a page of ruleset metadata. * * @param pageSize - The page size, 100 if undefined. This is also the maximum allowed * limit. * @param nextPageToken - The next page token. If not specified, returns rulesets * starting without any offset. * @returns A promise that fulfills with a page of rulesets. */ listRulesetMetadata(pageSize = 100, nextPageToken) { return this.client.listRulesets(pageSize, nextPageToken) .then((response) => { return new RulesetMetadataList(response); }); } getRulesetForRelease(releaseName) { return this.client.getRelease(releaseName) .then((release) => { const rulesetName = release.rulesetName; if (!validator.isNonEmptyString(rulesetName)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('not-found', `Ruleset name not found for ${releaseName}.`); } return this.getRuleset(stripProjectIdPrefix(rulesetName)); }); } releaseRuleset(ruleset, releaseName) { if (!validator.isNonEmptyString(ruleset) && (!validator.isNonNullObject(ruleset) || !validator.isNonEmptyString(ruleset.name))) { const err = new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'ruleset must be a non-empty name or a RulesetMetadata object.'); return Promise.reject(err); } const rulesetName = validator.isString(ruleset) ? ruleset : ruleset.name; return this.client.updateRelease(releaseName, rulesetName) .then(() => { return; }); } getBucketName(bucket) { const bucketName = (typeof bucket !== 'undefined') ? bucket : this.app.options.storageBucket; if (!validator.isNonEmptyString(bucketName)) { throw new security_rules_internal_1.FirebaseSecurityRulesError('invalid-argument', 'Bucket name not specified or invalid. Specify a default bucket name via the ' + 'storageBucket option when initializing the app, or specify the bucket name ' + 'explicitly when calling the rules API.'); } return bucketName; } } exports.SecurityRules = SecurityRules; SecurityRules.CLOUD_FIRESTORE = 'cloud.firestore'; SecurityRules.FIREBASE_STORAGE = 'firebase.storage'; function stripProjectIdPrefix(name) { return name.split('/').pop(); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/index.js
aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/index.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getSecurityRules = exports.SecurityRules = exports.RulesetMetadataList = exports.Ruleset = void 0; /** * Security Rules for Cloud Firestore and Cloud Storage. * * @packageDocumentation */ const app_1 = require("../app"); const security_rules_1 = require("./security-rules"); var security_rules_2 = require("./security-rules"); Object.defineProperty(exports, "Ruleset", { enumerable: true, get: function () { return security_rules_2.Ruleset; } }); Object.defineProperty(exports, "RulesetMetadataList", { enumerable: true, get: function () { return security_rules_2.RulesetMetadataList; } }); Object.defineProperty(exports, "SecurityRules", { enumerable: true, get: function () { return security_rules_2.SecurityRules; } }); /** * Gets the {@link SecurityRules} service for the default app or a given app. * * `admin.securityRules()` can be called with no arguments to access the * default app's `SecurityRules` service, or as `admin.securityRules(app)` to access * the `SecurityRules` service associated with a specific app. * * @example * ```javascript * // Get the SecurityRules service for the default app * const defaultSecurityRules = getSecurityRules(); * ``` * * @example * ```javascript * // Get the SecurityRules service for a given app * const otherSecurityRules = getSecurityRules(otherApp); * ``` * * @param app - Optional app to return the `SecurityRules` service * for. If not provided, the default `SecurityRules` service * is returned. * @returns The default `SecurityRules` service if no app is provided, or the * `SecurityRules` service associated with the provided app. */ function getSecurityRules(app) { if (typeof app === 'undefined') { app = (0, app_1.getApp)(); } const firebaseApp = app; return firebaseApp.getOrInitService('securityRules', (app) => new security_rules_1.SecurityRules(app)); } exports.getSecurityRules = getSecurityRules;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules-internal.js
aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules-internal.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebaseSecurityRulesError = void 0; const error_1 = require("../utils/error"); class FirebaseSecurityRulesError extends error_1.PrefixedFirebaseError { constructor(code, message) { super('security-rules', code, message); } } exports.FirebaseSecurityRulesError = FirebaseSecurityRulesError;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/security-rules/security-rules-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app-check/token-verifier.js
aws/lti-middleware/node_modules/firebase-admin/lib/app-check/token-verifier.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.AppCheckTokenVerifier = void 0; const validator = require("../utils/validator"); const util = require("../utils/index"); const app_check_api_client_internal_1 = require("./app-check-api-client-internal"); const jwt_1 = require("../utils/jwt"); const APP_CHECK_ISSUER = 'https://firebaseappcheck.googleapis.com/'; const JWKS_URL = 'https://firebaseappcheck.googleapis.com/v1/jwks'; /** * Class for verifying Firebase App Check tokens. * * @internal */ class AppCheckTokenVerifier { constructor(app) { this.app = app; this.signatureVerifier = jwt_1.PublicKeySignatureVerifier.withJwksUrl(JWKS_URL); } /** * Verifies the format and signature of a Firebase App Check token. * * @param token - The Firebase Auth JWT token to verify. * @returns A promise fulfilled with the decoded claims of the Firebase App Check token. */ verifyToken(token) { if (!validator.isString(token)) { throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'App check token must be a non-null string.'); } return this.ensureProjectId() .then((projectId) => { return this.decodeAndVerify(token, projectId); }) .then((decoded) => { const decodedAppCheckToken = decoded.payload; decodedAppCheckToken.app_id = decodedAppCheckToken.sub; return decodedAppCheckToken; }); } ensureProjectId() { return util.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-credential', 'Must initialize app with a cert credential or set your Firebase project ID as the ' + 'GOOGLE_CLOUD_PROJECT environment variable to verify an App Check token.'); } return projectId; }); } decodeAndVerify(token, projectId) { return this.safeDecode(token) .then((decodedToken) => { this.verifyContent(decodedToken, projectId); return this.verifySignature(token) .then(() => decodedToken); }); } safeDecode(jwtToken) { return (0, jwt_1.decodeJwt)(jwtToken) .catch(() => { const errorMessage = 'Decoding App Check token failed. Make sure you passed ' + 'the entire string JWT which represents the Firebase App Check token.'; throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); }); } /** * Verifies the content of a Firebase App Check JWT. * * @param fullDecodedToken - The decoded JWT. * @param projectId - The Firebase Project Id. */ verifyContent(fullDecodedToken, projectId) { const header = fullDecodedToken.header; const payload = fullDecodedToken.payload; const projectIdMatchMessage = ' Make sure the App Check token comes from the same ' + 'Firebase project as the service account used to authenticate this SDK.'; const scopedProjectId = `projects/${projectId}`; let errorMessage; if (header.alg !== jwt_1.ALGORITHM_RS256) { errorMessage = 'The provided App Check token has incorrect algorithm. Expected "' + jwt_1.ALGORITHM_RS256 + '" but got ' + '"' + header.alg + '".'; } else if (!validator.isNonEmptyArray(payload.aud) || !payload.aud.includes(scopedProjectId)) { errorMessage = 'The provided App Check token has incorrect "aud" (audience) claim. Expected "' + scopedProjectId + '" but got "' + payload.aud + '".' + projectIdMatchMessage; } else if (typeof payload.iss !== 'string' || !payload.iss.startsWith(APP_CHECK_ISSUER)) { errorMessage = 'The provided App Check token has incorrect "iss" (issuer) claim.'; } else if (typeof payload.sub !== 'string') { errorMessage = 'The provided App Check token has no "sub" (subject) claim.'; } else if (payload.sub === '') { errorMessage = 'The provided App Check token has an empty string "sub" (subject) claim.'; } if (errorMessage) { throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); } } verifySignature(jwtToken) { return this.signatureVerifier.verify(jwtToken) .catch((error) => { throw this.mapJwtErrorToAppCheckError(error); }); } /** * Maps JwtError to FirebaseAppCheckError * * @param error - JwtError to be mapped. * @returns FirebaseAppCheckError instance. */ mapJwtErrorToAppCheckError(error) { if (error.code === jwt_1.JwtErrorCode.TOKEN_EXPIRED) { const errorMessage = 'The provided App Check token has expired. Get a fresh App Check token' + ' from your client app and try again.'; return new app_check_api_client_internal_1.FirebaseAppCheckError('app-check-token-expired', errorMessage); } else if (error.code === jwt_1.JwtErrorCode.INVALID_SIGNATURE) { const errorMessage = 'The provided App Check token has invalid signature.'; return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); } else if (error.code === jwt_1.JwtErrorCode.NO_MATCHING_KID) { const errorMessage = 'The provided App Check token has "kid" claim which does not ' + 'correspond to a known public key. Most likely the provided App Check token ' + 'is expired, so get a fresh token from your client app and try again.'; return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage); } return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', error.message); } } exports.AppCheckTokenVerifier = AppCheckTokenVerifier;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/firebase-admin/lib/app-check/app-check-namespace.js
aws/lti-middleware/node_modules/firebase-admin/lib/app-check/app-check-namespace.js
/*! firebase-admin v11.0.0 */ "use strict"; /*! * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false