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/@firebase/database-compat/dist/node-esm/index.js
aws/lti-middleware/node_modules/@firebase/database-compat/dist/node-esm/index.js
import firebase from '@firebase/app-compat'; import { Provider, ComponentContainer, Component } from '@firebase/component'; import { _validatePathString, onChildMoved, onChildChanged, onChildRemoved, onChildAdded, onValue, off, get, query, limitToFirst, limitToLast, orderByChild, orderByKey, orderByPriority, orderByValue, startAt, startAfter, endAt, endBefore, equalTo, _ReferenceImpl, _QueryImpl, _QueryParams, child, set, _validateWritablePath, update, setWithPriority, remove, runTransaction, setPriority, push, OnDisconnect as OnDisconnect$1, forceWebSockets, forceLongPolling, connectDatabaseEmulator, refFromURL, ref, goOffline, goOnline, serverTimestamp, increment, _setSDKVersion, _repoManagerDatabaseFromApp, enableLogging } from '@firebase/database'; import { errorPrefix, validateArgCount, validateCallback, validateContextObject, Deferred } from '@firebase/util'; import { Logger } from '@firebase/logger'; const name = "@firebase/database-compat"; const version = "0.2.1"; /** * @license * Copyright 2021 Google LLC * * 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 logClient = new Logger('@firebase/database-compat'); const warn = function (msg) { const message = 'FIREBASE WARNING: ' + msg; logClient.warn(message); }; /** * @license * Copyright 2021 Google LLC * * 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 validateBoolean = function (fnName, argumentName, bool, optional) { if (optional && bool === undefined) { return; } if (typeof bool !== 'boolean') { throw new Error(errorPrefix(fnName, argumentName) + 'must be a boolean.'); } }; const validateEventType = function (fnName, eventType, optional) { if (optional && eventType === undefined) { return; } switch (eventType) { case 'value': case 'child_added': case 'child_removed': case 'child_changed': case 'child_moved': break; default: throw new Error(errorPrefix(fnName, 'eventType') + 'must be a valid event type = "value", "child_added", "child_removed", ' + '"child_changed", or "child_moved".'); } }; /** * @license * Copyright 2017 Google LLC * * 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. */ class OnDisconnect { constructor(_delegate) { this._delegate = _delegate; } cancel(onComplete) { validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true); const result = this._delegate.cancel(); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } remove(onComplete) { validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true); const result = this._delegate.remove(); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } set(value, onComplete) { validateArgCount('OnDisconnect.set', 1, 2, arguments.length); validateCallback('OnDisconnect.set', 'onComplete', onComplete, true); const result = this._delegate.set(value); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } setWithPriority(value, priority, onComplete) { validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true); const result = this._delegate.setWithPriority(value, priority); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } update(objectToMerge, onComplete) { validateArgCount('OnDisconnect.update', 1, 2, arguments.length); if (Array.isArray(objectToMerge)) { const newObjectToMerge = {}; for (let i = 0; i < objectToMerge.length; ++i) { newObjectToMerge['' + i] = objectToMerge[i]; } objectToMerge = newObjectToMerge; warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); } validateCallback('OnDisconnect.update', 'onComplete', onComplete, true); const result = this._delegate.update(objectToMerge); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } } /** * @license * Copyright 2017 Google LLC * * 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. */ class TransactionResult { /** * A type for the resolve value of Firebase.transaction. */ constructor(committed, snapshot) { this.committed = committed; this.snapshot = snapshot; } // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary // for end-users toJSON() { validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); return { committed: this.committed, snapshot: this.snapshot.toJSON() }; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Class representing a firebase data snapshot. It wraps a SnapshotNode and * surfaces the public methods (val, forEach, etc.) we want to expose. */ class DataSnapshot { constructor(_database, _delegate) { this._database = _database; this._delegate = _delegate; } /** * Retrieves the snapshot contents as JSON. Returns null if the snapshot is * empty. * * @returns JSON representation of the DataSnapshot contents, or null if empty. */ val() { validateArgCount('DataSnapshot.val', 0, 0, arguments.length); return this._delegate.val(); } /** * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting * the entire node contents. * @returns JSON representation of the DataSnapshot contents, or null if empty. */ exportVal() { validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); return this._delegate.exportVal(); } // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary // for end-users toJSON() { // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); return this._delegate.toJSON(); } /** * Returns whether the snapshot contains a non-null value. * * @returns Whether the snapshot contains a non-null value, or is empty. */ exists() { validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); return this._delegate.exists(); } /** * Returns a DataSnapshot of the specified child node's contents. * * @param path - Path to a child. * @returns DataSnapshot for child node. */ child(path) { validateArgCount('DataSnapshot.child', 0, 1, arguments.length); // Ensure the childPath is a string (can be a number) path = String(path); _validatePathString('DataSnapshot.child', 'path', path, false); return new DataSnapshot(this._database, this._delegate.child(path)); } /** * Returns whether the snapshot contains a child at the specified path. * * @param path - Path to a child. * @returns Whether the child exists. */ hasChild(path) { validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); _validatePathString('DataSnapshot.hasChild', 'path', path, false); return this._delegate.hasChild(path); } /** * Returns the priority of the object, or null if no priority was set. * * @returns The priority. */ getPriority() { validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); return this._delegate.priority; } /** * Iterates through child nodes and calls the specified action for each one. * * @param action - Callback function to be called * for each child. * @returns True if forEach was canceled by action returning true for * one of the child nodes. */ forEach(action) { validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); validateCallback('DataSnapshot.forEach', 'action', action, false); return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot))); } /** * Returns whether this DataSnapshot has children. * @returns True if the DataSnapshot contains 1 or more child nodes. */ hasChildren() { validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); return this._delegate.hasChildren(); } get key() { return this._delegate.key; } /** * Returns the number of children for this DataSnapshot. * @returns The number of children that this DataSnapshot contains. */ numChildren() { validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); return this._delegate.size; } /** * @returns The Firebase reference for the location this snapshot's data came * from. */ getRef() { validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); return new Reference(this._database, this._delegate.ref); } get ref() { return this.getRef(); } } /** * A Query represents a filter to be applied to a firebase location. This object purely represents the * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. * * Since every Firebase reference is a query, Firebase inherits from this object. */ class Query { constructor(database, _delegate) { this.database = database; this._delegate = _delegate; } on(eventType, callback, cancelCallbackOrContext, context) { var _a; validateArgCount('Query.on', 2, 4, arguments.length); validateCallback('Query.on', 'callback', callback, false); const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); const valueCallback = (expSnapshot, previousChildName) => { callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName); }; valueCallback.userCallback = callback; valueCallback.context = ret.context; const cancelCallback = (_a = ret.cancel) === null || _a === void 0 ? void 0 : _a.bind(ret.context); switch (eventType) { case 'value': onValue(this._delegate, valueCallback, cancelCallback); return callback; case 'child_added': onChildAdded(this._delegate, valueCallback, cancelCallback); return callback; case 'child_removed': onChildRemoved(this._delegate, valueCallback, cancelCallback); return callback; case 'child_changed': onChildChanged(this._delegate, valueCallback, cancelCallback); return callback; case 'child_moved': onChildMoved(this._delegate, valueCallback, cancelCallback); return callback; default: throw new Error(errorPrefix('Query.on', 'eventType') + 'must be a valid event type = "value", "child_added", "child_removed", ' + '"child_changed", or "child_moved".'); } } off(eventType, callback, context) { validateArgCount('Query.off', 0, 3, arguments.length); validateEventType('Query.off', eventType, true); validateCallback('Query.off', 'callback', callback, true); validateContextObject('Query.off', 'context', context, true); if (callback) { const valueCallback = () => { }; valueCallback.userCallback = callback; valueCallback.context = context; off(this._delegate, eventType, valueCallback); } else { off(this._delegate, eventType); } } /** * Get the server-value for this query, or return a cached value if not connected. */ get() { return get(this._delegate).then(expSnapshot => { return new DataSnapshot(this.database, expSnapshot); }); } /** * Attaches a listener, waits for the first event, and then removes the listener */ once(eventType, callback, failureCallbackOrContext, context) { validateArgCount('Query.once', 1, 4, arguments.length); validateCallback('Query.once', 'callback', callback, true); const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context); const deferred = new Deferred(); const valueCallback = (expSnapshot, previousChildName) => { const result = new DataSnapshot(this.database, expSnapshot); if (callback) { callback.call(ret.context, result, previousChildName); } deferred.resolve(result); }; valueCallback.userCallback = callback; valueCallback.context = ret.context; const cancelCallback = (error) => { if (ret.cancel) { ret.cancel.call(ret.context, error); } deferred.reject(error); }; switch (eventType) { case 'value': onValue(this._delegate, valueCallback, cancelCallback, { onlyOnce: true }); break; case 'child_added': onChildAdded(this._delegate, valueCallback, cancelCallback, { onlyOnce: true }); break; case 'child_removed': onChildRemoved(this._delegate, valueCallback, cancelCallback, { onlyOnce: true }); break; case 'child_changed': onChildChanged(this._delegate, valueCallback, cancelCallback, { onlyOnce: true }); break; case 'child_moved': onChildMoved(this._delegate, valueCallback, cancelCallback, { onlyOnce: true }); break; default: throw new Error(errorPrefix('Query.once', 'eventType') + 'must be a valid event type = "value", "child_added", "child_removed", ' + '"child_changed", or "child_moved".'); } return deferred.promise; } /** * Set a limit and anchor it to the start of the window. */ limitToFirst(limit) { validateArgCount('Query.limitToFirst', 1, 1, arguments.length); return new Query(this.database, query(this._delegate, limitToFirst(limit))); } /** * Set a limit and anchor it to the end of the window. */ limitToLast(limit) { validateArgCount('Query.limitToLast', 1, 1, arguments.length); return new Query(this.database, query(this._delegate, limitToLast(limit))); } /** * Given a child path, return a new query ordered by the specified grandchild path. */ orderByChild(path) { validateArgCount('Query.orderByChild', 1, 1, arguments.length); return new Query(this.database, query(this._delegate, orderByChild(path))); } /** * Return a new query ordered by the KeyIndex */ orderByKey() { validateArgCount('Query.orderByKey', 0, 0, arguments.length); return new Query(this.database, query(this._delegate, orderByKey())); } /** * Return a new query ordered by the PriorityIndex */ orderByPriority() { validateArgCount('Query.orderByPriority', 0, 0, arguments.length); return new Query(this.database, query(this._delegate, orderByPriority())); } /** * Return a new query ordered by the ValueIndex */ orderByValue() { validateArgCount('Query.orderByValue', 0, 0, arguments.length); return new Query(this.database, query(this._delegate, orderByValue())); } startAt(value = null, name) { validateArgCount('Query.startAt', 0, 2, arguments.length); return new Query(this.database, query(this._delegate, startAt(value, name))); } startAfter(value = null, name) { validateArgCount('Query.startAfter', 0, 2, arguments.length); return new Query(this.database, query(this._delegate, startAfter(value, name))); } endAt(value = null, name) { validateArgCount('Query.endAt', 0, 2, arguments.length); return new Query(this.database, query(this._delegate, endAt(value, name))); } endBefore(value = null, name) { validateArgCount('Query.endBefore', 0, 2, arguments.length); return new Query(this.database, query(this._delegate, endBefore(value, name))); } /** * Load the selection of children with exactly the specified value, and, optionally, * the specified name. */ equalTo(value, name) { validateArgCount('Query.equalTo', 1, 2, arguments.length); return new Query(this.database, query(this._delegate, equalTo(value, name))); } /** * @returns URL for this location. */ toString() { validateArgCount('Query.toString', 0, 0, arguments.length); return this._delegate.toString(); } // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary // for end-users. toJSON() { // An optional spacer argument is unnecessary for a string. validateArgCount('Query.toJSON', 0, 1, arguments.length); return this._delegate.toJSON(); } /** * Return true if this query and the provided query are equivalent; otherwise, return false. */ isEqual(other) { validateArgCount('Query.isEqual', 1, 1, arguments.length); if (!(other instanceof Query)) { const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; throw new Error(error); } return this._delegate.isEqual(other._delegate); } /** * Helper used by .on and .once to extract the context and or cancel arguments. * @param fnName - The function name (on or once) * */ static getCancelAndContextArgs_(fnName, cancelOrContext, context) { const ret = { cancel: undefined, context: undefined }; if (cancelOrContext && context) { ret.cancel = cancelOrContext; validateCallback(fnName, 'cancel', ret.cancel, true); ret.context = context; validateContextObject(fnName, 'context', ret.context, true); } else if (cancelOrContext) { // we have either a cancel callback or a context. if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { // it's a context! ret.context = cancelOrContext; } else if (typeof cancelOrContext === 'function') { ret.cancel = cancelOrContext; } else { throw new Error(errorPrefix(fnName, 'cancelOrContext') + ' must either be a cancel callback or a context object.'); } } return ret; } get ref() { return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path)); } } class Reference extends Query { /** * Call options: * new Reference(Repo, Path) or * new Reference(url: string, string|RepoManager) * * Externally - this is the firebase.database.Reference type. */ constructor(database, _delegate) { super(database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false)); this.database = database; this._delegate = _delegate; } /** @returns {?string} */ getKey() { validateArgCount('Reference.key', 0, 0, arguments.length); return this._delegate.key; } child(pathString) { validateArgCount('Reference.child', 1, 1, arguments.length); if (typeof pathString === 'number') { pathString = String(pathString); } return new Reference(this.database, child(this._delegate, pathString)); } /** @returns {?Reference} */ getParent() { validateArgCount('Reference.parent', 0, 0, arguments.length); const parent = this._delegate.parent; return parent ? new Reference(this.database, parent) : null; } /** @returns {!Reference} */ getRoot() { validateArgCount('Reference.root', 0, 0, arguments.length); return new Reference(this.database, this._delegate.root); } set(newVal, onComplete) { validateArgCount('Reference.set', 1, 2, arguments.length); validateCallback('Reference.set', 'onComplete', onComplete, true); const result = set(this._delegate, newVal); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } update(values, onComplete) { validateArgCount('Reference.update', 1, 2, arguments.length); if (Array.isArray(values)) { const newObjectToMerge = {}; for (let i = 0; i < values.length; ++i) { newObjectToMerge['' + i] = values[i]; } values = newObjectToMerge; warn('Passing an Array to Firebase.update() is deprecated. ' + 'Use set() if you want to overwrite the existing data, or ' + 'an Object with integer keys if you really do want to ' + 'only update some of the children.'); } _validateWritablePath('Reference.update', this._delegate._path); validateCallback('Reference.update', 'onComplete', onComplete, true); const result = update(this._delegate, values); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } setWithPriority(newVal, newPriority, onComplete) { validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true); const result = setWithPriority(this._delegate, newVal, newPriority); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } remove(onComplete) { validateArgCount('Reference.remove', 0, 1, arguments.length); validateCallback('Reference.remove', 'onComplete', onComplete, true); const result = remove(this._delegate); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } transaction(transactionUpdate, onComplete, applyLocally) { validateArgCount('Reference.transaction', 1, 3, arguments.length); validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false); validateCallback('Reference.transaction', 'onComplete', onComplete, true); validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true); const result = runTransaction(this._delegate, transactionUpdate, { applyLocally }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot))); if (onComplete) { result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null)); } return result; } setPriority(priority, onComplete) { validateArgCount('Reference.setPriority', 1, 2, arguments.length); validateCallback('Reference.setPriority', 'onComplete', onComplete, true); const result = setPriority(this._delegate, priority); if (onComplete) { result.then(() => onComplete(null), error => onComplete(error)); } return result; } push(value, onComplete) { validateArgCount('Reference.push', 0, 2, arguments.length); validateCallback('Reference.push', 'onComplete', onComplete, true); const expPromise = push(this._delegate, value); const promise = expPromise.then(expRef => new Reference(this.database, expRef)); if (onComplete) { promise.then(() => onComplete(null), error => onComplete(error)); } const result = new Reference(this.database, expPromise); result.then = promise.then.bind(promise); result.catch = promise.catch.bind(promise, undefined); return result; } onDisconnect() { _validateWritablePath('Reference.onDisconnect', this._delegate._path); return new OnDisconnect(new OnDisconnect$1(this._delegate._repo, this._delegate._path)); } get key() { return this.getKey(); } get parent() { return this.getParent(); } get root() { return this.getRoot(); } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Class representing a firebase database. */ class Database { /** * The constructor should not be called by users of our public API. */ constructor(_delegate, app) { this._delegate = _delegate; this.app = app; this.INTERNAL = { delete: () => this._delegate._delete(), forceWebSockets, forceLongPolling }; } /** * Modify this instance to communicate with the Realtime Database emulator. * * <p>Note: This method must be called before performing any other operation. * * @param host - the emulator host (ex: localhost) * @param port - the emulator port (ex: 8080) * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules */ useEmulator(host, port, options = {}) { connectDatabaseEmulator(this._delegate, host, port, options); } ref(path) { validateArgCount('database.ref', 0, 1, arguments.length); if (path instanceof Reference) { const childRef = refFromURL(this._delegate, path.toString()); return new Reference(this, childRef); } else { const childRef = ref(this._delegate, path); return new Reference(this, childRef); } } /** * Returns a reference to the root or the path specified in url. * We throw a exception if the url is not in the same domain as the * current repo. * @returns Firebase reference. */ refFromURL(url) { const apiName = 'database.refFromURL'; validateArgCount(apiName, 1, 1, arguments.length); const childRef = refFromURL(this._delegate, url); return new Reference(this, childRef); } // Make individual repo go offline. goOffline() { validateArgCount('database.goOffline', 0, 0, arguments.length); return goOffline(this._delegate); } goOnline() { validateArgCount('database.goOnline', 0, 0, arguments.length); return goOnline(this._delegate); } } Database.ServerValue = { TIMESTAMP: serverTimestamp(), increment: (delta) => increment(delta) }; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Used by console to create a database based on the app, * passed database URL and a custom auth implementation. * * @param app - A valid FirebaseApp-like object * @param url - A valid Firebase databaseURL * @param version - custom version e.g. firebase-admin version * @param customAuthImpl - custom auth implementation */ function initStandalone({ app, url, version, customAuthImpl, namespace, nodeAdmin = false }) { _setSDKVersion(version); /** * ComponentContainer('database-standalone') is just a placeholder that doesn't perform * any actual function. */ const authProvider = new Provider('auth-internal', new ComponentContainer('database-standalone')); authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* PRIVATE */)); return {
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/database/dist/index.standalone.js
aws/lti-middleware/node_modules/@firebase/database/dist/index.standalone.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var Websocket = require('faye-websocket'); var util = require('@firebase/util'); var tslib = require('tslib'); var logger$1 = require('@firebase/logger'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket); /** * @license * Copyright 2017 Google LLC * * 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 PROTOCOL_VERSION = '5'; var VERSION_PARAM = 'v'; var TRANSPORT_SESSION_PARAM = 's'; var REFERER_PARAM = 'r'; var FORGE_REF = 'f'; // Matches console.firebase.google.com, firebase-console-*.corp.google.com and // firebase.corp.google.com var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; var LAST_SESSION_PARAM = 'ls'; var APPLICATION_ID_PARAM = 'p'; var APP_CHECK_TOKEN_PARAM = 'ac'; var WEBSOCKET = 'websocket'; var LONG_POLLING = 'long_polling'; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Wraps a DOM Storage object and: * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. * - prefixes names with "firebase:" to avoid collisions with app data. * * We automatically (see storage.js) create two such wrappers, one for sessionStorage, * and one for localStorage. * */ var DOMStorageWrapper = /** @class */ (function () { /** * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) */ function DOMStorageWrapper(domStorage_) { this.domStorage_ = domStorage_; // Use a prefix to avoid collisions with other stuff saved by the app. this.prefix_ = 'firebase:'; } /** * @param key - The key to save the value under * @param value - The value being stored, or null to remove the key. */ DOMStorageWrapper.prototype.set = function (key, value) { if (value == null) { this.domStorage_.removeItem(this.prefixedName_(key)); } else { this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); } }; /** * @returns The value that was stored under this key, or null */ DOMStorageWrapper.prototype.get = function (key) { var storedVal = this.domStorage_.getItem(this.prefixedName_(key)); if (storedVal == null) { return null; } else { return util.jsonEval(storedVal); } }; DOMStorageWrapper.prototype.remove = function (key) { this.domStorage_.removeItem(this.prefixedName_(key)); }; DOMStorageWrapper.prototype.prefixedName_ = function (name) { return this.prefix_ + name; }; DOMStorageWrapper.prototype.toString = function () { return this.domStorage_.toString(); }; return DOMStorageWrapper; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An in-memory storage implementation that matches the API of DOMStorageWrapper * (TODO: create interface for both to implement). */ var MemoryStorage = /** @class */ (function () { function MemoryStorage() { this.cache_ = {}; this.isInMemoryStorage = true; } MemoryStorage.prototype.set = function (key, value) { if (value == null) { delete this.cache_[key]; } else { this.cache_[key] = value; } }; MemoryStorage.prototype.get = function (key) { if (util.contains(this.cache_, key)) { return this.cache_[key]; } return null; }; MemoryStorage.prototype.remove = function (key) { delete this.cache_[key]; }; return MemoryStorage; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change * to reflect this type * * @param domStorageName - Name of the underlying storage object * (e.g. 'localStorage' or 'sessionStorage'). * @returns Turning off type information until a common interface is defined. */ var createStoragefor = function (domStorageName) { try { // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, // so it must be inside the try/catch. if (typeof window !== 'undefined' && typeof window[domStorageName] !== 'undefined') { // Need to test cache. Just because it's here doesn't mean it works var domStorage = window[domStorageName]; domStorage.setItem('firebase:sentinel', 'cache'); domStorage.removeItem('firebase:sentinel'); return new DOMStorageWrapper(domStorage); } } catch (e) { } // Failed to create wrapper. Just return in-memory storage. // TODO: log? return new MemoryStorage(); }; /** A storage object that lasts across sessions */ var PersistentStorage = createStoragefor('localStorage'); /** A storage object that only lasts one session */ var SessionStorage = createStoragefor('sessionStorage'); /** * @license * Copyright 2017 Google LLC * * 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 logClient = new logger$1.Logger('@firebase/database'); /** * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). */ var LUIDGenerator = (function () { var id = 1; return function () { return id++; }; })(); /** * Sha1 hash of the input string * @param str - The string to hash * @returns {!string} The resulting hash */ var sha1 = function (str) { var utf8Bytes = util.stringToByteArray(str); var sha1 = new util.Sha1(); sha1.update(utf8Bytes); var sha1Bytes = sha1.digest(); return util.base64.encodeByteArray(sha1Bytes); }; var buildLogMessage_ = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = ''; for (var i = 0; i < varArgs.length; i++) { var arg = varArgs[i]; if (Array.isArray(arg) || (arg && typeof arg === 'object' && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof arg.length === 'number')) { message += buildLogMessage_.apply(null, arg); } else if (typeof arg === 'object') { message += util.stringify(arg); } else { message += arg; } message += ' '; } return message; }; /** * Use this for all debug messages in Firebase. */ var logger = null; /** * Flag to check for log availability on first log message */ var firstLog_ = true; /** * The implementation of Firebase.enableLogging (defined here to break dependencies) * @param logger_ - A flag to turn on logging, or a custom logger * @param persistent - Whether or not to persist logging settings across refreshes */ var enableLogging$1 = function (logger_, persistent) { util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); if (logger_ === true) { logClient.logLevel = logger$1.LogLevel.VERBOSE; logger = logClient.log.bind(logClient); if (persistent) { SessionStorage.set('logging_enabled', true); } } else if (typeof logger_ === 'function') { logger = logger_; } else { logger = null; SessionStorage.remove('logging_enabled'); } }; var log = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } if (firstLog_ === true) { firstLog_ = false; if (logger === null && SessionStorage.get('logging_enabled') === true) { enableLogging$1(true); } } if (logger) { var message = buildLogMessage_.apply(null, varArgs); logger(message); } }; var logWrapper = function (prefix) { return function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs))); }; }; var error = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs))); logClient.error(message); }; var fatal = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = "FIREBASE FATAL ERROR: " + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs))); logClient.error(message); throw new Error(message); }; var warn = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs))); logClient.warn(message); }; /** * Logs a warning if the containing page uses https. Called when a call to new Firebase * does not use https. */ var warnIfPageIsSecure = function () { // Be very careful accessing browser globals. Who knows what may or may not exist. if (typeof window !== 'undefined' && window.location && window.location.protocol && window.location.protocol.indexOf('https:') !== -1) { warn('Insecure Firebase access from a secure page. ' + 'Please use https in calls to new Firebase().'); } }; /** * Returns true if data is NaN, or +/- Infinity. */ var isInvalidJSONNumber = function (data) { return (typeof data === 'number' && (data !== data || // NaN data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY)); }; var executeWhenDOMReady = function (fn) { if (util.isNodeSdk() || document.readyState === 'complete') { fn(); } else { // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which // fire before onload), but fall back to onload. var called_1 = false; var wrappedFn_1 = function () { if (!document.body) { setTimeout(wrappedFn_1, Math.floor(10)); return; } if (!called_1) { called_1 = true; fn(); } }; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', wrappedFn_1, false); // fallback to onload. window.addEventListener('load', wrappedFn_1, false); // eslint-disable-next-line @typescript-eslint/no-explicit-any } else if (document.attachEvent) { // IE. // eslint-disable-next-line @typescript-eslint/no-explicit-any document.attachEvent('onreadystatechange', function () { if (document.readyState === 'complete') { wrappedFn_1(); } }); // fallback to onload. // eslint-disable-next-line @typescript-eslint/no-explicit-any window.attachEvent('onload', wrappedFn_1); // jQuery has an extra hack for IE that we could employ (based on // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. // I'm hoping we don't need it. } } }; /** * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names */ var MIN_NAME = '[MIN_NAME]'; /** * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names */ var MAX_NAME = '[MAX_NAME]'; /** * Compares valid Firebase key names, plus min and max name */ var nameCompare = function (a, b) { if (a === b) { return 0; } else if (a === MIN_NAME || b === MAX_NAME) { return -1; } else if (b === MIN_NAME || a === MAX_NAME) { return 1; } else { var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); if (aAsInt !== null) { if (bAsInt !== null) { return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; } else { return -1; } } else if (bAsInt !== null) { return 1; } else { return a < b ? -1 : 1; } } }; /** * @returns {!number} comparison result. */ var stringCompare = function (a, b) { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } }; var requireKey = function (key, obj) { if (obj && key in obj) { return obj[key]; } else { throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); } }; var ObjectToUniqueKey = function (obj) { if (typeof obj !== 'object' || obj === null) { return util.stringify(obj); } var keys = []; // eslint-disable-next-line guard-for-in for (var k in obj) { keys.push(k); } // Export as json, but with the keys sorted. keys.sort(); var key = '{'; for (var i = 0; i < keys.length; i++) { if (i !== 0) { key += ','; } key += util.stringify(keys[i]); key += ':'; key += ObjectToUniqueKey(obj[keys[i]]); } key += '}'; return key; }; /** * Splits a string into a number of smaller segments of maximum size * @param str - The string * @param segsize - The maximum number of chars in the string. * @returns The string, split into appropriately-sized chunks */ var splitStringBySize = function (str, segsize) { var len = str.length; if (len <= segsize) { return [str]; } var dataSegs = []; for (var c = 0; c < len; c += segsize) { if (c + segsize > len) { dataSegs.push(str.substring(c, len)); } else { dataSegs.push(str.substring(c, c + segsize)); } } return dataSegs; }; /** * Apply a function to each (key, value) pair in an object or * apply a function to each (index, value) pair in an array * @param obj - The object or array to iterate over * @param fn - The function to apply */ function each(obj, fn) { for (var key in obj) { if (obj.hasOwnProperty(key)) { fn(key, obj[key]); } } } /** * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) * I made one modification at the end and removed the NaN / Infinity * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. * @param v - A double * */ var doubleToIEEE754String = function (v) { util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL var ebits = 11, fbits = 52; var bias = (1 << (ebits - 1)) - 1; var s, e, f, ln, i; // Compute sign, exponent, fraction // Skip NaN / Infinity handling --MJL. if (v === 0) { e = 0; f = 0; s = 1 / v === -Infinity ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { // Normalized ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); e = ln + bias; f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); } else { // Denormalized e = 0; f = Math.round(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction var bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); var str = bits.join(''); // Return the data as a hex string. --MJL var hexByteString = ''; for (i = 0; i < 64; i += 8) { var hexByte = parseInt(str.substr(i, 8), 2).toString(16); if (hexByte.length === 1) { hexByte = '0' + hexByte; } hexByteString = hexByteString + hexByte; } return hexByteString.toLowerCase(); }; /** * Used to detect if we're in a Chrome content script (which executes in an * isolated environment where long-polling doesn't work). */ var isChromeExtensionContentScript = function () { return !!(typeof window === 'object' && window['chrome'] && window['chrome']['extension'] && !/^chrome/.test(window.location.href)); }; /** * Used to detect if we're in a Windows 8 Store app. */ var isWindowsStoreApp = function () { // Check for the presence of a couple WinRT globals return typeof Windows === 'object' && typeof Windows.UI === 'object'; }; /** * Converts a server error code to a Javascript Error */ function errorForServerCode(code, query) { var reason = 'Unknown Error'; if (code === 'too_big') { reason = 'The data requested exceeds the maximum size ' + 'that can be accessed with a single request.'; } else if (code === 'permission_denied') { reason = "Client doesn't have permission to access the desired data."; } else if (code === 'unavailable') { reason = 'The service is unavailable'; } var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); // eslint-disable-next-line @typescript-eslint/no-explicit-any error.code = code.toUpperCase(); return error; } /** * Used to test for integer-looking strings */ var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); /** * For use in keys, the minimum possible 32-bit integer. */ var INTEGER_32_MIN = -2147483648; /** * For use in kyes, the maximum possible 32-bit integer. */ var INTEGER_32_MAX = 2147483647; /** * If the string contains a 32-bit integer, return it. Else return null. */ var tryParseInt = function (str) { if (INTEGER_REGEXP_.test(str)) { var intVal = Number(str); if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { return intVal; } } return null; }; /** * Helper to run some code but catch any exceptions and re-throw them later. * Useful for preventing user callbacks from breaking internal code. * * Re-throwing the exception from a setTimeout is a little evil, but it's very * convenient (we don't have to try to figure out when is a safe point to * re-throw it), and the behavior seems reasonable: * * * If you aren't pausing on exceptions, you get an error in the console with * the correct stack trace. * * If you're pausing on all exceptions, the debugger will pause on your * exception and then again when we rethrow it. * * If you're only pausing on uncaught exceptions, the debugger will only pause * on us re-throwing it. * * @param fn - The code to guard. */ var exceptionGuard = function (fn) { try { fn(); } catch (e) { // Re-throw exception when it's safe. setTimeout(function () { // It used to be that "throw e" would result in a good console error with // relevant context, but as of Chrome 39, you just get the firebase.js // file/line number where we re-throw it, which is useless. So we log // e.stack explicitly. var stack = e.stack || ''; warn('Exception was thrown by user callback.', stack); throw e; }, Math.floor(0)); } }; /** * @returns {boolean} true if we think we're currently being crawled. */ var beingCrawled = function () { var userAgent = (typeof window === 'object' && window['navigator'] && window['navigator']['userAgent']) || ''; // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we // believe to support JavaScript/AJAX rendering. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website // would have seen the page" is flaky if we don't treat it as a crawler. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); }; /** * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. * * It is removed with clearTimeout() as normal. * * @param fn - Function to run. * @param time - Milliseconds to wait before running. * @returns The setTimeout() return value. */ var setTimeoutNonBlocking = function (fn, time) { var timeout = setTimeout(fn, time); // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof timeout === 'object' && timeout['unref']) { // eslint-disable-next-line @typescript-eslint/no-explicit-any timeout['unref'](); } return timeout; }; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * A class that holds metadata about a Repo object */ var RepoInfo = /** @class */ (function () { /** * @param host - Hostname portion of the url for the repo * @param secure - Whether or not this repo is accessed over ssl * @param namespace - The namespace represented by the repo * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). * @param nodeAdmin - Whether this instance uses Admin SDK credentials * @param persistenceKey - Override the default session persistence storage key */ function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) { if (nodeAdmin === void 0) { nodeAdmin = false; } if (persistenceKey === void 0) { persistenceKey = ''; } if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; } this.secure = secure; this.namespace = namespace; this.webSocketOnly = webSocketOnly; this.nodeAdmin = nodeAdmin; this.persistenceKey = persistenceKey; this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; this._host = host.toLowerCase(); this._domain = this._host.substr(this._host.indexOf('.') + 1); this.internalHost = PersistentStorage.get('host:' + host) || this._host; } RepoInfo.prototype.isCacheableHost = function () { return this.internalHost.substr(0, 2) === 's-'; }; RepoInfo.prototype.isCustomHost = function () { return (this._domain !== 'firebaseio.com' && this._domain !== 'firebaseio-demo.com'); }; Object.defineProperty(RepoInfo.prototype, "host", { get: function () { return this._host; }, set: function (newHost) { if (newHost !== this.internalHost) { this.internalHost = newHost; if (this.isCacheableHost()) { PersistentStorage.set('host:' + this._host, this.internalHost); } } }, enumerable: false, configurable: true }); RepoInfo.prototype.toString = function () { var str = this.toURLString(); if (this.persistenceKey) { str += '<' + this.persistenceKey + '>'; } return str; }; RepoInfo.prototype.toURLString = function () { var protocol = this.secure ? 'https://' : 'http://'; var query = this.includeNamespaceInQueryParams ? "?ns=" + this.namespace : ''; return "" + protocol + this.host + "/" + query; }; return RepoInfo; }()); function repoInfoNeedsQueryParam(repoInfo) { return (repoInfo.host !== repoInfo.internalHost || repoInfo.isCustomHost() || repoInfo.includeNamespaceInQueryParams); } /** * Returns the websocket URL for this repo * @param repoInfo - RepoInfo object * @param type - of connection * @param params - list * @returns The URL for this repo */ function repoInfoConnectionURL(repoInfo, type, params) { util.assert(typeof type === 'string', 'typeof type must == string'); util.assert(typeof params === 'object', 'typeof params must == object'); var connURL; if (type === WEBSOCKET) { connURL = (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; } else if (type === LONG_POLLING) { connURL = (repoInfo.secure ? 'https://' : 'http://') + repoInfo.internalHost + '/.lp?'; } else { throw new Error('Unknown connection type: ' + type); } if (repoInfoNeedsQueryParam(repoInfo)) { params['ns'] = repoInfo.namespace; } var pairs = []; each(params, function (key, value) { pairs.push(key + '=' + value); }); return connURL + pairs.join('&'); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Tracks a collection of stats. */ var StatsCollection = /** @class */ (function () { function StatsCollection() { this.counters_ = {}; } StatsCollection.prototype.incrementCounter = function (name, amount) { if (amount === void 0) { amount = 1; } if (!util.contains(this.counters_, name)) { this.counters_[name] = 0; } this.counters_[name] += amount; }; StatsCollection.prototype.get = function () { return util.deepCopy(this.counters_); }; return StatsCollection; }()); /** * @license * Copyright 2017 Google LLC * * 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 collections = {}; var reporters = {}; function statsManagerGetCollection(repoInfo) { var hashString = repoInfo.toString(); if (!collections[hashString]) { collections[hashString] = new StatsCollection(); } return collections[hashString]; } function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { var hashString = repoInfo.toString(); if (!reporters[hashString]) { reporters[hashString] = creatorFunction(); } return reporters[hashString]; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** The semver (www.semver.org) version of the SDK. */ var SDK_VERSION = ''; /** * SDK_VERSION should be set before any database instance is created * @internal */ function setSDKVersion(version) { SDK_VERSION = version; } /** * @license * Copyright 2017 Google LLC * * 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 WEBSOCKET_MAX_FRAME_SIZE = 16384; var WEBSOCKET_KEEPALIVE_INTERVAL = 45000; var WebSocketImpl = null; if (typeof MozWebSocket !== 'undefined') { WebSocketImpl = MozWebSocket; } else if (typeof WebSocket !== 'undefined') { WebSocketImpl = WebSocket; } function setWebSocketImpl(impl) { WebSocketImpl = impl; } /** * Create a new websocket connection with the given callbacks. */ var WebSocketConnection = /** @class */ (function () { /** * @param connId identifier for this transport
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/database/dist/index.esm5.js
aws/lti-middleware/node_modules/@firebase/database/dist/index.esm5.js
import { getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app'; import { Component } from '@firebase/component'; import { stringify, jsonEval, contains, assert, isNodeSdk, base64, stringToByteArray, Sha1, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, createMockUserToken } from '@firebase/util'; import { __spreadArray, __read, __values, __extends, __awaiter, __generator, __assign } from 'tslib'; import { Logger, LogLevel } from '@firebase/logger'; var name = "@firebase/database"; var version = "0.13.1"; /** * @license * Copyright 2019 Google LLC * * 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. */ /** The semver (www.semver.org) version of the SDK. */ var SDK_VERSION = ''; /** * SDK_VERSION should be set before any database instance is created * @internal */ function setSDKVersion(version) { SDK_VERSION = version; } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Wraps a DOM Storage object and: * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. * - prefixes names with "firebase:" to avoid collisions with app data. * * We automatically (see storage.js) create two such wrappers, one for sessionStorage, * and one for localStorage. * */ var DOMStorageWrapper = /** @class */ (function () { /** * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) */ function DOMStorageWrapper(domStorage_) { this.domStorage_ = domStorage_; // Use a prefix to avoid collisions with other stuff saved by the app. this.prefix_ = 'firebase:'; } /** * @param key - The key to save the value under * @param value - The value being stored, or null to remove the key. */ DOMStorageWrapper.prototype.set = function (key, value) { if (value == null) { this.domStorage_.removeItem(this.prefixedName_(key)); } else { this.domStorage_.setItem(this.prefixedName_(key), stringify(value)); } }; /** * @returns The value that was stored under this key, or null */ DOMStorageWrapper.prototype.get = function (key) { var storedVal = this.domStorage_.getItem(this.prefixedName_(key)); if (storedVal == null) { return null; } else { return jsonEval(storedVal); } }; DOMStorageWrapper.prototype.remove = function (key) { this.domStorage_.removeItem(this.prefixedName_(key)); }; DOMStorageWrapper.prototype.prefixedName_ = function (name) { return this.prefix_ + name; }; DOMStorageWrapper.prototype.toString = function () { return this.domStorage_.toString(); }; return DOMStorageWrapper; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An in-memory storage implementation that matches the API of DOMStorageWrapper * (TODO: create interface for both to implement). */ var MemoryStorage = /** @class */ (function () { function MemoryStorage() { this.cache_ = {}; this.isInMemoryStorage = true; } MemoryStorage.prototype.set = function (key, value) { if (value == null) { delete this.cache_[key]; } else { this.cache_[key] = value; } }; MemoryStorage.prototype.get = function (key) { if (contains(this.cache_, key)) { return this.cache_[key]; } return null; }; MemoryStorage.prototype.remove = function (key) { delete this.cache_[key]; }; return MemoryStorage; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change * to reflect this type * * @param domStorageName - Name of the underlying storage object * (e.g. 'localStorage' or 'sessionStorage'). * @returns Turning off type information until a common interface is defined. */ var createStoragefor = function (domStorageName) { try { // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, // so it must be inside the try/catch. if (typeof window !== 'undefined' && typeof window[domStorageName] !== 'undefined') { // Need to test cache. Just because it's here doesn't mean it works var domStorage = window[domStorageName]; domStorage.setItem('firebase:sentinel', 'cache'); domStorage.removeItem('firebase:sentinel'); return new DOMStorageWrapper(domStorage); } } catch (e) { } // Failed to create wrapper. Just return in-memory storage. // TODO: log? return new MemoryStorage(); }; /** A storage object that lasts across sessions */ var PersistentStorage = createStoragefor('localStorage'); /** A storage object that only lasts one session */ var SessionStorage = createStoragefor('sessionStorage'); /** * @license * Copyright 2017 Google LLC * * 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 logClient = new Logger('@firebase/database'); /** * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). */ var LUIDGenerator = (function () { var id = 1; return function () { return id++; }; })(); /** * Sha1 hash of the input string * @param str - The string to hash * @returns {!string} The resulting hash */ var sha1 = function (str) { var utf8Bytes = stringToByteArray(str); var sha1 = new Sha1(); sha1.update(utf8Bytes); var sha1Bytes = sha1.digest(); return base64.encodeByteArray(sha1Bytes); }; var buildLogMessage_ = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = ''; for (var i = 0; i < varArgs.length; i++) { var arg = varArgs[i]; if (Array.isArray(arg) || (arg && typeof arg === 'object' && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof arg.length === 'number')) { message += buildLogMessage_.apply(null, arg); } else if (typeof arg === 'object') { message += stringify(arg); } else { message += arg; } message += ' '; } return message; }; /** * Use this for all debug messages in Firebase. */ var logger = null; /** * Flag to check for log availability on first log message */ var firstLog_ = true; /** * The implementation of Firebase.enableLogging (defined here to break dependencies) * @param logger_ - A flag to turn on logging, or a custom logger * @param persistent - Whether or not to persist logging settings across refreshes */ var enableLogging$1 = function (logger_, persistent) { assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); if (logger_ === true) { logClient.logLevel = LogLevel.VERBOSE; logger = logClient.log.bind(logClient); if (persistent) { SessionStorage.set('logging_enabled', true); } } else if (typeof logger_ === 'function') { logger = logger_; } else { logger = null; SessionStorage.remove('logging_enabled'); } }; var log = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } if (firstLog_ === true) { firstLog_ = false; if (logger === null && SessionStorage.get('logging_enabled') === true) { enableLogging$1(true); } } if (logger) { var message = buildLogMessage_.apply(null, varArgs); logger(message); } }; var logWrapper = function (prefix) { return function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } log.apply(void 0, __spreadArray([prefix], __read(varArgs))); }; }; var error = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs))); logClient.error(message); }; var fatal = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = "FIREBASE FATAL ERROR: " + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs))); logClient.error(message); throw new Error(message); }; var warn = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs))); logClient.warn(message); }; /** * Logs a warning if the containing page uses https. Called when a call to new Firebase * does not use https. */ var warnIfPageIsSecure = function () { // Be very careful accessing browser globals. Who knows what may or may not exist. if (typeof window !== 'undefined' && window.location && window.location.protocol && window.location.protocol.indexOf('https:') !== -1) { warn('Insecure Firebase access from a secure page. ' + 'Please use https in calls to new Firebase().'); } }; /** * Returns true if data is NaN, or +/- Infinity. */ var isInvalidJSONNumber = function (data) { return (typeof data === 'number' && (data !== data || // NaN data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY)); }; var executeWhenDOMReady = function (fn) { if (isNodeSdk() || document.readyState === 'complete') { fn(); } else { // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which // fire before onload), but fall back to onload. var called_1 = false; var wrappedFn_1 = function () { if (!document.body) { setTimeout(wrappedFn_1, Math.floor(10)); return; } if (!called_1) { called_1 = true; fn(); } }; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', wrappedFn_1, false); // fallback to onload. window.addEventListener('load', wrappedFn_1, false); // eslint-disable-next-line @typescript-eslint/no-explicit-any } else if (document.attachEvent) { // IE. // eslint-disable-next-line @typescript-eslint/no-explicit-any document.attachEvent('onreadystatechange', function () { if (document.readyState === 'complete') { wrappedFn_1(); } }); // fallback to onload. // eslint-disable-next-line @typescript-eslint/no-explicit-any window.attachEvent('onload', wrappedFn_1); // jQuery has an extra hack for IE that we could employ (based on // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. // I'm hoping we don't need it. } } }; /** * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names */ var MIN_NAME = '[MIN_NAME]'; /** * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names */ var MAX_NAME = '[MAX_NAME]'; /** * Compares valid Firebase key names, plus min and max name */ var nameCompare = function (a, b) { if (a === b) { return 0; } else if (a === MIN_NAME || b === MAX_NAME) { return -1; } else if (b === MIN_NAME || a === MAX_NAME) { return 1; } else { var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); if (aAsInt !== null) { if (bAsInt !== null) { return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; } else { return -1; } } else if (bAsInt !== null) { return 1; } else { return a < b ? -1 : 1; } } }; /** * @returns {!number} comparison result. */ var stringCompare = function (a, b) { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } }; var requireKey = function (key, obj) { if (obj && key in obj) { return obj[key]; } else { throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj)); } }; var ObjectToUniqueKey = function (obj) { if (typeof obj !== 'object' || obj === null) { return stringify(obj); } var keys = []; // eslint-disable-next-line guard-for-in for (var k in obj) { keys.push(k); } // Export as json, but with the keys sorted. keys.sort(); var key = '{'; for (var i = 0; i < keys.length; i++) { if (i !== 0) { key += ','; } key += stringify(keys[i]); key += ':'; key += ObjectToUniqueKey(obj[keys[i]]); } key += '}'; return key; }; /** * Splits a string into a number of smaller segments of maximum size * @param str - The string * @param segsize - The maximum number of chars in the string. * @returns The string, split into appropriately-sized chunks */ var splitStringBySize = function (str, segsize) { var len = str.length; if (len <= segsize) { return [str]; } var dataSegs = []; for (var c = 0; c < len; c += segsize) { if (c + segsize > len) { dataSegs.push(str.substring(c, len)); } else { dataSegs.push(str.substring(c, c + segsize)); } } return dataSegs; }; /** * Apply a function to each (key, value) pair in an object or * apply a function to each (index, value) pair in an array * @param obj - The object or array to iterate over * @param fn - The function to apply */ function each(obj, fn) { for (var key in obj) { if (obj.hasOwnProperty(key)) { fn(key, obj[key]); } } } /** * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) * I made one modification at the end and removed the NaN / Infinity * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. * @param v - A double * */ var doubleToIEEE754String = function (v) { assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL var ebits = 11, fbits = 52; var bias = (1 << (ebits - 1)) - 1; var s, e, f, ln, i; // Compute sign, exponent, fraction // Skip NaN / Infinity handling --MJL. if (v === 0) { e = 0; f = 0; s = 1 / v === -Infinity ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { // Normalized ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); e = ln + bias; f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); } else { // Denormalized e = 0; f = Math.round(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction var bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); var str = bits.join(''); // Return the data as a hex string. --MJL var hexByteString = ''; for (i = 0; i < 64; i += 8) { var hexByte = parseInt(str.substr(i, 8), 2).toString(16); if (hexByte.length === 1) { hexByte = '0' + hexByte; } hexByteString = hexByteString + hexByte; } return hexByteString.toLowerCase(); }; /** * Used to detect if we're in a Chrome content script (which executes in an * isolated environment where long-polling doesn't work). */ var isChromeExtensionContentScript = function () { return !!(typeof window === 'object' && window['chrome'] && window['chrome']['extension'] && !/^chrome/.test(window.location.href)); }; /** * Used to detect if we're in a Windows 8 Store app. */ var isWindowsStoreApp = function () { // Check for the presence of a couple WinRT globals return typeof Windows === 'object' && typeof Windows.UI === 'object'; }; /** * Converts a server error code to a Javascript Error */ function errorForServerCode(code, query) { var reason = 'Unknown Error'; if (code === 'too_big') { reason = 'The data requested exceeds the maximum size ' + 'that can be accessed with a single request.'; } else if (code === 'permission_denied') { reason = "Client doesn't have permission to access the desired data."; } else if (code === 'unavailable') { reason = 'The service is unavailable'; } var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); // eslint-disable-next-line @typescript-eslint/no-explicit-any error.code = code.toUpperCase(); return error; } /** * Used to test for integer-looking strings */ var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); /** * For use in keys, the minimum possible 32-bit integer. */ var INTEGER_32_MIN = -2147483648; /** * For use in kyes, the maximum possible 32-bit integer. */ var INTEGER_32_MAX = 2147483647; /** * If the string contains a 32-bit integer, return it. Else return null. */ var tryParseInt = function (str) { if (INTEGER_REGEXP_.test(str)) { var intVal = Number(str); if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { return intVal; } } return null; }; /** * Helper to run some code but catch any exceptions and re-throw them later. * Useful for preventing user callbacks from breaking internal code. * * Re-throwing the exception from a setTimeout is a little evil, but it's very * convenient (we don't have to try to figure out when is a safe point to * re-throw it), and the behavior seems reasonable: * * * If you aren't pausing on exceptions, you get an error in the console with * the correct stack trace. * * If you're pausing on all exceptions, the debugger will pause on your * exception and then again when we rethrow it. * * If you're only pausing on uncaught exceptions, the debugger will only pause * on us re-throwing it. * * @param fn - The code to guard. */ var exceptionGuard = function (fn) { try { fn(); } catch (e) { // Re-throw exception when it's safe. setTimeout(function () { // It used to be that "throw e" would result in a good console error with // relevant context, but as of Chrome 39, you just get the firebase.js // file/line number where we re-throw it, which is useless. So we log // e.stack explicitly. var stack = e.stack || ''; warn('Exception was thrown by user callback.', stack); throw e; }, Math.floor(0)); } }; /** * @returns {boolean} true if we think we're currently being crawled. */ var beingCrawled = function () { var userAgent = (typeof window === 'object' && window['navigator'] && window['navigator']['userAgent']) || ''; // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we // believe to support JavaScript/AJAX rendering. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website // would have seen the page" is flaky if we don't treat it as a crawler. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); }; /** * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. * * It is removed with clearTimeout() as normal. * * @param fn - Function to run. * @param time - Milliseconds to wait before running. * @returns The setTimeout() return value. */ var setTimeoutNonBlocking = function (fn, time) { var timeout = setTimeout(fn, time); // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof timeout === 'object' && timeout['unref']) { // eslint-disable-next-line @typescript-eslint/no-explicit-any timeout['unref'](); } return timeout; }; /** * @license * Copyright 2021 Google LLC * * 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. */ /** * Abstraction around AppCheck's token fetching capabilities. */ var AppCheckTokenProvider = /** @class */ (function () { function AppCheckTokenProvider(appName_, appCheckProvider) { var _this = this; this.appName_ = appName_; this.appCheckProvider = appCheckProvider; this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true }); if (!this.appCheck) { appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); }); } } AppCheckTokenProvider.prototype.getToken = function (forceRefresh) { var _this = this; if (!this.appCheck) { return new Promise(function (resolve, reject) { // Support delayed initialization of FirebaseAppCheck. This allows our // customers to initialize the RTDB SDK before initializing Firebase // AppCheck and ensures that all requests are authenticated if a token // becomes available before the timoeout below expires. setTimeout(function () { if (_this.appCheck) { _this.getToken(forceRefresh).then(resolve, reject); } else { resolve(null); } }, 0); }); } return this.appCheck.getToken(forceRefresh); }; AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) { var _a; (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); }); }; AppCheckTokenProvider.prototype.notifyForInvalidToken = function () { warn("Provided AppCheck credentials for the app named \"" + this.appName_ + "\" " + 'are invalid. This usually indicates your app was not initialized correctly.'); }; return AppCheckTokenProvider; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Abstraction around FirebaseApp's token fetching capabilities. */ var FirebaseAuthTokenProvider = /** @class */ (function () { function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) { var _this = this; this.appName_ = appName_; this.firebaseOptions_ = firebaseOptions_; this.authProvider_ = authProvider_; this.auth_ = null; this.auth_ = authProvider_.getImmediate({ optional: true }); if (!this.auth_) { authProvider_.onInit(function (auth) { return (_this.auth_ = auth); }); } } FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) { var _this = this; if (!this.auth_) { return new Promise(function (resolve, reject) { // Support delayed initialization of FirebaseAuth. This allows our // customers to initialize the RTDB SDK before initializing Firebase // Auth and ensures that all requests are authenticated if a token // becomes available before the timoeout below expires. setTimeout(function () { if (_this.auth_) { _this.getToken(forceRefresh).then(resolve, reject); } else { resolve(null); } }, 0); }); } return this.auth_.getToken(forceRefresh).catch(function (error) { // TODO: Need to figure out all the cases this is raised and whether // this makes sense. if (error && error.code === 'auth/token-not-initialized') { log('Got auth/token-not-initialized error. Treating as null token.'); return null; } else { return Promise.reject(error); } }); }; FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) { // TODO: We might want to wrap the listener and call it with no args to // avoid a leaky abstraction, but that makes removing the listener harder. if (this.auth_) { this.auth_.addAuthTokenListener(listener); } else { this.authProvider_ .get() .then(function (auth) { return auth.addAuthTokenListener(listener); }); } }; FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) { this.authProvider_ .get() .then(function (auth) { return auth.removeAuthTokenListener(listener); }); }; FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () { var errorMessage = 'Provided authentication credentials for the app named "' + this.appName_ + '" are invalid. This usually indicates your app was not ' + 'initialized correctly. '; if ('credential' in this.firebaseOptions_) { errorMessage += 'Make sure the "credential" property provided to initializeApp() ' + 'is authorized to access the specified "databaseURL" and is from the correct ' + 'project.'; } else if ('serviceAccount' in this.firebaseOptions_) { errorMessage += 'Make sure the "serviceAccount" property provided to initializeApp() ' + 'is authorized to access the specified "databaseURL" and is from the correct ' + 'project.'; } else { errorMessage += 'Make sure the "apiKey" and "databaseURL" properties provided to ' + 'initializeApp() match the values provided for your app at ' + 'https://console.firebase.google.com/.'; } warn(errorMessage); }; return FirebaseAuthTokenProvider; }()); /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ var EmulatorTokenProvider = /** @class */ (function () { function EmulatorTokenProvider(accessToken) { this.accessToken = accessToken; } EmulatorTokenProvider.prototype.getToken = function (forceRefresh) { return Promise.resolve({ accessToken: this.accessToken }); }; EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) { // Invoke the listener immediately to match the behavior in Firebase Auth // (see packages/auth/src/auth.js#L1807) listener(this.accessToken); }; EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { }; EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { }; /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ EmulatorTokenProvider.OWNER = 'owner'; return EmulatorTokenProvider; }()); /** * @license * Copyright 2017 Google LLC * * 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
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/database/dist/index.esm2017.js
aws/lti-middleware/node_modules/@firebase/database/dist/index.esm2017.js
import { getApp, _getProvider, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app'; import { Component } from '@firebase/component'; import { stringify, jsonEval, contains, assert, isNodeSdk, base64, stringToByteArray, Sha1, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, createMockUserToken } from '@firebase/util'; import { Logger, LogLevel } from '@firebase/logger'; const name = "@firebase/database"; const version = "0.13.1"; /** * @license * Copyright 2019 Google LLC * * 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. */ /** The semver (www.semver.org) version of the SDK. */ let SDK_VERSION = ''; /** * SDK_VERSION should be set before any database instance is created * @internal */ function setSDKVersion(version) { SDK_VERSION = version; } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Wraps a DOM Storage object and: * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. * - prefixes names with "firebase:" to avoid collisions with app data. * * We automatically (see storage.js) create two such wrappers, one for sessionStorage, * and one for localStorage. * */ class DOMStorageWrapper { /** * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) */ constructor(domStorage_) { this.domStorage_ = domStorage_; // Use a prefix to avoid collisions with other stuff saved by the app. this.prefix_ = 'firebase:'; } /** * @param key - The key to save the value under * @param value - The value being stored, or null to remove the key. */ set(key, value) { if (value == null) { this.domStorage_.removeItem(this.prefixedName_(key)); } else { this.domStorage_.setItem(this.prefixedName_(key), stringify(value)); } } /** * @returns The value that was stored under this key, or null */ get(key) { const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); if (storedVal == null) { return null; } else { return jsonEval(storedVal); } } remove(key) { this.domStorage_.removeItem(this.prefixedName_(key)); } prefixedName_(name) { return this.prefix_ + name; } toString() { return this.domStorage_.toString(); } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An in-memory storage implementation that matches the API of DOMStorageWrapper * (TODO: create interface for both to implement). */ class MemoryStorage { constructor() { this.cache_ = {}; this.isInMemoryStorage = true; } set(key, value) { if (value == null) { delete this.cache_[key]; } else { this.cache_[key] = value; } } get(key) { if (contains(this.cache_, key)) { return this.cache_[key]; } return null; } remove(key) { delete this.cache_[key]; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change * to reflect this type * * @param domStorageName - Name of the underlying storage object * (e.g. 'localStorage' or 'sessionStorage'). * @returns Turning off type information until a common interface is defined. */ const createStoragefor = function (domStorageName) { try { // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, // so it must be inside the try/catch. if (typeof window !== 'undefined' && typeof window[domStorageName] !== 'undefined') { // Need to test cache. Just because it's here doesn't mean it works const domStorage = window[domStorageName]; domStorage.setItem('firebase:sentinel', 'cache'); domStorage.removeItem('firebase:sentinel'); return new DOMStorageWrapper(domStorage); } } catch (e) { } // Failed to create wrapper. Just return in-memory storage. // TODO: log? return new MemoryStorage(); }; /** A storage object that lasts across sessions */ const PersistentStorage = createStoragefor('localStorage'); /** A storage object that only lasts one session */ const SessionStorage = createStoragefor('sessionStorage'); /** * @license * Copyright 2017 Google LLC * * 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 logClient = new Logger('@firebase/database'); /** * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). */ const LUIDGenerator = (function () { let id = 1; return function () { return id++; }; })(); /** * Sha1 hash of the input string * @param str - The string to hash * @returns {!string} The resulting hash */ const sha1 = function (str) { const utf8Bytes = stringToByteArray(str); const sha1 = new Sha1(); sha1.update(utf8Bytes); const sha1Bytes = sha1.digest(); return base64.encodeByteArray(sha1Bytes); }; const buildLogMessage_ = function (...varArgs) { let message = ''; for (let i = 0; i < varArgs.length; i++) { const arg = varArgs[i]; if (Array.isArray(arg) || (arg && typeof arg === 'object' && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof arg.length === 'number')) { message += buildLogMessage_.apply(null, arg); } else if (typeof arg === 'object') { message += stringify(arg); } else { message += arg; } message += ' '; } return message; }; /** * Use this for all debug messages in Firebase. */ let logger = null; /** * Flag to check for log availability on first log message */ let firstLog_ = true; /** * The implementation of Firebase.enableLogging (defined here to break dependencies) * @param logger_ - A flag to turn on logging, or a custom logger * @param persistent - Whether or not to persist logging settings across refreshes */ const enableLogging$1 = function (logger_, persistent) { assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); if (logger_ === true) { logClient.logLevel = LogLevel.VERBOSE; logger = logClient.log.bind(logClient); if (persistent) { SessionStorage.set('logging_enabled', true); } } else if (typeof logger_ === 'function') { logger = logger_; } else { logger = null; SessionStorage.remove('logging_enabled'); } }; const log = function (...varArgs) { if (firstLog_ === true) { firstLog_ = false; if (logger === null && SessionStorage.get('logging_enabled') === true) { enableLogging$1(true); } } if (logger) { const message = buildLogMessage_.apply(null, varArgs); logger(message); } }; const logWrapper = function (prefix) { return function (...varArgs) { log(prefix, ...varArgs); }; }; const error = function (...varArgs) { const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); logClient.error(message); }; const fatal = function (...varArgs) { const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; logClient.error(message); throw new Error(message); }; const warn = function (...varArgs) { const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); logClient.warn(message); }; /** * Logs a warning if the containing page uses https. Called when a call to new Firebase * does not use https. */ const warnIfPageIsSecure = function () { // Be very careful accessing browser globals. Who knows what may or may not exist. if (typeof window !== 'undefined' && window.location && window.location.protocol && window.location.protocol.indexOf('https:') !== -1) { warn('Insecure Firebase access from a secure page. ' + 'Please use https in calls to new Firebase().'); } }; /** * Returns true if data is NaN, or +/- Infinity. */ const isInvalidJSONNumber = function (data) { return (typeof data === 'number' && (data !== data || // NaN data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY)); }; const executeWhenDOMReady = function (fn) { if (isNodeSdk() || document.readyState === 'complete') { fn(); } else { // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which // fire before onload), but fall back to onload. let called = false; const wrappedFn = function () { if (!document.body) { setTimeout(wrappedFn, Math.floor(10)); return; } if (!called) { called = true; fn(); } }; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', wrappedFn, false); // fallback to onload. window.addEventListener('load', wrappedFn, false); // eslint-disable-next-line @typescript-eslint/no-explicit-any } else if (document.attachEvent) { // IE. // eslint-disable-next-line @typescript-eslint/no-explicit-any document.attachEvent('onreadystatechange', () => { if (document.readyState === 'complete') { wrappedFn(); } }); // fallback to onload. // eslint-disable-next-line @typescript-eslint/no-explicit-any window.attachEvent('onload', wrappedFn); // jQuery has an extra hack for IE that we could employ (based on // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. // I'm hoping we don't need it. } } }; /** * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names */ const MIN_NAME = '[MIN_NAME]'; /** * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names */ const MAX_NAME = '[MAX_NAME]'; /** * Compares valid Firebase key names, plus min and max name */ const nameCompare = function (a, b) { if (a === b) { return 0; } else if (a === MIN_NAME || b === MAX_NAME) { return -1; } else if (b === MIN_NAME || a === MAX_NAME) { return 1; } else { const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); if (aAsInt !== null) { if (bAsInt !== null) { return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; } else { return -1; } } else if (bAsInt !== null) { return 1; } else { return a < b ? -1 : 1; } } }; /** * @returns {!number} comparison result. */ const stringCompare = function (a, b) { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } }; const requireKey = function (key, obj) { if (obj && key in obj) { return obj[key]; } else { throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj)); } }; const ObjectToUniqueKey = function (obj) { if (typeof obj !== 'object' || obj === null) { return stringify(obj); } const keys = []; // eslint-disable-next-line guard-for-in for (const k in obj) { keys.push(k); } // Export as json, but with the keys sorted. keys.sort(); let key = '{'; for (let i = 0; i < keys.length; i++) { if (i !== 0) { key += ','; } key += stringify(keys[i]); key += ':'; key += ObjectToUniqueKey(obj[keys[i]]); } key += '}'; return key; }; /** * Splits a string into a number of smaller segments of maximum size * @param str - The string * @param segsize - The maximum number of chars in the string. * @returns The string, split into appropriately-sized chunks */ const splitStringBySize = function (str, segsize) { const len = str.length; if (len <= segsize) { return [str]; } const dataSegs = []; for (let c = 0; c < len; c += segsize) { if (c + segsize > len) { dataSegs.push(str.substring(c, len)); } else { dataSegs.push(str.substring(c, c + segsize)); } } return dataSegs; }; /** * Apply a function to each (key, value) pair in an object or * apply a function to each (index, value) pair in an array * @param obj - The object or array to iterate over * @param fn - The function to apply */ function each(obj, fn) { for (const key in obj) { if (obj.hasOwnProperty(key)) { fn(key, obj[key]); } } } /** * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) * I made one modification at the end and removed the NaN / Infinity * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. * @param v - A double * */ const doubleToIEEE754String = function (v) { assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL const ebits = 11, fbits = 52; const bias = (1 << (ebits - 1)) - 1; let s, e, f, ln, i; // Compute sign, exponent, fraction // Skip NaN / Infinity handling --MJL. if (v === 0) { e = 0; f = 0; s = 1 / v === -Infinity ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { // Normalized ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); e = ln + bias; f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); } else { // Denormalized e = 0; f = Math.round(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction const bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); const str = bits.join(''); // Return the data as a hex string. --MJL let hexByteString = ''; for (i = 0; i < 64; i += 8) { let hexByte = parseInt(str.substr(i, 8), 2).toString(16); if (hexByte.length === 1) { hexByte = '0' + hexByte; } hexByteString = hexByteString + hexByte; } return hexByteString.toLowerCase(); }; /** * Used to detect if we're in a Chrome content script (which executes in an * isolated environment where long-polling doesn't work). */ const isChromeExtensionContentScript = function () { return !!(typeof window === 'object' && window['chrome'] && window['chrome']['extension'] && !/^chrome/.test(window.location.href)); }; /** * Used to detect if we're in a Windows 8 Store app. */ const isWindowsStoreApp = function () { // Check for the presence of a couple WinRT globals return typeof Windows === 'object' && typeof Windows.UI === 'object'; }; /** * Converts a server error code to a Javascript Error */ function errorForServerCode(code, query) { let reason = 'Unknown Error'; if (code === 'too_big') { reason = 'The data requested exceeds the maximum size ' + 'that can be accessed with a single request.'; } else if (code === 'permission_denied') { reason = "Client doesn't have permission to access the desired data."; } else if (code === 'unavailable') { reason = 'The service is unavailable'; } const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); // eslint-disable-next-line @typescript-eslint/no-explicit-any error.code = code.toUpperCase(); return error; } /** * Used to test for integer-looking strings */ const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); /** * For use in keys, the minimum possible 32-bit integer. */ const INTEGER_32_MIN = -2147483648; /** * For use in kyes, the maximum possible 32-bit integer. */ const INTEGER_32_MAX = 2147483647; /** * If the string contains a 32-bit integer, return it. Else return null. */ const tryParseInt = function (str) { if (INTEGER_REGEXP_.test(str)) { const intVal = Number(str); if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { return intVal; } } return null; }; /** * Helper to run some code but catch any exceptions and re-throw them later. * Useful for preventing user callbacks from breaking internal code. * * Re-throwing the exception from a setTimeout is a little evil, but it's very * convenient (we don't have to try to figure out when is a safe point to * re-throw it), and the behavior seems reasonable: * * * If you aren't pausing on exceptions, you get an error in the console with * the correct stack trace. * * If you're pausing on all exceptions, the debugger will pause on your * exception and then again when we rethrow it. * * If you're only pausing on uncaught exceptions, the debugger will only pause * on us re-throwing it. * * @param fn - The code to guard. */ const exceptionGuard = function (fn) { try { fn(); } catch (e) { // Re-throw exception when it's safe. setTimeout(() => { // It used to be that "throw e" would result in a good console error with // relevant context, but as of Chrome 39, you just get the firebase.js // file/line number where we re-throw it, which is useless. So we log // e.stack explicitly. const stack = e.stack || ''; warn('Exception was thrown by user callback.', stack); throw e; }, Math.floor(0)); } }; /** * @returns {boolean} true if we think we're currently being crawled. */ const beingCrawled = function () { const userAgent = (typeof window === 'object' && window['navigator'] && window['navigator']['userAgent']) || ''; // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we // believe to support JavaScript/AJAX rendering. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website // would have seen the page" is flaky if we don't treat it as a crawler. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); }; /** * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. * * It is removed with clearTimeout() as normal. * * @param fn - Function to run. * @param time - Milliseconds to wait before running. * @returns The setTimeout() return value. */ const setTimeoutNonBlocking = function (fn, time) { const timeout = setTimeout(fn, time); // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof timeout === 'object' && timeout['unref']) { // eslint-disable-next-line @typescript-eslint/no-explicit-any timeout['unref'](); } return timeout; }; /** * @license * Copyright 2021 Google LLC * * 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. */ /** * Abstraction around AppCheck's token fetching capabilities. */ class AppCheckTokenProvider { constructor(appName_, appCheckProvider) { this.appName_ = appName_; this.appCheckProvider = appCheckProvider; this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true }); if (!this.appCheck) { appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck)); } } getToken(forceRefresh) { if (!this.appCheck) { return new Promise((resolve, reject) => { // Support delayed initialization of FirebaseAppCheck. This allows our // customers to initialize the RTDB SDK before initializing Firebase // AppCheck and ensures that all requests are authenticated if a token // becomes available before the timoeout below expires. setTimeout(() => { if (this.appCheck) { this.getToken(forceRefresh).then(resolve, reject); } else { resolve(null); } }, 0); }); } return this.appCheck.getToken(forceRefresh); } addTokenChangeListener(listener) { var _a; (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener)); } notifyForInvalidToken() { warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` + 'are invalid. This usually indicates your app was not initialized correctly.'); } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Abstraction around FirebaseApp's token fetching capabilities. */ class FirebaseAuthTokenProvider { constructor(appName_, firebaseOptions_, authProvider_) { this.appName_ = appName_; this.firebaseOptions_ = firebaseOptions_; this.authProvider_ = authProvider_; this.auth_ = null; this.auth_ = authProvider_.getImmediate({ optional: true }); if (!this.auth_) { authProvider_.onInit(auth => (this.auth_ = auth)); } } getToken(forceRefresh) { if (!this.auth_) { return new Promise((resolve, reject) => { // Support delayed initialization of FirebaseAuth. This allows our // customers to initialize the RTDB SDK before initializing Firebase // Auth and ensures that all requests are authenticated if a token // becomes available before the timoeout below expires. setTimeout(() => { if (this.auth_) { this.getToken(forceRefresh).then(resolve, reject); } else { resolve(null); } }, 0); }); } return this.auth_.getToken(forceRefresh).catch(error => { // TODO: Need to figure out all the cases this is raised and whether // this makes sense. if (error && error.code === 'auth/token-not-initialized') { log('Got auth/token-not-initialized error. Treating as null token.'); return null; } else { return Promise.reject(error); } }); } addTokenChangeListener(listener) { // TODO: We might want to wrap the listener and call it with no args to // avoid a leaky abstraction, but that makes removing the listener harder. if (this.auth_) { this.auth_.addAuthTokenListener(listener); } else { this.authProvider_ .get() .then(auth => auth.addAuthTokenListener(listener)); } } removeTokenChangeListener(listener) { this.authProvider_ .get() .then(auth => auth.removeAuthTokenListener(listener)); } notifyForInvalidToken() { let errorMessage = 'Provided authentication credentials for the app named "' + this.appName_ + '" are invalid. This usually indicates your app was not ' + 'initialized correctly. '; if ('credential' in this.firebaseOptions_) { errorMessage += 'Make sure the "credential" property provided to initializeApp() ' + 'is authorized to access the specified "databaseURL" and is from the correct ' + 'project.'; } else if ('serviceAccount' in this.firebaseOptions_) { errorMessage += 'Make sure the "serviceAccount" property provided to initializeApp() ' + 'is authorized to access the specified "databaseURL" and is from the correct ' + 'project.'; } else { errorMessage += 'Make sure the "apiKey" and "databaseURL" properties provided to ' + 'initializeApp() match the values provided for your app at ' + 'https://console.firebase.google.com/.'; } warn(errorMessage); } } /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */ class EmulatorTokenProvider { constructor(accessToken) { this.accessToken = accessToken; } getToken(forceRefresh) { return Promise.resolve({ accessToken: this.accessToken }); } addTokenChangeListener(listener) { // Invoke the listener immediately to match the behavior in Firebase Auth // (see packages/auth/src/auth.js#L1807) listener(this.accessToken); } removeTokenChangeListener(listener) { } notifyForInvalidToken() { } } /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */ EmulatorTokenProvider.OWNER = 'owner'; /** * @license * Copyright 2017 Google LLC * * 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 PROTOCOL_VERSION = '5'; const VERSION_PARAM = 'v'; const TRANSPORT_SESSION_PARAM = 's'; const REFERER_PARAM = 'r'; const FORGE_REF = 'f'; // Matches console.firebase.google.com, firebase-console-*.corp.google.com and // firebase.corp.google.com const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; const LAST_SESSION_PARAM = 'ls'; const APPLICATION_ID_PARAM = 'p'; const APP_CHECK_TOKEN_PARAM = 'ac'; const WEBSOCKET = 'websocket'; const LONG_POLLING = 'long_polling'; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * A class that holds metadata about a Repo object */ class RepoInfo { /** * @param host - Hostname portion of the url for the repo * @param secure - Whether or not this repo is accessed over ssl * @param namespace - The namespace represented by the repo * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). * @param nodeAdmin - Whether this instance uses Admin SDK credentials * @param persistenceKey - Override the default session persistence storage key */ constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false) { this.secure = secure; this.namespace = namespace; this.webSocketOnly = webSocketOnly; this.nodeAdmin = nodeAdmin; this.persistenceKey = persistenceKey; this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; this._host = host.toLowerCase(); this._domain = this._host.substr(this._host.indexOf('.') + 1); this.internalHost = PersistentStorage.get('host:' + host) || this._host;
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/database/dist/index.node.cjs.js
aws/lti-middleware/node_modules/@firebase/database/dist/index.node.cjs.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var Websocket = require('faye-websocket'); var util = require('@firebase/util'); var tslib = require('tslib'); var logger$1 = require('@firebase/logger'); var app = require('@firebase/app'); var component = require('@firebase/component'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket); /** * @license * Copyright 2017 Google LLC * * 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 PROTOCOL_VERSION = '5'; var VERSION_PARAM = 'v'; var TRANSPORT_SESSION_PARAM = 's'; var REFERER_PARAM = 'r'; var FORGE_REF = 'f'; // Matches console.firebase.google.com, firebase-console-*.corp.google.com and // firebase.corp.google.com var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; var LAST_SESSION_PARAM = 'ls'; var APPLICATION_ID_PARAM = 'p'; var APP_CHECK_TOKEN_PARAM = 'ac'; var WEBSOCKET = 'websocket'; var LONG_POLLING = 'long_polling'; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Wraps a DOM Storage object and: * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. * - prefixes names with "firebase:" to avoid collisions with app data. * * We automatically (see storage.js) create two such wrappers, one for sessionStorage, * and one for localStorage. * */ var DOMStorageWrapper = /** @class */ (function () { /** * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) */ function DOMStorageWrapper(domStorage_) { this.domStorage_ = domStorage_; // Use a prefix to avoid collisions with other stuff saved by the app. this.prefix_ = 'firebase:'; } /** * @param key - The key to save the value under * @param value - The value being stored, or null to remove the key. */ DOMStorageWrapper.prototype.set = function (key, value) { if (value == null) { this.domStorage_.removeItem(this.prefixedName_(key)); } else { this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); } }; /** * @returns The value that was stored under this key, or null */ DOMStorageWrapper.prototype.get = function (key) { var storedVal = this.domStorage_.getItem(this.prefixedName_(key)); if (storedVal == null) { return null; } else { return util.jsonEval(storedVal); } }; DOMStorageWrapper.prototype.remove = function (key) { this.domStorage_.removeItem(this.prefixedName_(key)); }; DOMStorageWrapper.prototype.prefixedName_ = function (name) { return this.prefix_ + name; }; DOMStorageWrapper.prototype.toString = function () { return this.domStorage_.toString(); }; return DOMStorageWrapper; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An in-memory storage implementation that matches the API of DOMStorageWrapper * (TODO: create interface for both to implement). */ var MemoryStorage = /** @class */ (function () { function MemoryStorage() { this.cache_ = {}; this.isInMemoryStorage = true; } MemoryStorage.prototype.set = function (key, value) { if (value == null) { delete this.cache_[key]; } else { this.cache_[key] = value; } }; MemoryStorage.prototype.get = function (key) { if (util.contains(this.cache_, key)) { return this.cache_[key]; } return null; }; MemoryStorage.prototype.remove = function (key) { delete this.cache_[key]; }; return MemoryStorage; }()); /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change * to reflect this type * * @param domStorageName - Name of the underlying storage object * (e.g. 'localStorage' or 'sessionStorage'). * @returns Turning off type information until a common interface is defined. */ var createStoragefor = function (domStorageName) { try { // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, // so it must be inside the try/catch. if (typeof window !== 'undefined' && typeof window[domStorageName] !== 'undefined') { // Need to test cache. Just because it's here doesn't mean it works var domStorage = window[domStorageName]; domStorage.setItem('firebase:sentinel', 'cache'); domStorage.removeItem('firebase:sentinel'); return new DOMStorageWrapper(domStorage); } } catch (e) { } // Failed to create wrapper. Just return in-memory storage. // TODO: log? return new MemoryStorage(); }; /** A storage object that lasts across sessions */ var PersistentStorage = createStoragefor('localStorage'); /** A storage object that only lasts one session */ var SessionStorage = createStoragefor('sessionStorage'); /** * @license * Copyright 2017 Google LLC * * 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 logClient = new logger$1.Logger('@firebase/database'); /** * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). */ var LUIDGenerator = (function () { var id = 1; return function () { return id++; }; })(); /** * Sha1 hash of the input string * @param str - The string to hash * @returns {!string} The resulting hash */ var sha1 = function (str) { var utf8Bytes = util.stringToByteArray(str); var sha1 = new util.Sha1(); sha1.update(utf8Bytes); var sha1Bytes = sha1.digest(); return util.base64.encodeByteArray(sha1Bytes); }; var buildLogMessage_ = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = ''; for (var i = 0; i < varArgs.length; i++) { var arg = varArgs[i]; if (Array.isArray(arg) || (arg && typeof arg === 'object' && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof arg.length === 'number')) { message += buildLogMessage_.apply(null, arg); } else if (typeof arg === 'object') { message += util.stringify(arg); } else { message += arg; } message += ' '; } return message; }; /** * Use this for all debug messages in Firebase. */ var logger = null; /** * Flag to check for log availability on first log message */ var firstLog_ = true; /** * The implementation of Firebase.enableLogging (defined here to break dependencies) * @param logger_ - A flag to turn on logging, or a custom logger * @param persistent - Whether or not to persist logging settings across refreshes */ var enableLogging$1 = function (logger_, persistent) { util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); if (logger_ === true) { logClient.logLevel = logger$1.LogLevel.VERBOSE; logger = logClient.log.bind(logClient); if (persistent) { SessionStorage.set('logging_enabled', true); } } else if (typeof logger_ === 'function') { logger = logger_; } else { logger = null; SessionStorage.remove('logging_enabled'); } }; var log = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } if (firstLog_ === true) { firstLog_ = false; if (logger === null && SessionStorage.get('logging_enabled') === true) { enableLogging$1(true); } } if (logger) { var message = buildLogMessage_.apply(null, varArgs); logger(message); } }; var logWrapper = function (prefix) { return function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs))); }; }; var error = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs))); logClient.error(message); }; var fatal = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = "FIREBASE FATAL ERROR: " + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs))); logClient.error(message); throw new Error(message); }; var warn = function () { var varArgs = []; for (var _i = 0; _i < arguments.length; _i++) { varArgs[_i] = arguments[_i]; } var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs))); logClient.warn(message); }; /** * Logs a warning if the containing page uses https. Called when a call to new Firebase * does not use https. */ var warnIfPageIsSecure = function () { // Be very careful accessing browser globals. Who knows what may or may not exist. if (typeof window !== 'undefined' && window.location && window.location.protocol && window.location.protocol.indexOf('https:') !== -1) { warn('Insecure Firebase access from a secure page. ' + 'Please use https in calls to new Firebase().'); } }; /** * Returns true if data is NaN, or +/- Infinity. */ var isInvalidJSONNumber = function (data) { return (typeof data === 'number' && (data !== data || // NaN data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY)); }; var executeWhenDOMReady = function (fn) { if (util.isNodeSdk() || document.readyState === 'complete') { fn(); } else { // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which // fire before onload), but fall back to onload. var called_1 = false; var wrappedFn_1 = function () { if (!document.body) { setTimeout(wrappedFn_1, Math.floor(10)); return; } if (!called_1) { called_1 = true; fn(); } }; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', wrappedFn_1, false); // fallback to onload. window.addEventListener('load', wrappedFn_1, false); // eslint-disable-next-line @typescript-eslint/no-explicit-any } else if (document.attachEvent) { // IE. // eslint-disable-next-line @typescript-eslint/no-explicit-any document.attachEvent('onreadystatechange', function () { if (document.readyState === 'complete') { wrappedFn_1(); } }); // fallback to onload. // eslint-disable-next-line @typescript-eslint/no-explicit-any window.attachEvent('onload', wrappedFn_1); // jQuery has an extra hack for IE that we could employ (based on // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. // I'm hoping we don't need it. } } }; /** * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names */ var MIN_NAME = '[MIN_NAME]'; /** * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names */ var MAX_NAME = '[MAX_NAME]'; /** * Compares valid Firebase key names, plus min and max name */ var nameCompare = function (a, b) { if (a === b) { return 0; } else if (a === MIN_NAME || b === MAX_NAME) { return -1; } else if (b === MIN_NAME || a === MAX_NAME) { return 1; } else { var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); if (aAsInt !== null) { if (bAsInt !== null) { return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; } else { return -1; } } else if (bAsInt !== null) { return 1; } else { return a < b ? -1 : 1; } } }; /** * @returns {!number} comparison result. */ var stringCompare = function (a, b) { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } }; var requireKey = function (key, obj) { if (obj && key in obj) { return obj[key]; } else { throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); } }; var ObjectToUniqueKey = function (obj) { if (typeof obj !== 'object' || obj === null) { return util.stringify(obj); } var keys = []; // eslint-disable-next-line guard-for-in for (var k in obj) { keys.push(k); } // Export as json, but with the keys sorted. keys.sort(); var key = '{'; for (var i = 0; i < keys.length; i++) { if (i !== 0) { key += ','; } key += util.stringify(keys[i]); key += ':'; key += ObjectToUniqueKey(obj[keys[i]]); } key += '}'; return key; }; /** * Splits a string into a number of smaller segments of maximum size * @param str - The string * @param segsize - The maximum number of chars in the string. * @returns The string, split into appropriately-sized chunks */ var splitStringBySize = function (str, segsize) { var len = str.length; if (len <= segsize) { return [str]; } var dataSegs = []; for (var c = 0; c < len; c += segsize) { if (c + segsize > len) { dataSegs.push(str.substring(c, len)); } else { dataSegs.push(str.substring(c, c + segsize)); } } return dataSegs; }; /** * Apply a function to each (key, value) pair in an object or * apply a function to each (index, value) pair in an array * @param obj - The object or array to iterate over * @param fn - The function to apply */ function each(obj, fn) { for (var key in obj) { if (obj.hasOwnProperty(key)) { fn(key, obj[key]); } } } /** * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) * I made one modification at the end and removed the NaN / Infinity * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. * @param v - A double * */ var doubleToIEEE754String = function (v) { util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL var ebits = 11, fbits = 52; var bias = (1 << (ebits - 1)) - 1; var s, e, f, ln, i; // Compute sign, exponent, fraction // Skip NaN / Infinity handling --MJL. if (v === 0) { e = 0; f = 0; s = 1 / v === -Infinity ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { // Normalized ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); e = ln + bias; f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); } else { // Denormalized e = 0; f = Math.round(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction var bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); var str = bits.join(''); // Return the data as a hex string. --MJL var hexByteString = ''; for (i = 0; i < 64; i += 8) { var hexByte = parseInt(str.substr(i, 8), 2).toString(16); if (hexByte.length === 1) { hexByte = '0' + hexByte; } hexByteString = hexByteString + hexByte; } return hexByteString.toLowerCase(); }; /** * Used to detect if we're in a Chrome content script (which executes in an * isolated environment where long-polling doesn't work). */ var isChromeExtensionContentScript = function () { return !!(typeof window === 'object' && window['chrome'] && window['chrome']['extension'] && !/^chrome/.test(window.location.href)); }; /** * Used to detect if we're in a Windows 8 Store app. */ var isWindowsStoreApp = function () { // Check for the presence of a couple WinRT globals return typeof Windows === 'object' && typeof Windows.UI === 'object'; }; /** * Converts a server error code to a Javascript Error */ function errorForServerCode(code, query) { var reason = 'Unknown Error'; if (code === 'too_big') { reason = 'The data requested exceeds the maximum size ' + 'that can be accessed with a single request.'; } else if (code === 'permission_denied') { reason = "Client doesn't have permission to access the desired data."; } else if (code === 'unavailable') { reason = 'The service is unavailable'; } var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); // eslint-disable-next-line @typescript-eslint/no-explicit-any error.code = code.toUpperCase(); return error; } /** * Used to test for integer-looking strings */ var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); /** * For use in keys, the minimum possible 32-bit integer. */ var INTEGER_32_MIN = -2147483648; /** * For use in kyes, the maximum possible 32-bit integer. */ var INTEGER_32_MAX = 2147483647; /** * If the string contains a 32-bit integer, return it. Else return null. */ var tryParseInt = function (str) { if (INTEGER_REGEXP_.test(str)) { var intVal = Number(str); if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { return intVal; } } return null; }; /** * Helper to run some code but catch any exceptions and re-throw them later. * Useful for preventing user callbacks from breaking internal code. * * Re-throwing the exception from a setTimeout is a little evil, but it's very * convenient (we don't have to try to figure out when is a safe point to * re-throw it), and the behavior seems reasonable: * * * If you aren't pausing on exceptions, you get an error in the console with * the correct stack trace. * * If you're pausing on all exceptions, the debugger will pause on your * exception and then again when we rethrow it. * * If you're only pausing on uncaught exceptions, the debugger will only pause * on us re-throwing it. * * @param fn - The code to guard. */ var exceptionGuard = function (fn) { try { fn(); } catch (e) { // Re-throw exception when it's safe. setTimeout(function () { // It used to be that "throw e" would result in a good console error with // relevant context, but as of Chrome 39, you just get the firebase.js // file/line number where we re-throw it, which is useless. So we log // e.stack explicitly. var stack = e.stack || ''; warn('Exception was thrown by user callback.', stack); throw e; }, Math.floor(0)); } }; /** * @returns {boolean} true if we think we're currently being crawled. */ var beingCrawled = function () { var userAgent = (typeof window === 'object' && window['navigator'] && window['navigator']['userAgent']) || ''; // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we // believe to support JavaScript/AJAX rendering. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website // would have seen the page" is flaky if we don't treat it as a crawler. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); }; /** * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. * * It is removed with clearTimeout() as normal. * * @param fn - Function to run. * @param time - Milliseconds to wait before running. * @returns The setTimeout() return value. */ var setTimeoutNonBlocking = function (fn, time) { var timeout = setTimeout(fn, time); // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof timeout === 'object' && timeout['unref']) { // eslint-disable-next-line @typescript-eslint/no-explicit-any timeout['unref'](); } return timeout; }; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * A class that holds metadata about a Repo object */ var RepoInfo = /** @class */ (function () { /** * @param host - Hostname portion of the url for the repo * @param secure - Whether or not this repo is accessed over ssl * @param namespace - The namespace represented by the repo * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). * @param nodeAdmin - Whether this instance uses Admin SDK credentials * @param persistenceKey - Override the default session persistence storage key */ function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) { if (nodeAdmin === void 0) { nodeAdmin = false; } if (persistenceKey === void 0) { persistenceKey = ''; } if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; } this.secure = secure; this.namespace = namespace; this.webSocketOnly = webSocketOnly; this.nodeAdmin = nodeAdmin; this.persistenceKey = persistenceKey; this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; this._host = host.toLowerCase(); this._domain = this._host.substr(this._host.indexOf('.') + 1); this.internalHost = PersistentStorage.get('host:' + host) || this._host; } RepoInfo.prototype.isCacheableHost = function () { return this.internalHost.substr(0, 2) === 's-'; }; RepoInfo.prototype.isCustomHost = function () { return (this._domain !== 'firebaseio.com' && this._domain !== 'firebaseio-demo.com'); }; Object.defineProperty(RepoInfo.prototype, "host", { get: function () { return this._host; }, set: function (newHost) { if (newHost !== this.internalHost) { this.internalHost = newHost; if (this.isCacheableHost()) { PersistentStorage.set('host:' + this._host, this.internalHost); } } }, enumerable: false, configurable: true }); RepoInfo.prototype.toString = function () { var str = this.toURLString(); if (this.persistenceKey) { str += '<' + this.persistenceKey + '>'; } return str; }; RepoInfo.prototype.toURLString = function () { var protocol = this.secure ? 'https://' : 'http://'; var query = this.includeNamespaceInQueryParams ? "?ns=" + this.namespace : ''; return "" + protocol + this.host + "/" + query; }; return RepoInfo; }()); function repoInfoNeedsQueryParam(repoInfo) { return (repoInfo.host !== repoInfo.internalHost || repoInfo.isCustomHost() || repoInfo.includeNamespaceInQueryParams); } /** * Returns the websocket URL for this repo * @param repoInfo - RepoInfo object * @param type - of connection * @param params - list * @returns The URL for this repo */ function repoInfoConnectionURL(repoInfo, type, params) { util.assert(typeof type === 'string', 'typeof type must == string'); util.assert(typeof params === 'object', 'typeof params must == object'); var connURL; if (type === WEBSOCKET) { connURL = (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; } else if (type === LONG_POLLING) { connURL = (repoInfo.secure ? 'https://' : 'http://') + repoInfo.internalHost + '/.lp?'; } else { throw new Error('Unknown connection type: ' + type); } if (repoInfoNeedsQueryParam(repoInfo)) { params['ns'] = repoInfo.namespace; } var pairs = []; each(params, function (key, value) { pairs.push(key + '=' + value); }); return connURL + pairs.join('&'); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Tracks a collection of stats. */ var StatsCollection = /** @class */ (function () { function StatsCollection() { this.counters_ = {}; } StatsCollection.prototype.incrementCounter = function (name, amount) { if (amount === void 0) { amount = 1; } if (!util.contains(this.counters_, name)) { this.counters_[name] = 0; } this.counters_[name] += amount; }; StatsCollection.prototype.get = function () { return util.deepCopy(this.counters_); }; return StatsCollection; }()); /** * @license * Copyright 2017 Google LLC * * 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 collections = {}; var reporters = {}; function statsManagerGetCollection(repoInfo) { var hashString = repoInfo.toString(); if (!collections[hashString]) { collections[hashString] = new StatsCollection(); } return collections[hashString]; } function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { var hashString = repoInfo.toString(); if (!reporters[hashString]) { reporters[hashString] = creatorFunction(); } return reporters[hashString]; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** The semver (www.semver.org) version of the SDK. */ var SDK_VERSION = ''; /** * SDK_VERSION should be set before any database instance is created * @internal */ function setSDKVersion(version) { SDK_VERSION = version; } /** * @license * Copyright 2017 Google LLC * * 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 WEBSOCKET_MAX_FRAME_SIZE = 16384; var WEBSOCKET_KEEPALIVE_INTERVAL = 45000; var WebSocketImpl = null; if (typeof MozWebSocket !== 'undefined') { WebSocketImpl = MozWebSocket; } else if (typeof WebSocket !== 'undefined') { WebSocketImpl = WebSocket; } function setWebSocketImpl(impl) { WebSocketImpl = impl; } /** * Create a new websocket connection with the given callbacks. */ var WebSocketConnection = /** @class */ (function () { /**
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/database/dist/node-esm/index.node.esm.js
aws/lti-middleware/node_modules/@firebase/database/dist/node-esm/index.node.esm.js
import Websocket from 'faye-websocket'; import { stringify, jsonEval, contains, assert, isNodeSdk, base64, stringToByteArray, Sha1, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, createMockUserToken } from '@firebase/util'; import { Logger, LogLevel } from '@firebase/logger'; import { getApp, _getProvider, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app'; import { Component } from '@firebase/component'; /** * @license * Copyright 2017 Google LLC * * 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 PROTOCOL_VERSION = '5'; const VERSION_PARAM = 'v'; const TRANSPORT_SESSION_PARAM = 's'; const REFERER_PARAM = 'r'; const FORGE_REF = 'f'; // Matches console.firebase.google.com, firebase-console-*.corp.google.com and // firebase.corp.google.com const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/; const LAST_SESSION_PARAM = 'ls'; const APPLICATION_ID_PARAM = 'p'; const APP_CHECK_TOKEN_PARAM = 'ac'; const WEBSOCKET = 'websocket'; const LONG_POLLING = 'long_polling'; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Wraps a DOM Storage object and: * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. * - prefixes names with "firebase:" to avoid collisions with app data. * * We automatically (see storage.js) create two such wrappers, one for sessionStorage, * and one for localStorage. * */ class DOMStorageWrapper { /** * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage) */ constructor(domStorage_) { this.domStorage_ = domStorage_; // Use a prefix to avoid collisions with other stuff saved by the app. this.prefix_ = 'firebase:'; } /** * @param key - The key to save the value under * @param value - The value being stored, or null to remove the key. */ set(key, value) { if (value == null) { this.domStorage_.removeItem(this.prefixedName_(key)); } else { this.domStorage_.setItem(this.prefixedName_(key), stringify(value)); } } /** * @returns The value that was stored under this key, or null */ get(key) { const storedVal = this.domStorage_.getItem(this.prefixedName_(key)); if (storedVal == null) { return null; } else { return jsonEval(storedVal); } } remove(key) { this.domStorage_.removeItem(this.prefixedName_(key)); } prefixedName_(name) { return this.prefix_ + name; } toString() { return this.domStorage_.toString(); } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An in-memory storage implementation that matches the API of DOMStorageWrapper * (TODO: create interface for both to implement). */ class MemoryStorage { constructor() { this.cache_ = {}; this.isInMemoryStorage = true; } set(key, value) { if (value == null) { delete this.cache_[key]; } else { this.cache_[key] = value; } } get(key) { if (contains(this.cache_, key)) { return this.cache_[key]; } return null; } remove(key) { delete this.cache_[key]; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change * to reflect this type * * @param domStorageName - Name of the underlying storage object * (e.g. 'localStorage' or 'sessionStorage'). * @returns Turning off type information until a common interface is defined. */ const createStoragefor = function (domStorageName) { try { // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, // so it must be inside the try/catch. if (typeof window !== 'undefined' && typeof window[domStorageName] !== 'undefined') { // Need to test cache. Just because it's here doesn't mean it works const domStorage = window[domStorageName]; domStorage.setItem('firebase:sentinel', 'cache'); domStorage.removeItem('firebase:sentinel'); return new DOMStorageWrapper(domStorage); } } catch (e) { } // Failed to create wrapper. Just return in-memory storage. // TODO: log? return new MemoryStorage(); }; /** A storage object that lasts across sessions */ const PersistentStorage = createStoragefor('localStorage'); /** A storage object that only lasts one session */ const SessionStorage = createStoragefor('sessionStorage'); /** * @license * Copyright 2017 Google LLC * * 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 logClient = new Logger('@firebase/database'); /** * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). */ const LUIDGenerator = (function () { let id = 1; return function () { return id++; }; })(); /** * Sha1 hash of the input string * @param str - The string to hash * @returns {!string} The resulting hash */ const sha1 = function (str) { const utf8Bytes = stringToByteArray(str); const sha1 = new Sha1(); sha1.update(utf8Bytes); const sha1Bytes = sha1.digest(); return base64.encodeByteArray(sha1Bytes); }; const buildLogMessage_ = function (...varArgs) { let message = ''; for (let i = 0; i < varArgs.length; i++) { const arg = varArgs[i]; if (Array.isArray(arg) || (arg && typeof arg === 'object' && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof arg.length === 'number')) { message += buildLogMessage_.apply(null, arg); } else if (typeof arg === 'object') { message += stringify(arg); } else { message += arg; } message += ' '; } return message; }; /** * Use this for all debug messages in Firebase. */ let logger = null; /** * Flag to check for log availability on first log message */ let firstLog_ = true; /** * The implementation of Firebase.enableLogging (defined here to break dependencies) * @param logger_ - A flag to turn on logging, or a custom logger * @param persistent - Whether or not to persist logging settings across refreshes */ const enableLogging$1 = function (logger_, persistent) { assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently."); if (logger_ === true) { logClient.logLevel = LogLevel.VERBOSE; logger = logClient.log.bind(logClient); if (persistent) { SessionStorage.set('logging_enabled', true); } } else if (typeof logger_ === 'function') { logger = logger_; } else { logger = null; SessionStorage.remove('logging_enabled'); } }; const log = function (...varArgs) { if (firstLog_ === true) { firstLog_ = false; if (logger === null && SessionStorage.get('logging_enabled') === true) { enableLogging$1(true); } } if (logger) { const message = buildLogMessage_.apply(null, varArgs); logger(message); } }; const logWrapper = function (prefix) { return function (...varArgs) { log(prefix, ...varArgs); }; }; const error = function (...varArgs) { const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs); logClient.error(message); }; const fatal = function (...varArgs) { const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`; logClient.error(message); throw new Error(message); }; const warn = function (...varArgs) { const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs); logClient.warn(message); }; /** * Logs a warning if the containing page uses https. Called when a call to new Firebase * does not use https. */ const warnIfPageIsSecure = function () { // Be very careful accessing browser globals. Who knows what may or may not exist. if (typeof window !== 'undefined' && window.location && window.location.protocol && window.location.protocol.indexOf('https:') !== -1) { warn('Insecure Firebase access from a secure page. ' + 'Please use https in calls to new Firebase().'); } }; /** * Returns true if data is NaN, or +/- Infinity. */ const isInvalidJSONNumber = function (data) { return (typeof data === 'number' && (data !== data || // NaN data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY)); }; const executeWhenDOMReady = function (fn) { if (isNodeSdk() || document.readyState === 'complete') { fn(); } else { // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which // fire before onload), but fall back to onload. let called = false; const wrappedFn = function () { if (!document.body) { setTimeout(wrappedFn, Math.floor(10)); return; } if (!called) { called = true; fn(); } }; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', wrappedFn, false); // fallback to onload. window.addEventListener('load', wrappedFn, false); // eslint-disable-next-line @typescript-eslint/no-explicit-any } else if (document.attachEvent) { // IE. // eslint-disable-next-line @typescript-eslint/no-explicit-any document.attachEvent('onreadystatechange', () => { if (document.readyState === 'complete') { wrappedFn(); } }); // fallback to onload. // eslint-disable-next-line @typescript-eslint/no-explicit-any window.attachEvent('onload', wrappedFn); // jQuery has an extra hack for IE that we could employ (based on // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. // I'm hoping we don't need it. } } }; /** * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names */ const MIN_NAME = '[MIN_NAME]'; /** * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names */ const MAX_NAME = '[MAX_NAME]'; /** * Compares valid Firebase key names, plus min and max name */ const nameCompare = function (a, b) { if (a === b) { return 0; } else if (a === MIN_NAME || b === MAX_NAME) { return -1; } else if (b === MIN_NAME || a === MAX_NAME) { return 1; } else { const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); if (aAsInt !== null) { if (bAsInt !== null) { return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt; } else { return -1; } } else if (bAsInt !== null) { return 1; } else { return a < b ? -1 : 1; } } }; /** * @returns {!number} comparison result. */ const stringCompare = function (a, b) { if (a === b) { return 0; } else if (a < b) { return -1; } else { return 1; } }; const requireKey = function (key, obj) { if (obj && key in obj) { return obj[key]; } else { throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj)); } }; const ObjectToUniqueKey = function (obj) { if (typeof obj !== 'object' || obj === null) { return stringify(obj); } const keys = []; // eslint-disable-next-line guard-for-in for (const k in obj) { keys.push(k); } // Export as json, but with the keys sorted. keys.sort(); let key = '{'; for (let i = 0; i < keys.length; i++) { if (i !== 0) { key += ','; } key += stringify(keys[i]); key += ':'; key += ObjectToUniqueKey(obj[keys[i]]); } key += '}'; return key; }; /** * Splits a string into a number of smaller segments of maximum size * @param str - The string * @param segsize - The maximum number of chars in the string. * @returns The string, split into appropriately-sized chunks */ const splitStringBySize = function (str, segsize) { const len = str.length; if (len <= segsize) { return [str]; } const dataSegs = []; for (let c = 0; c < len; c += segsize) { if (c + segsize > len) { dataSegs.push(str.substring(c, len)); } else { dataSegs.push(str.substring(c, c + segsize)); } } return dataSegs; }; /** * Apply a function to each (key, value) pair in an object or * apply a function to each (index, value) pair in an array * @param obj - The object or array to iterate over * @param fn - The function to apply */ function each(obj, fn) { for (const key in obj) { if (obj.hasOwnProperty(key)) { fn(key, obj[key]); } } } /** * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) * I made one modification at the end and removed the NaN / Infinity * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. * @param v - A double * */ const doubleToIEEE754String = function (v) { assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL const ebits = 11, fbits = 52; const bias = (1 << (ebits - 1)) - 1; let s, e, f, ln, i; // Compute sign, exponent, fraction // Skip NaN / Infinity handling --MJL. if (v === 0) { e = 0; f = 0; s = 1 / v === -Infinity ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { // Normalized ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); e = ln + bias; f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); } else { // Denormalized e = 0; f = Math.round(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction const bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); const str = bits.join(''); // Return the data as a hex string. --MJL let hexByteString = ''; for (i = 0; i < 64; i += 8) { let hexByte = parseInt(str.substr(i, 8), 2).toString(16); if (hexByte.length === 1) { hexByte = '0' + hexByte; } hexByteString = hexByteString + hexByte; } return hexByteString.toLowerCase(); }; /** * Used to detect if we're in a Chrome content script (which executes in an * isolated environment where long-polling doesn't work). */ const isChromeExtensionContentScript = function () { return !!(typeof window === 'object' && window['chrome'] && window['chrome']['extension'] && !/^chrome/.test(window.location.href)); }; /** * Used to detect if we're in a Windows 8 Store app. */ const isWindowsStoreApp = function () { // Check for the presence of a couple WinRT globals return typeof Windows === 'object' && typeof Windows.UI === 'object'; }; /** * Converts a server error code to a Javascript Error */ function errorForServerCode(code, query) { let reason = 'Unknown Error'; if (code === 'too_big') { reason = 'The data requested exceeds the maximum size ' + 'that can be accessed with a single request.'; } else if (code === 'permission_denied') { reason = "Client doesn't have permission to access the desired data."; } else if (code === 'unavailable') { reason = 'The service is unavailable'; } const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason); // eslint-disable-next-line @typescript-eslint/no-explicit-any error.code = code.toUpperCase(); return error; } /** * Used to test for integer-looking strings */ const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$'); /** * For use in keys, the minimum possible 32-bit integer. */ const INTEGER_32_MIN = -2147483648; /** * For use in kyes, the maximum possible 32-bit integer. */ const INTEGER_32_MAX = 2147483647; /** * If the string contains a 32-bit integer, return it. Else return null. */ const tryParseInt = function (str) { if (INTEGER_REGEXP_.test(str)) { const intVal = Number(str); if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) { return intVal; } } return null; }; /** * Helper to run some code but catch any exceptions and re-throw them later. * Useful for preventing user callbacks from breaking internal code. * * Re-throwing the exception from a setTimeout is a little evil, but it's very * convenient (we don't have to try to figure out when is a safe point to * re-throw it), and the behavior seems reasonable: * * * If you aren't pausing on exceptions, you get an error in the console with * the correct stack trace. * * If you're pausing on all exceptions, the debugger will pause on your * exception and then again when we rethrow it. * * If you're only pausing on uncaught exceptions, the debugger will only pause * on us re-throwing it. * * @param fn - The code to guard. */ const exceptionGuard = function (fn) { try { fn(); } catch (e) { // Re-throw exception when it's safe. setTimeout(() => { // It used to be that "throw e" would result in a good console error with // relevant context, but as of Chrome 39, you just get the firebase.js // file/line number where we re-throw it, which is useless. So we log // e.stack explicitly. const stack = e.stack || ''; warn('Exception was thrown by user callback.', stack); throw e; }, Math.floor(0)); } }; /** * @returns {boolean} true if we think we're currently being crawled. */ const beingCrawled = function () { const userAgent = (typeof window === 'object' && window['navigator'] && window['navigator']['userAgent']) || ''; // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we // believe to support JavaScript/AJAX rendering. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website // would have seen the page" is flaky if we don't treat it as a crawler. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); }; /** * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. * * It is removed with clearTimeout() as normal. * * @param fn - Function to run. * @param time - Milliseconds to wait before running. * @returns The setTimeout() return value. */ const setTimeoutNonBlocking = function (fn, time) { const timeout = setTimeout(fn, time); // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof timeout === 'object' && timeout['unref']) { // eslint-disable-next-line @typescript-eslint/no-explicit-any timeout['unref'](); } return timeout; }; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * A class that holds metadata about a Repo object */ class RepoInfo { /** * @param host - Hostname portion of the url for the repo * @param secure - Whether or not this repo is accessed over ssl * @param namespace - The namespace represented by the repo * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). * @param nodeAdmin - Whether this instance uses Admin SDK credentials * @param persistenceKey - Override the default session persistence storage key */ constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false) { this.secure = secure; this.namespace = namespace; this.webSocketOnly = webSocketOnly; this.nodeAdmin = nodeAdmin; this.persistenceKey = persistenceKey; this.includeNamespaceInQueryParams = includeNamespaceInQueryParams; this._host = host.toLowerCase(); this._domain = this._host.substr(this._host.indexOf('.') + 1); this.internalHost = PersistentStorage.get('host:' + host) || this._host; } isCacheableHost() { return this.internalHost.substr(0, 2) === 's-'; } isCustomHost() { return (this._domain !== 'firebaseio.com' && this._domain !== 'firebaseio-demo.com'); } get host() { return this._host; } set host(newHost) { if (newHost !== this.internalHost) { this.internalHost = newHost; if (this.isCacheableHost()) { PersistentStorage.set('host:' + this._host, this.internalHost); } } } toString() { let str = this.toURLString(); if (this.persistenceKey) { str += '<' + this.persistenceKey + '>'; } return str; } toURLString() { const protocol = this.secure ? 'https://' : 'http://'; const query = this.includeNamespaceInQueryParams ? `?ns=${this.namespace}` : ''; return `${protocol}${this.host}/${query}`; } } function repoInfoNeedsQueryParam(repoInfo) { return (repoInfo.host !== repoInfo.internalHost || repoInfo.isCustomHost() || repoInfo.includeNamespaceInQueryParams); } /** * Returns the websocket URL for this repo * @param repoInfo - RepoInfo object * @param type - of connection * @param params - list * @returns The URL for this repo */ function repoInfoConnectionURL(repoInfo, type, params) { assert(typeof type === 'string', 'typeof type must == string'); assert(typeof params === 'object', 'typeof params must == object'); let connURL; if (type === WEBSOCKET) { connURL = (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?'; } else if (type === LONG_POLLING) { connURL = (repoInfo.secure ? 'https://' : 'http://') + repoInfo.internalHost + '/.lp?'; } else { throw new Error('Unknown connection type: ' + type); } if (repoInfoNeedsQueryParam(repoInfo)) { params['ns'] = repoInfo.namespace; } const pairs = []; each(params, (key, value) => { pairs.push(key + '=' + value); }); return connURL + pairs.join('&'); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Tracks a collection of stats. */ class StatsCollection { constructor() { this.counters_ = {}; } incrementCounter(name, amount = 1) { if (!contains(this.counters_, name)) { this.counters_[name] = 0; } this.counters_[name] += amount; } get() { return deepCopy(this.counters_); } } /** * @license * Copyright 2017 Google LLC * * 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 collections = {}; const reporters = {}; function statsManagerGetCollection(repoInfo) { const hashString = repoInfo.toString(); if (!collections[hashString]) { collections[hashString] = new StatsCollection(); } return collections[hashString]; } function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) { const hashString = repoInfo.toString(); if (!reporters[hashString]) { reporters[hashString] = creatorFunction(); } return reporters[hashString]; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** The semver (www.semver.org) version of the SDK. */ let SDK_VERSION = ''; /** * SDK_VERSION should be set before any database instance is created * @internal */ function setSDKVersion(version) { SDK_VERSION = version; } /** * @license * Copyright 2017 Google LLC * * 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 WEBSOCKET_MAX_FRAME_SIZE = 16384; const WEBSOCKET_KEEPALIVE_INTERVAL = 45000; let WebSocketImpl = null; if (typeof MozWebSocket !== 'undefined') { WebSocketImpl = MozWebSocket; } else if (typeof WebSocket !== 'undefined') { WebSocketImpl = WebSocket; } function setWebSocketImpl(impl) { WebSocketImpl = impl; } /** * Create a new websocket connection with the given callbacks. */ class WebSocketConnection { /** * @param connId identifier for this transport * @param repoInfo The info for the websocket endpoint. * @param applicationId The Firebase App ID for this project. * @param appCheckToken The App Check Token for this client. * @param authToken The Auth Token for this client. * @param transportSessionId Optional transportSessionId if this is connecting * to an existing transport session * @param lastSessionId Optional lastSessionId if there was a previous * connection */ constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) { this.connId = connId; this.applicationId = applicationId; this.appCheckToken = appCheckToken; this.authToken = authToken; this.keepaliveTimer = null; this.frames = null; this.totalFrames = 0; this.bytesSent = 0; this.bytesReceived = 0; this.log_ = logWrapper(this.connId); this.stats_ = statsManagerGetCollection(repoInfo); this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId); this.nodeAdmin = repoInfo.nodeAdmin; } /** * @param repoInfo - The info for the websocket endpoint. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport * session * @param lastSessionId - Optional lastSessionId if there was a previous connection * @returns connection url */ static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) { const urlParams = {}; urlParams[VERSION_PARAM] = PROTOCOL_VERSION; if (!isNodeSdk() && typeof location !== 'undefined' && location.hostname && FORGE_DOMAIN_RE.test(location.hostname)) { urlParams[REFERER_PARAM] = FORGE_REF; }
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/component/dist/index.cjs.js
aws/lti-middleware/node_modules/@firebase/component/dist/index.cjs.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var tslib = require('tslib'); var util = require('@firebase/util'); /** * Component for service name T, e.g. `auth`, `auth-internal` */ var Component = /** @class */ (function () { /** * * @param name The public service name, e.g. app, auth, firestore, database * @param instanceFactory Service factory responsible for creating the public interface * @param type whether the service provided by the component is public or private */ function Component(name, instanceFactory, type) { this.name = name; this.instanceFactory = instanceFactory; this.type = type; this.multipleInstances = false; /** * Properties to be added to the service namespace */ this.serviceProps = {}; this.instantiationMode = "LAZY" /* LAZY */; this.onInstanceCreated = null; } Component.prototype.setInstantiationMode = function (mode) { this.instantiationMode = mode; return this; }; Component.prototype.setMultipleInstances = function (multipleInstances) { this.multipleInstances = multipleInstances; return this; }; Component.prototype.setServiceProps = function (props) { this.serviceProps = props; return this; }; Component.prototype.setInstanceCreatedCallback = function (callback) { this.onInstanceCreated = callback; return this; }; return Component; }()); /** * @license * Copyright 2019 Google LLC * * 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 DEFAULT_ENTRY_NAME = '[DEFAULT]'; /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Provider for instance for service name T, e.g. 'auth', 'auth-internal' * NameServiceMapping[T] is an alias for the type of the instance */ var Provider = /** @class */ (function () { function Provider(name, container) { this.name = name; this.container = container; this.component = null; this.instances = new Map(); this.instancesDeferred = new Map(); this.instancesOptions = new Map(); this.onInitCallbacks = new Map(); } /** * @param identifier A provider can provide mulitple instances of a service * if this.component.multipleInstances is true. */ Provider.prototype.get = function (identifier) { // if multipleInstances is not supported, use the default name var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); if (!this.instancesDeferred.has(normalizedIdentifier)) { var deferred = new util.Deferred(); this.instancesDeferred.set(normalizedIdentifier, deferred); if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { // initialize the service if it can be auto-initialized try { var instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); if (instance) { deferred.resolve(instance); } } catch (e) { // when the instance factory throws an exception during get(), it should not cause // a fatal error. We just return the unresolved promise in this case. } } } return this.instancesDeferred.get(normalizedIdentifier).promise; }; Provider.prototype.getImmediate = function (options) { var _a; // if multipleInstances is not supported, use the default name var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); var optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false; if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { try { return this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); } catch (e) { if (optional) { return null; } else { throw e; } } } else { // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw if (optional) { return null; } else { throw Error("Service " + this.name + " is not available"); } } }; Provider.prototype.getComponent = function () { return this.component; }; Provider.prototype.setComponent = function (component) { var e_1, _a; if (component.name !== this.name) { throw Error("Mismatching Component " + component.name + " for Provider " + this.name + "."); } if (this.component) { throw Error("Component for " + this.name + " has already been provided"); } this.component = component; // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) if (!this.shouldAutoInitialize()) { return; } // if the service is eager, initialize the default instance if (isComponentEager(component)) { try { this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); } catch (e) { // when the instance factory for an eager Component throws an exception during the eager // initialization, it should not cause a fatal error. // TODO: Investigate if we need to make it configurable, because some component may want to cause // a fatal error in this case? } } try { // Create service instances for the pending promises and resolve them // NOTE: if this.multipleInstances is false, only the default instance will be created // and all promises with resolve with it regardless of the identifier. for (var _b = tslib.__values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = tslib.__read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1]; var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); try { // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. var instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); instanceDeferred.resolve(instance); } catch (e) { // when the instance factory throws an exception, it should not cause // a fatal error. We just leave the promise unresolved. } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }; Provider.prototype.clearInstance = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } this.instancesDeferred.delete(identifier); this.instancesOptions.delete(identifier); this.instances.delete(identifier); }; // app.delete() will call this method on every provider to delete the services // TODO: should we mark the provider as deleted? Provider.prototype.delete = function () { return tslib.__awaiter(this, void 0, void 0, function () { var services; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: services = Array.from(this.instances.values()); return [4 /*yield*/, Promise.all(tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(services .filter(function (service) { return 'INTERNAL' in service; }) // legacy services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(function (service) { return service.INTERNAL.delete(); }))), tslib.__read(services .filter(function (service) { return '_delete' in service; }) // modularized services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(function (service) { return service._delete(); }))))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; Provider.prototype.isComponentSet = function () { return this.component != null; }; Provider.prototype.isInitialized = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } return this.instances.has(identifier); }; Provider.prototype.getOptions = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } return this.instancesOptions.get(identifier) || {}; }; Provider.prototype.initialize = function (opts) { var e_2, _a; if (opts === void 0) { opts = {}; } var _b = opts.options, options = _b === void 0 ? {} : _b; var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); if (this.isInitialized(normalizedIdentifier)) { throw Error(this.name + "(" + normalizedIdentifier + ") has already been initialized"); } if (!this.isComponentSet()) { throw Error("Component " + this.name + " has not been registered yet"); } var instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier, options: options }); try { // resolve any pending promise waiting for the service instance for (var _c = tslib.__values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = tslib.__read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1]; var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); if (normalizedIdentifier === normalizedDeferredIdentifier) { instanceDeferred.resolve(instance); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_2) throw e_2.error; } } return instance; }; /** * * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. * * @param identifier An optional instance identifier * @returns a function to unregister the callback */ Provider.prototype.onInit = function (callback, identifier) { var _a; var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); existingCallbacks.add(callback); this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); var existingInstance = this.instances.get(normalizedIdentifier); if (existingInstance) { callback(existingInstance, normalizedIdentifier); } return function () { existingCallbacks.delete(callback); }; }; /** * Invoke onInit callbacks synchronously * @param instance the service instance` */ Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) { var e_3, _a; var callbacks = this.onInitCallbacks.get(identifier); if (!callbacks) { return; } try { for (var callbacks_1 = tslib.__values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { var callback = callbacks_1_1.value; try { callback(instance, identifier); } catch (_b) { // ignore errors in the onInit callback } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); } finally { if (e_3) throw e_3.error; } } }; Provider.prototype.getOrInitializeService = function (_a) { var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b; var instance = this.instances.get(instanceIdentifier); if (!instance && this.component) { instance = this.component.instanceFactory(this.container, { instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), options: options }); this.instances.set(instanceIdentifier, instance); this.instancesOptions.set(instanceIdentifier, options); /** * Invoke onInit listeners. * Note this.component.onInstanceCreated is different, which is used by the component creator, * while onInit listeners are registered by consumers of the provider. */ this.invokeOnInitCallbacks(instance, instanceIdentifier); /** * Order is important * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which * makes `isInitialized()` return true. */ if (this.component.onInstanceCreated) { try { this.component.onInstanceCreated(this.container, instanceIdentifier, instance); } catch (_c) { // ignore errors in the onInstanceCreatedCallback } } } return instance || null; }; Provider.prototype.normalizeInstanceIdentifier = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } if (this.component) { return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; } else { return identifier; // assume multiple instances are supported before the component is provided. } }; Provider.prototype.shouldAutoInitialize = function () { return (!!this.component && this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */); }; return Provider; }()); // undefined should be passed to the service factory for the default instance function normalizeIdentifierForFactory(identifier) { return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier; } function isComponentEager(component) { return component.instantiationMode === "EAGER" /* EAGER */; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` */ var ComponentContainer = /** @class */ (function () { function ComponentContainer(name) { this.name = name; this.providers = new Map(); } /** * * @param component Component being added * @param overwrite When a component with the same name has already been registered, * if overwrite is true: overwrite the existing component with the new component and create a new * provider with the new component. It can be useful in tests where you want to use different mocks * for different tests. * if overwrite is false: throw an exception */ ComponentContainer.prototype.addComponent = function (component) { var provider = this.getProvider(component.name); if (provider.isComponentSet()) { throw new Error("Component " + component.name + " has already been registered with " + this.name); } provider.setComponent(component); }; ComponentContainer.prototype.addOrOverwriteComponent = function (component) { var provider = this.getProvider(component.name); if (provider.isComponentSet()) { // delete the existing provider from the container, so we can register the new component this.providers.delete(component.name); } this.addComponent(component); }; /** * getProvider provides a type safe interface where it can only be called with a field name * present in NameServiceMapping interface. * * Firebase SDKs providing services should extend NameServiceMapping interface to register * themselves. */ ComponentContainer.prototype.getProvider = function (name) { if (this.providers.has(name)) { return this.providers.get(name); } // create a Provider for a service that hasn't registered with Firebase var provider = new Provider(name, this); this.providers.set(name, provider); return provider; }; ComponentContainer.prototype.getProviders = function () { return Array.from(this.providers.values()); }; return ComponentContainer; }()); exports.Component = Component; exports.ComponentContainer = ComponentContainer; exports.Provider = Provider; //# sourceMappingURL=index.cjs.js.map
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/component/dist/esm/index.esm5.js
aws/lti-middleware/node_modules/@firebase/component/dist/esm/index.esm5.js
import { __values, __read, __awaiter, __generator, __spreadArray } from 'tslib'; import { Deferred } from '@firebase/util'; /** * Component for service name T, e.g. `auth`, `auth-internal` */ var Component = /** @class */ (function () { /** * * @param name The public service name, e.g. app, auth, firestore, database * @param instanceFactory Service factory responsible for creating the public interface * @param type whether the service provided by the component is public or private */ function Component(name, instanceFactory, type) { this.name = name; this.instanceFactory = instanceFactory; this.type = type; this.multipleInstances = false; /** * Properties to be added to the service namespace */ this.serviceProps = {}; this.instantiationMode = "LAZY" /* LAZY */; this.onInstanceCreated = null; } Component.prototype.setInstantiationMode = function (mode) { this.instantiationMode = mode; return this; }; Component.prototype.setMultipleInstances = function (multipleInstances) { this.multipleInstances = multipleInstances; return this; }; Component.prototype.setServiceProps = function (props) { this.serviceProps = props; return this; }; Component.prototype.setInstanceCreatedCallback = function (callback) { this.onInstanceCreated = callback; return this; }; return Component; }()); /** * @license * Copyright 2019 Google LLC * * 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 DEFAULT_ENTRY_NAME = '[DEFAULT]'; /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Provider for instance for service name T, e.g. 'auth', 'auth-internal' * NameServiceMapping[T] is an alias for the type of the instance */ var Provider = /** @class */ (function () { function Provider(name, container) { this.name = name; this.container = container; this.component = null; this.instances = new Map(); this.instancesDeferred = new Map(); this.instancesOptions = new Map(); this.onInitCallbacks = new Map(); } /** * @param identifier A provider can provide mulitple instances of a service * if this.component.multipleInstances is true. */ Provider.prototype.get = function (identifier) { // if multipleInstances is not supported, use the default name var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); if (!this.instancesDeferred.has(normalizedIdentifier)) { var deferred = new Deferred(); this.instancesDeferred.set(normalizedIdentifier, deferred); if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { // initialize the service if it can be auto-initialized try { var instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); if (instance) { deferred.resolve(instance); } } catch (e) { // when the instance factory throws an exception during get(), it should not cause // a fatal error. We just return the unresolved promise in this case. } } } return this.instancesDeferred.get(normalizedIdentifier).promise; }; Provider.prototype.getImmediate = function (options) { var _a; // if multipleInstances is not supported, use the default name var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); var optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false; if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { try { return this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); } catch (e) { if (optional) { return null; } else { throw e; } } } else { // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw if (optional) { return null; } else { throw Error("Service " + this.name + " is not available"); } } }; Provider.prototype.getComponent = function () { return this.component; }; Provider.prototype.setComponent = function (component) { var e_1, _a; if (component.name !== this.name) { throw Error("Mismatching Component " + component.name + " for Provider " + this.name + "."); } if (this.component) { throw Error("Component for " + this.name + " has already been provided"); } this.component = component; // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) if (!this.shouldAutoInitialize()) { return; } // if the service is eager, initialize the default instance if (isComponentEager(component)) { try { this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); } catch (e) { // when the instance factory for an eager Component throws an exception during the eager // initialization, it should not cause a fatal error. // TODO: Investigate if we need to make it configurable, because some component may want to cause // a fatal error in this case? } } try { // Create service instances for the pending promises and resolve them // NOTE: if this.multipleInstances is false, only the default instance will be created // and all promises with resolve with it regardless of the identifier. for (var _b = __values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = __read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1]; var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); try { // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. var instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); instanceDeferred.resolve(instance); } catch (e) { // when the instance factory throws an exception, it should not cause // a fatal error. We just leave the promise unresolved. } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }; Provider.prototype.clearInstance = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } this.instancesDeferred.delete(identifier); this.instancesOptions.delete(identifier); this.instances.delete(identifier); }; // app.delete() will call this method on every provider to delete the services // TODO: should we mark the provider as deleted? Provider.prototype.delete = function () { return __awaiter(this, void 0, void 0, function () { var services; return __generator(this, function (_a) { switch (_a.label) { case 0: services = Array.from(this.instances.values()); return [4 /*yield*/, Promise.all(__spreadArray(__spreadArray([], __read(services .filter(function (service) { return 'INTERNAL' in service; }) // legacy services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(function (service) { return service.INTERNAL.delete(); }))), __read(services .filter(function (service) { return '_delete' in service; }) // modularized services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(function (service) { return service._delete(); }))))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; Provider.prototype.isComponentSet = function () { return this.component != null; }; Provider.prototype.isInitialized = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } return this.instances.has(identifier); }; Provider.prototype.getOptions = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } return this.instancesOptions.get(identifier) || {}; }; Provider.prototype.initialize = function (opts) { var e_2, _a; if (opts === void 0) { opts = {}; } var _b = opts.options, options = _b === void 0 ? {} : _b; var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); if (this.isInitialized(normalizedIdentifier)) { throw Error(this.name + "(" + normalizedIdentifier + ") has already been initialized"); } if (!this.isComponentSet()) { throw Error("Component " + this.name + " has not been registered yet"); } var instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier, options: options }); try { // resolve any pending promise waiting for the service instance for (var _c = __values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = __read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1]; var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); if (normalizedIdentifier === normalizedDeferredIdentifier) { instanceDeferred.resolve(instance); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_2) throw e_2.error; } } return instance; }; /** * * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. * * @param identifier An optional instance identifier * @returns a function to unregister the callback */ Provider.prototype.onInit = function (callback, identifier) { var _a; var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); existingCallbacks.add(callback); this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); var existingInstance = this.instances.get(normalizedIdentifier); if (existingInstance) { callback(existingInstance, normalizedIdentifier); } return function () { existingCallbacks.delete(callback); }; }; /** * Invoke onInit callbacks synchronously * @param instance the service instance` */ Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) { var e_3, _a; var callbacks = this.onInitCallbacks.get(identifier); if (!callbacks) { return; } try { for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { var callback = callbacks_1_1.value; try { callback(instance, identifier); } catch (_b) { // ignore errors in the onInit callback } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); } finally { if (e_3) throw e_3.error; } } }; Provider.prototype.getOrInitializeService = function (_a) { var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b; var instance = this.instances.get(instanceIdentifier); if (!instance && this.component) { instance = this.component.instanceFactory(this.container, { instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), options: options }); this.instances.set(instanceIdentifier, instance); this.instancesOptions.set(instanceIdentifier, options); /** * Invoke onInit listeners. * Note this.component.onInstanceCreated is different, which is used by the component creator, * while onInit listeners are registered by consumers of the provider. */ this.invokeOnInitCallbacks(instance, instanceIdentifier); /** * Order is important * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which * makes `isInitialized()` return true. */ if (this.component.onInstanceCreated) { try { this.component.onInstanceCreated(this.container, instanceIdentifier, instance); } catch (_c) { // ignore errors in the onInstanceCreatedCallback } } } return instance || null; }; Provider.prototype.normalizeInstanceIdentifier = function (identifier) { if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; } if (this.component) { return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; } else { return identifier; // assume multiple instances are supported before the component is provided. } }; Provider.prototype.shouldAutoInitialize = function () { return (!!this.component && this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */); }; return Provider; }()); // undefined should be passed to the service factory for the default instance function normalizeIdentifierForFactory(identifier) { return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier; } function isComponentEager(component) { return component.instantiationMode === "EAGER" /* EAGER */; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` */ var ComponentContainer = /** @class */ (function () { function ComponentContainer(name) { this.name = name; this.providers = new Map(); } /** * * @param component Component being added * @param overwrite When a component with the same name has already been registered, * if overwrite is true: overwrite the existing component with the new component and create a new * provider with the new component. It can be useful in tests where you want to use different mocks * for different tests. * if overwrite is false: throw an exception */ ComponentContainer.prototype.addComponent = function (component) { var provider = this.getProvider(component.name); if (provider.isComponentSet()) { throw new Error("Component " + component.name + " has already been registered with " + this.name); } provider.setComponent(component); }; ComponentContainer.prototype.addOrOverwriteComponent = function (component) { var provider = this.getProvider(component.name); if (provider.isComponentSet()) { // delete the existing provider from the container, so we can register the new component this.providers.delete(component.name); } this.addComponent(component); }; /** * getProvider provides a type safe interface where it can only be called with a field name * present in NameServiceMapping interface. * * Firebase SDKs providing services should extend NameServiceMapping interface to register * themselves. */ ComponentContainer.prototype.getProvider = function (name) { if (this.providers.has(name)) { return this.providers.get(name); } // create a Provider for a service that hasn't registered with Firebase var provider = new Provider(name, this); this.providers.set(name, provider); return provider; }; ComponentContainer.prototype.getProviders = function () { return Array.from(this.providers.values()); }; return ComponentContainer; }()); export { Component, ComponentContainer, Provider }; //# sourceMappingURL=index.esm5.js.map
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/component/dist/esm/index.esm2017.js
aws/lti-middleware/node_modules/@firebase/component/dist/esm/index.esm2017.js
import { Deferred } from '@firebase/util'; /** * Component for service name T, e.g. `auth`, `auth-internal` */ class Component { /** * * @param name The public service name, e.g. app, auth, firestore, database * @param instanceFactory Service factory responsible for creating the public interface * @param type whether the service provided by the component is public or private */ constructor(name, instanceFactory, type) { this.name = name; this.instanceFactory = instanceFactory; this.type = type; this.multipleInstances = false; /** * Properties to be added to the service namespace */ this.serviceProps = {}; this.instantiationMode = "LAZY" /* LAZY */; this.onInstanceCreated = null; } setInstantiationMode(mode) { this.instantiationMode = mode; return this; } setMultipleInstances(multipleInstances) { this.multipleInstances = multipleInstances; return this; } setServiceProps(props) { this.serviceProps = props; return this; } setInstanceCreatedCallback(callback) { this.onInstanceCreated = callback; return this; } } /** * @license * Copyright 2019 Google LLC * * 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 DEFAULT_ENTRY_NAME = '[DEFAULT]'; /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Provider for instance for service name T, e.g. 'auth', 'auth-internal' * NameServiceMapping[T] is an alias for the type of the instance */ class Provider { constructor(name, container) { this.name = name; this.container = container; this.component = null; this.instances = new Map(); this.instancesDeferred = new Map(); this.instancesOptions = new Map(); this.onInitCallbacks = new Map(); } /** * @param identifier A provider can provide mulitple instances of a service * if this.component.multipleInstances is true. */ get(identifier) { // if multipleInstances is not supported, use the default name const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); if (!this.instancesDeferred.has(normalizedIdentifier)) { const deferred = new Deferred(); this.instancesDeferred.set(normalizedIdentifier, deferred); if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { // initialize the service if it can be auto-initialized try { const instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); if (instance) { deferred.resolve(instance); } } catch (e) { // when the instance factory throws an exception during get(), it should not cause // a fatal error. We just return the unresolved promise in this case. } } } return this.instancesDeferred.get(normalizedIdentifier).promise; } getImmediate(options) { var _a; // if multipleInstances is not supported, use the default name const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false; if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { try { return this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); } catch (e) { if (optional) { return null; } else { throw e; } } } else { // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw if (optional) { return null; } else { throw Error(`Service ${this.name} is not available`); } } } getComponent() { return this.component; } setComponent(component) { if (component.name !== this.name) { throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`); } if (this.component) { throw Error(`Component for ${this.name} has already been provided`); } this.component = component; // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) if (!this.shouldAutoInitialize()) { return; } // if the service is eager, initialize the default instance if (isComponentEager(component)) { try { this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); } catch (e) { // when the instance factory for an eager Component throws an exception during the eager // initialization, it should not cause a fatal error. // TODO: Investigate if we need to make it configurable, because some component may want to cause // a fatal error in this case? } } // Create service instances for the pending promises and resolve them // NOTE: if this.multipleInstances is false, only the default instance will be created // and all promises with resolve with it regardless of the identifier. for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); try { // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. const instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); instanceDeferred.resolve(instance); } catch (e) { // when the instance factory throws an exception, it should not cause // a fatal error. We just leave the promise unresolved. } } } clearInstance(identifier = DEFAULT_ENTRY_NAME) { this.instancesDeferred.delete(identifier); this.instancesOptions.delete(identifier); this.instances.delete(identifier); } // app.delete() will call this method on every provider to delete the services // TODO: should we mark the provider as deleted? async delete() { const services = Array.from(this.instances.values()); await Promise.all([ ...services .filter(service => 'INTERNAL' in service) // legacy services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(service => service.INTERNAL.delete()), ...services .filter(service => '_delete' in service) // modularized services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(service => service._delete()) ]); } isComponentSet() { return this.component != null; } isInitialized(identifier = DEFAULT_ENTRY_NAME) { return this.instances.has(identifier); } getOptions(identifier = DEFAULT_ENTRY_NAME) { return this.instancesOptions.get(identifier) || {}; } initialize(opts = {}) { const { options = {} } = opts; const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); if (this.isInitialized(normalizedIdentifier)) { throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`); } if (!this.isComponentSet()) { throw Error(`Component ${this.name} has not been registered yet`); } const instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier, options }); // resolve any pending promise waiting for the service instance for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); if (normalizedIdentifier === normalizedDeferredIdentifier) { instanceDeferred.resolve(instance); } } return instance; } /** * * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. * * @param identifier An optional instance identifier * @returns a function to unregister the callback */ onInit(callback, identifier) { var _a; const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); existingCallbacks.add(callback); this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); const existingInstance = this.instances.get(normalizedIdentifier); if (existingInstance) { callback(existingInstance, normalizedIdentifier); } return () => { existingCallbacks.delete(callback); }; } /** * Invoke onInit callbacks synchronously * @param instance the service instance` */ invokeOnInitCallbacks(instance, identifier) { const callbacks = this.onInitCallbacks.get(identifier); if (!callbacks) { return; } for (const callback of callbacks) { try { callback(instance, identifier); } catch (_a) { // ignore errors in the onInit callback } } } getOrInitializeService({ instanceIdentifier, options = {} }) { let instance = this.instances.get(instanceIdentifier); if (!instance && this.component) { instance = this.component.instanceFactory(this.container, { instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), options }); this.instances.set(instanceIdentifier, instance); this.instancesOptions.set(instanceIdentifier, options); /** * Invoke onInit listeners. * Note this.component.onInstanceCreated is different, which is used by the component creator, * while onInit listeners are registered by consumers of the provider. */ this.invokeOnInitCallbacks(instance, instanceIdentifier); /** * Order is important * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which * makes `isInitialized()` return true. */ if (this.component.onInstanceCreated) { try { this.component.onInstanceCreated(this.container, instanceIdentifier, instance); } catch (_a) { // ignore errors in the onInstanceCreatedCallback } } } return instance || null; } normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) { if (this.component) { return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; } else { return identifier; // assume multiple instances are supported before the component is provided. } } shouldAutoInitialize() { return (!!this.component && this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */); } } // undefined should be passed to the service factory for the default instance function normalizeIdentifierForFactory(identifier) { return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier; } function isComponentEager(component) { return component.instantiationMode === "EAGER" /* EAGER */; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal` */ class ComponentContainer { constructor(name) { this.name = name; this.providers = new Map(); } /** * * @param component Component being added * @param overwrite When a component with the same name has already been registered, * if overwrite is true: overwrite the existing component with the new component and create a new * provider with the new component. It can be useful in tests where you want to use different mocks * for different tests. * if overwrite is false: throw an exception */ addComponent(component) { const provider = this.getProvider(component.name); if (provider.isComponentSet()) { throw new Error(`Component ${component.name} has already been registered with ${this.name}`); } provider.setComponent(component); } addOrOverwriteComponent(component) { const provider = this.getProvider(component.name); if (provider.isComponentSet()) { // delete the existing provider from the container, so we can register the new component this.providers.delete(component.name); } this.addComponent(component); } /** * getProvider provides a type safe interface where it can only be called with a field name * present in NameServiceMapping interface. * * Firebase SDKs providing services should extend NameServiceMapping interface to register * themselves. */ getProvider(name) { if (this.providers.has(name)) { return this.providers.get(name); } // create a Provider for a service that hasn't registered with Firebase const provider = new Provider(name, this); this.providers.set(name, provider); return provider; } getProviders() { return Array.from(this.providers.values()); } } export { Component, ComponentContainer, Provider }; //# sourceMappingURL=index.esm2017.js.map
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/async-retry/lib/index.js
aws/lti-middleware/node_modules/async-retry/lib/index.js
// Packages var retrier = require('retry'); function retry(fn, opts) { function run(resolve, reject) { var options = opts || {}; var op; // Default `randomize` to true if (!('randomize' in options)) { options.randomize = true; } op = retrier.operation(options); // We allow the user to abort retrying // this makes sense in the cases where // knowledge is obtained that retrying // would be futile (e.g.: auth errors) function bail(err) { reject(err || new Error('Aborted')); } function onError(err, num) { if (err.bail) { bail(err); return; } if (!op.retry(err)) { reject(op.mainError()); } else if (options.onRetry) { options.onRetry(err, num); } } function runAttempt(num) { var val; try { val = fn(bail, num); } catch (err) { onError(err, num); return; } Promise.resolve(val) .then(resolve) .catch(function catchIt(err) { onError(err, num); }); } op.attempt(runAttempt); } return new Promise(run); } module.exports = retry;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/readable.js
aws/lti-middleware/node_modules/readable-stream/readable.js
var Stream = require('stream'); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream.Readable; Object.assign(module.exports, Stream); module.exports.Stream = Stream; } else { exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); exports.finished = require('./lib/internal/streams/end-of-stream.js'); exports.pipeline = require('./lib/internal/streams/pipeline.js'); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/readable-browser.js
aws/lti-middleware/node_modules/readable-stream/readable-browser.js
exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); exports.finished = require('./lib/internal/streams/end-of-stream.js'); exports.pipeline = require('./lib/internal/streams/pipeline.js');
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/experimentalWarning.js
aws/lti-middleware/node_modules/readable-stream/experimentalWarning.js
'use strict' var experimentalWarnings = new Set(); function emitExperimentalWarning(feature) { if (experimentalWarnings.has(feature)) return; var msg = feature + ' is an experimental feature. This feature could ' + 'change at any time'; experimentalWarnings.add(feature); process.emitWarning(msg, 'ExperimentalWarning'); } function noop() {} module.exports.emitExperimentalWarning = process.emitWarning ? emitExperimentalWarning : noop;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/errors-browser.js
aws/lti-middleware/node_modules/readable-stream/errors-browser.js
'use strict'; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error; } function getMessage(arg1, arg2, arg3) { if (typeof message === 'string') { return message; } else { return message(arg1, arg2, arg3); } } var NodeError = /*#__PURE__*/ function (_Base) { _inheritsLoose(NodeError, _Base); function NodeError(arg1, arg2, arg3) { return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; } return NodeError; }(Base); NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { var len = expected.length; expected = expected.map(function (i) { return String(i); }); if (len > 2) { return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; } else if (len === 2) { return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { return "of ".concat(thing, " ").concat(expected[0]); } } else { return "of ".concat(thing, " ").concat(String(expected)); } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"'; }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' var determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } var msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } else { var type = includes(name, '.') ? 'property' : 'argument'; msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } msg += ". Received type ".concat(typeof actual); return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented'; }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg; }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/errors.js
aws/lti-middleware/node_modules/readable-stream/errors.js
'use strict'; const codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error } function getMessage (arg1, arg2, arg3) { if (typeof message === 'string') { return message } else { return message(arg1, arg2, arg3) } } class NodeError extends Base { constructor (arg1, arg2, arg3) { super(getMessage(arg1, arg2, arg3)); } } NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { const len = expected.length; expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"' }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = includes(name, '.') ? 'property' : 'argument'; msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented' }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/_stream_writable.js
aws/lti-middleware/node_modules/readable-stream/lib/_stream_writable.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; module.exports = Writable; /* <replacement> */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* </replacement> */ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var internalUtil = { deprecate: require('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ var Buffer = require('buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = require('./internal/streams/destroy'); var _require = require('./internal/streams/state'), getHighWaterMark = _require.getHighWaterMark; var _require$codes = require('../errors').codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; require('inherits')(Writable, Stream); function nop() {} function WritableState(options, stream, isDuplex) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') this.autoDestroy = !!options.autoDestroy; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function writableStateBufferGetter() { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function realHasInstance(object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); this._writableState = new WritableState(options, this, isDuplex); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; function writeAfterEnd(stream, cb) { var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); process.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var er; if (chunk === null) { er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } if (er) { errorOrDestroy(stream, er); process.nextTick(cb, er); return false; } return true; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { this._writableState.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; Object.defineProperty(Writable.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack process.nextTick(cb, er); // this can emit finish, and it will always happen // after error process.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state) || stream.destroyed; if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { process.nextTick(afterWrite, stream, state, finished, cb); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); return this; }; Object.defineProperty(Writable.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { errorOrDestroy(stream, err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { state.pendingcb++; state.finalCalled = true; process.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well var rState = stream._readableState; if (!rState || rState.autoDestroy && rState.endEmitted) { stream.destroy(); } } } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { cb(err); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/_stream_duplex.js
aws/lti-middleware/node_modules/readable-stream/lib/_stream_duplex.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys; }; /*</replacement>*/ module.exports = Duplex; var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); require('inherits')(Duplex, Readable); { // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); this.allowHalfOpen = true; if (options) { if (options.readable === false) this.readable = false; if (options.writable === false) this.writable = false; if (options.allowHalfOpen === false) { this.allowHalfOpen = false; this.once('end', onend); } } } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); Object.defineProperty(Duplex.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); Object.defineProperty(Duplex.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); // the no-half-open enforcer function onend() { // If the writable side ended, then we're ok. if (this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = 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/readable-stream/lib/_stream_passthrough.js
aws/lti-middleware/node_modules/readable-stream/lib/_stream_passthrough.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); require('inherits')(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/_stream_transform.js
aws/lti-middleware/node_modules/readable-stream/lib/_stream_transform.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var _require$codes = require('../errors').codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = require('./_stream_duplex'); require('inherits')(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(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/readable-stream/lib/_stream_readable.js
aws/lti-middleware/node_modules/readable-stream/lib/_stream_readable.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; module.exports = Readable; /*<replacement>*/ var Duplex; /*</replacement>*/ Readable.ReadableState = ReadableState; /*<replacement>*/ var EE = require('events').EventEmitter; var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ var Buffer = require('buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*<replacement>*/ var debugUtil = require('util'); var debug; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function debug() {}; } /*</replacement>*/ var BufferList = require('./internal/streams/buffer_list'); var destroyImpl = require('./internal/streams/destroy'); var _require = require('./internal/streams/state'), getHighWaterMark = _require.getHighWaterMark; var _require$codes = require('../errors').codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. var StringDecoder; var createReadableStreamAsyncIterator; var from; require('inherits')(Readable, Stream); var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream, isDuplex) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; this.paused = true; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') this.autoDestroy = !!options.autoDestroy; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside // the ReadableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; this._readableState = new ReadableState(options, this, isDuplex); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { debug('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); } else if (state.destroyed) { return false; } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; maybeReadMore(stream, state); } } // We can push more data if we are below the highWaterMark. // Also, if we have no data yet, we can stand some more bytes. // This is to work around cases where hwm=0, such as the repl. return !state.ended && (state.length < state.highWaterMark || state.length === 0); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { state.awaitDrain = 0; stream.emit('data', chunk); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } return er; } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; var decoder = new StringDecoder(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: var p = this._readableState.buffer.head; var content = ''; while (p !== null) { content += decoder.write(p.data); p = p.next; } this._readableState.buffer.clear(); if (content !== '') this._readableState.buffer.push(content); this._readableState.length = content.length; return this; }; // Don't raise the hwm > 1GB var MAX_HWM = 0x40000000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n; state.awaitDrain = 0; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { debug('onEofChunk'); if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; if (state.sync) { // if we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() // the readable code triggers during a read() call emitReadable(stream); } else { // emit 'readable' now to make sure it gets picked up. state.needReadable = false; if (!state.emittedReadable) { state.emittedReadable = true; emitReadable_(stream); } } } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; process.nextTick(emitReadable_, stream); } } function emitReadable_(stream) { var state = stream._readableState; debug('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); state.emittedReadable = false; } // The stream needs another readable event if // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // // The conditions for reading more data are (one of): // - Not enough data buffered (state.length < state.highWaterMark). The loop // is responsible for filling the buffer with enough data if such data // is available. If highWaterMark is 0 and we are not in the flowing mode // we should _not_ attempt to buffer any extra data. We'll get more data // when the stream consumer calls read() instead. // - No data in the buffer, and the stream is in flowing mode. In this mode // the loop below is responsible for ensuring read() is called. Failing to // call read here would abort the flow and there's no other mechanism for // continuing the flow if the stream consumer has just subscribed to the // 'data' event. // // In addition to the above conditions to keep reading data, the following // conditions prevent the data from being read: // - The stream has ended (state.ended). // - There is already a pending 'read' operation (state.reading). This is a // case where the the stream has called the implementation defined _read() // method, but they are processing the call asynchronously and have _not_ // called push() with new data. In this case we skip performing more // read()s. The execution ends in this method again after the _read() ends // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } src.on('data', ondata); function ondata(chunk) { debug('ondata'); var ret = dest.write(chunk); debug('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, { hasUnpiped: false }); } return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); var state = this._readableState; if (ev === 'data') { // update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused if (state.flowing !== false) this.resume(); } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; debug('on readable', state.length, state.reading); if (state.length) { emitReadable(this); } else if (!state.reading) { process.nextTick(nReadingNextTick, this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; Readable.prototype.removeListener = function (ev, fn) { var res = Stream.prototype.removeListener.call(this, ev, fn); if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this); } return res; }; Readable.prototype.removeAllListeners = function (ev) { var res = Stream.prototype.removeAllListeners.apply(this, arguments); if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this); } return res; }; function updateReadableListening(self) { var state = self._readableState; state.readableListening = self.listenerCount('readable') > 0; if (state.resumeScheduled && !state.paused) { // flowing needs to be set to true now, otherwise // the upcoming resume will not flow. state.flowing = true; // crude way to check if we should resume } else if (self.listenerCount('data') > 0) { self.resume(); } } function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() state.flowing = !state.readableListening; resume(this, state); } state.paused = false; return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; process.nextTick(resume_, stream, state); } } function resume_(stream, state) { debug('resume', state.reading); if (!state.reading) { stream.read(0); } state.resumeScheduled = false; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } this._readableState.paused = true; return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) { ; } } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function methodWrap(method) { return function methodWrapReturnFunction() { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; if (typeof Symbol === 'function') { Readable.prototype[Symbol.asyncIterator] = function () { if (createReadableStreamAsyncIterator === undefined) { createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); } return createReadableStreamAsyncIterator(this); }; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/from.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/from.js
'use strict'; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; function from(Readable, iterable, opts) { var iterator; if (iterable && typeof iterable.next === 'function') { iterator = iterable; } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); var readable = new Readable(_objectSpread({ objectMode: true }, opts)); // Reading boolean to protect against _read // being called before last iteration completion. var reading = false; readable._read = function () { if (!reading) { reading = true; next(); } }; function next() { return _next2.apply(this, arguments); } function _next2() { _next2 = _asyncToGenerator(function* () { try { var _ref = yield iterator.next(), value = _ref.value, done = _ref.done; if (done) { readable.push(null); } else if (readable.push((yield value))) { next(); } else { reading = false; } } catch (err) { readable.destroy(err); } }); return _next2.apply(this, arguments); } return readable; } module.exports = from;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/pipeline.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/pipeline.js
// Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; var eos; function once(callback) { var called = false; return function () { if (called) return; called = true; callback.apply(void 0, arguments); }; } var _require$codes = require('../../../errors').codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on('close', function () { closed = true; }); if (eos === undefined) eos = require('./end-of-stream'); eos(stream, { readable: reading, writable: writing }, function (err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function (err) { if (closed) return; if (destroyed) return; destroyed = true; // request.destroy just do .end - .abort is what we want if (isRequest(stream)) return stream.abort(); if (typeof stream.destroy === 'function') return stream.destroy(); callback(err || new ERR_STREAM_DESTROYED('pipe')); }; } function call(fn) { fn(); } function pipe(from, to) { return from.pipe(to); } function popCallback(streams) { if (!streams.length) return noop; if (typeof streams[streams.length - 1] !== 'function') return noop; return streams.pop(); } function pipeline() { for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { streams[_key] = arguments[_key]; } var callback = popCallback(streams); if (Array.isArray(streams[0])) streams = streams[0]; if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } var error; var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1; var writing = i > 0; return destroyer(stream, reading, writing, function (err) { if (!error) error = err; if (err) destroys.forEach(call); if (reading) return; destroys.forEach(call); callback(error); }); }); return streams.reduce(pipe); } module.exports = pipeline;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/from-browser.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/from-browser.js
module.exports = function () { throw new Error('Readable.from is not available in the browser') };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/state.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/state.js
'use strict'; var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } return Math.floor(hwm); } // Default value return state.objectMode ? 16 : 16 * 1024; } module.exports = { getHighWaterMark: getHighWaterMark };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/buffer_list.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/buffer_list.js
'use strict'; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require = require('buffer'), Buffer = _require.Buffer; var _require2 = require('util'), inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } module.exports = /*#__PURE__*/ function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } _createClass(BufferList, [{ key: "push", value: function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; } }, { key: "unshift", value: function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; } }, { key: "shift", value: function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; } }, { key: "clear", value: function clear() { this.head = this.tail = null; this.length = 0; } }, { key: "join", value: function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; } return ret; } }, { key: "concat", value: function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; } // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); this.head.data = this.head.data.slice(n); } else if (n === this.head.data.length) { // First chunk is a perfect match. ret = this.shift(); } else { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } return ret; } }, { key: "first", value: function first() { return this.head.data; } // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { var p = this.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = str.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { var ret = Buffer.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = buf.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { return inspect(this, _objectSpread({}, options, { // Only inspect one level. depth: 0, // It should not recurse. customInspect: false })); } }]); return BufferList; }();
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
// Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; function once(callback) { var called = false; return function () { if (called) return; called = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } callback.apply(this, args); }; } function noop() {} function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; var writableEnded = stream._writableState && stream._writableState.finished; var onfinish = function onfinish() { writable = false; writableEnded = true; if (!readable) callback.call(stream); }; var readableEnded = stream._readableState && stream._readableState.endEmitted; var onend = function onend() { readable = false; readableEnded = true; if (!writable) callback.call(stream); }; var onerror = function onerror(err) { callback.call(stream, err); }; var onclose = function onclose() { var err; if (readable && !readableEnded) { if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } if (writable && !writableEnded) { if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } }; var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest();else stream.on('request', onrequest); } else if (writable && !stream._writableState) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function () { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; } module.exports = eos;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/destroy.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/destroy.js
'use strict'; // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { process.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; process.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { process.nextTick(emitErrorAndCloseNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; process.nextTick(emitErrorAndCloseNT, _this, err); } else { process.nextTick(emitCloseNT, _this); } } else if (cb) { process.nextTick(emitCloseNT, _this); cb(err); } else { process.nextTick(emitCloseNT, _this); } }); return this; } function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. var rState = stream._readableState; var wState = stream._writableState; if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy, errorOrDestroy: errorOrDestroy };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/stream.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/stream.js
module.exports = require('stream');
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/async_iterator.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/async_iterator.js
'use strict'; var _Object$setPrototypeO; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var finished = require('./end-of-stream'); var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); function createIterResult(value, done) { return { value: value, done: done }; } function readAndResolve(iter) { var resolve = iter[kLastResolve]; if (resolve !== null) { var data = iter[kStream].read(); // we defer if data is null // we can be expecting either 'end' or // 'error' if (data !== null) { iter[kLastPromise] = null; iter[kLastResolve] = null; iter[kLastReject] = null; resolve(createIterResult(data, false)); } } } function onReadable(iter) { // we wait for the next tick, because it might // emit an error with process.nextTick process.nextTick(readAndResolve, iter); } function wrapForNext(lastPromise, iter) { return function (resolve, reject) { lastPromise.then(function () { if (iter[kEnded]) { resolve(createIterResult(undefined, true)); return; } iter[kHandlePromise](resolve, reject); }, reject); }; } var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { get stream() { return this[kStream]; }, next: function next() { var _this = this; // if we have detected an error in the meanwhile // reject straight away var error = this[kError]; if (error !== null) { return Promise.reject(error); } if (this[kEnded]) { return Promise.resolve(createIterResult(undefined, true)); } if (this[kStream].destroyed) { // We need to defer via nextTick because if .destroy(err) is // called, the error will be emitted via nextTick, and // we cannot guarantee that there is no error lingering around // waiting to be emitted. return new Promise(function (resolve, reject) { process.nextTick(function () { if (_this[kError]) { reject(_this[kError]); } else { resolve(createIterResult(undefined, true)); } }); }); } // if we have multiple next() calls // we will wait for the previous Promise to finish // this logic is optimized to support for await loops, // where next() is only called once at a time var lastPromise = this[kLastPromise]; var promise; if (lastPromise) { promise = new Promise(wrapForNext(lastPromise, this)); } else { // fast path needed to support multiple this.push() // without triggering the next() queue var data = this[kStream].read(); if (data !== null) { return Promise.resolve(createIterResult(data, false)); } promise = new Promise(this[kHandlePromise]); } this[kLastPromise] = promise; return promise; } }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { return this; }), _defineProperty(_Object$setPrototypeO, "return", function _return() { var _this2 = this; // destroy(err, cb) is a private API // we can guarantee we have that here, because we control the // Readable class this is attached to return new Promise(function (resolve, reject) { _this2[kStream].destroy(null, function (err) { if (err) { reject(err); return; } resolve(createIterResult(undefined, true)); }); }); }), _Object$setPrototypeO), AsyncIteratorPrototype); var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { var _Object$create; var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { value: stream, writable: true }), _defineProperty(_Object$create, kLastResolve, { value: null, writable: true }), _defineProperty(_Object$create, kLastReject, { value: null, writable: true }), _defineProperty(_Object$create, kError, { value: null, writable: true }), _defineProperty(_Object$create, kEnded, { value: stream._readableState.endEmitted, writable: true }), _defineProperty(_Object$create, kHandlePromise, { value: function value(resolve, reject) { var data = iterator[kStream].read(); if (data) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(data, false)); } else { iterator[kLastResolve] = resolve; iterator[kLastReject] = reject; } }, writable: true }), _Object$create)); iterator[kLastPromise] = null; finished(stream, function (err) { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise // returned by next() and store the error if (reject !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; reject(err); } iterator[kError] = err; return; } var resolve = iterator[kLastResolve]; if (resolve !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(undefined, true)); } iterator[kEnded] = true; }); stream.on('readable', onReadable.bind(null, iterator)); return iterator; }; module.exports = createReadableStreamAsyncIterator;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/stream-browser.js
aws/lti-middleware/node_modules/readable-stream/lib/internal/streams/stream-browser.js
module.exports = require('events').EventEmitter;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/cliui/build/lib/string-utils.js
aws/lti-middleware/node_modules/cliui/build/lib/string-utils.js
// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi". // to facilitate ESM and Deno modules. // TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM. // The npm application // Copyright (c) npm, Inc. and Contributors // Licensed on the terms of The Artistic License 2.0 // See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' + '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g'); export function stripAnsi(str) { return str.replace(ansi, ''); } export function wrap(str, width) { const [start, end] = str.match(ansi) || ['', '']; str = stripAnsi(str); let wrapped = ''; for (let i = 0; i < str.length; i++) { if (i !== 0 && (i % width) === 0) { wrapped += '\n'; } wrapped += str.charAt(i); } if (start && end) { wrapped = `${start}${wrapped}${end}`; } return wrapped; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/cliui/build/lib/index.js
aws/lti-middleware/node_modules/cliui/build/lib/index.js
'use strict'; const align = { right: alignRight, center: alignCenter }; const top = 0; const right = 1; const bottom = 2; const left = 3; export class UI { constructor(opts) { var _a; this.width = opts.width; this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(''); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { return this.applyLayoutDSL(args[0]); } const cols = args.map(arg => { if (typeof arg === 'string') { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === 'string' && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split('\n').map(row => row.split('\t')); let leftColumnWidth = 0; // simple heuristic for layout, make sure the // second column lines up along the left-hand. // don't allow the first column to take up more // than 50% of the screen. rows.forEach(columns => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); // generate a table: // replacing ' ' with padding calculations. // using the algorithmically generated width. rows.forEach(columns => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { // measure padding without ansi escape codes const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach(row => { this.rowToString(row, lines); }); // don't display any lines with the // hidden flag set. return lines .filter(line => !line.hidden) .map(line => line.text) .join('\n'); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ''; rrow.forEach((col, c) => { const { width } = row[c]; // the width with padding. const wrapWidth = this.negatePadding(row[c]); // the width without padding. let ts = col; // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1); } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += ' '.repeat(padding[left]); } str += addBorder(row[c], ts, '| '); str += ts; str += addBorder(row[c], ts, ' |'); if (padding[right]) { str += ' '.repeat(padding[right]); } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); const leadingWhitespace = match ? match[0].length : 0; const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimRight()); if (!previousLine.span) { return source; } // if we're not applying wrapping logic, // just always append to the span. if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } else { wrapped = col.text.split('\n'); } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push(''); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { let wrapWidth = col.width || 0; if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return undefined; }); // any unset widths should be calculated. const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } } function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ''; } if (ts.trim().length !== 0) { return style; } return ' '; } return ''; } // calculates the minimum width of // a column, based on padding preferences. function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { /* istanbul ignore next: depends on terminal */ if (typeof process === 'object' && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return ' '.repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); /* istanbul ignore next */ if (strWidth >= width) { return str; } return ' '.repeat((width - strWidth) >> 1) + str; } let mixin; export function cliui(opts, _mixin) { mixin = _mixin; return new UI({ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap }); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/stream-shift/index.js
aws/lti-middleware/node_modules/stream-shift/index.js
module.exports = shift function shift (stream) { var rs = stream._readableState if (!rs) return null return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs)) } function getStateLength (state) { if (state.buffer.length) { // Since node 6.3.0 state.buffer is a BufferList not an array if (state.buffer.head) { return state.buffer.head.data.length } return state.buffer[0].length } return state.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/stream-shift/test.js
aws/lti-middleware/node_modules/stream-shift/test.js
var tape = require('tape') var through = require('through2') var stream = require('stream') var shift = require('./') tape('shifts next', function (t) { var passthrough = through() passthrough.write('hello') passthrough.write('world') t.same(shift(passthrough), Buffer('hello')) t.same(shift(passthrough), Buffer('world')) t.end() }) tape('shifts next with core', function (t) { var passthrough = stream.PassThrough() passthrough.write('hello') passthrough.write('world') t.same(shift(passthrough), Buffer('hello')) t.same(shift(passthrough), Buffer('world')) t.end() }) tape('shifts next with object mode', function (t) { var passthrough = through({objectMode: true}) passthrough.write({hello: 1}) passthrough.write({world: 1}) t.same(shift(passthrough), {hello: 1}) t.same(shift(passthrough), {world: 1}) t.end() }) tape('shifts next with object mode with core', function (t) { var passthrough = stream.PassThrough({objectMode: true}) passthrough.write({hello: 1}) passthrough.write({world: 1}) t.same(shift(passthrough), {hello: 1}) t.same(shift(passthrough), {world: 1}) t.end() })
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1.js
const { define } = require('./asn1/api') const base = require('./asn1/base') const constants = require('./asn1/constants') const decoders = require('./asn1/decoders') const encoders = require('./asn1/encoders') module.exports = { base, constants, decoders, define, encoders }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/api.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/api.js
const { inherits } = require('util') const encoders = require('./encoders') const decoders = require('./decoders') module.exports.define = function define (name, body) { return new Entity(name, body) } function Entity (name, body) { this.name = name this.body = body this.decoders = {} this.encoders = {} } Entity.prototype._createNamed = function createNamed (Base) { const name = this.name function Generated (entity) { this._initNamed(entity, name) } inherits(Generated, Base) Generated.prototype._initNamed = function _initNamed (entity, name) { Base.call(this, entity, name) } return new Generated(this) } Entity.prototype._getDecoder = function _getDecoder (enc) { enc = enc || 'der' // Lazily create decoder if (!Object.prototype.hasOwnProperty.call(this.decoders, enc)) { this.decoders[enc] = this._createNamed(decoders[enc]) } return this.decoders[enc] } Entity.prototype.decode = function decode (data, enc, options) { return this._getDecoder(enc).decode(data, options) } Entity.prototype._getEncoder = function _getEncoder (enc) { enc = enc || 'der' // Lazily create encoder if (!Object.prototype.hasOwnProperty.call(this.encoders, enc)) { this.encoders[enc] = this._createNamed(encoders[enc]) } return this.encoders[enc] } Entity.prototype.encode = function encode (data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter) }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/buffer.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/buffer.js
const { inherits } = require('util') const { Reporter } = require('../base/reporter') function DecoderBuffer (base, options) { Reporter.call(this, options) if (!Buffer.isBuffer(base)) { this.error('Input not Buffer') return } this.base = base this.offset = 0 this.length = base.length } inherits(DecoderBuffer, Reporter) DecoderBuffer.isDecoderBuffer = function isDecoderBuffer (data) { if (data instanceof DecoderBuffer) { return true } // Or accept compatible API const isCompatible = typeof data === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function' return isCompatible } DecoderBuffer.prototype.save = function save () { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) } } DecoderBuffer.prototype.restore = function restore (save) { // Return skipped data const res = new DecoderBuffer(this.base) res.offset = save.offset res.length = this.offset this.offset = save.offset Reporter.prototype.restore.call(this, save.reporter) return res } DecoderBuffer.prototype.isEmpty = function isEmpty () { return this.offset === this.length } DecoderBuffer.prototype.readUInt8 = function readUInt8 (fail) { if (this.offset + 1 <= this.length) { return this.base.readUInt8(this.offset++, true) } else { return this.error(fail || 'DecoderBuffer overrun') } } DecoderBuffer.prototype.skip = function skip (bytes, fail) { if (!(this.offset + bytes <= this.length)) { return this.error(fail || 'DecoderBuffer overrun') } const res = new DecoderBuffer(this.base) // Share reporter state res._reporterState = this._reporterState res.offset = this.offset res.length = this.offset + bytes this.offset += bytes return res } DecoderBuffer.prototype.raw = function raw (save) { return this.base.slice(save ? save.offset : this.offset, this.length) } function EncoderBuffer (value, reporter) { if (Array.isArray(value)) { this.length = 0 this.value = value.map(function (item) { if (!EncoderBuffer.isEncoderBuffer(item)) { item = new EncoderBuffer(item, reporter) } this.length += item.length return item }, this) } else if (typeof value === 'number') { if (!(value >= 0 && value <= 0xff)) { return reporter.error('non-byte EncoderBuffer value') } this.value = value this.length = 1 } else if (typeof value === 'string') { this.value = value this.length = Buffer.byteLength(value) } else if (Buffer.isBuffer(value)) { this.value = value this.length = value.length } else { return reporter.error(`Unsupported type: ${typeof value}`) } } EncoderBuffer.isEncoderBuffer = function isEncoderBuffer (data) { if (data instanceof EncoderBuffer) { return true } // Or accept compatible API const isCompatible = typeof data === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function' return isCompatible } EncoderBuffer.prototype.join = function join (out, offset) { if (!out) { out = Buffer.alloc(this.length) } if (!offset) { offset = 0 } if (this.length === 0) { return out } if (Array.isArray(this.value)) { this.value.forEach(function (item) { item.join(out, offset) offset += item.length }) } else { if (typeof this.value === 'number') { out[offset] = this.value } else if (typeof this.value === 'string') { out.write(this.value, offset) } else if (Buffer.isBuffer(this.value)) { this.value.copy(out, offset) } offset += this.length } return out } module.exports = { DecoderBuffer, EncoderBuffer }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/index.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/index.js
const { Reporter } = require('./reporter') const { DecoderBuffer, EncoderBuffer } = require('./buffer') const Node = require('./node') module.exports = { DecoderBuffer, EncoderBuffer, Node, Reporter }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/reporter.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/reporter.js
const { inherits } = require('util') function Reporter (options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] } } Reporter.prototype.isError = function isError (obj) { return obj instanceof ReporterError } Reporter.prototype.save = function save () { const state = this._reporterState return { obj: state.obj, pathLen: state.path.length } } Reporter.prototype.restore = function restore (data) { const state = this._reporterState state.obj = data.obj state.path = state.path.slice(0, data.pathLen) } Reporter.prototype.enterKey = function enterKey (key) { return this._reporterState.path.push(key) } Reporter.prototype.exitKey = function exitKey (index) { const state = this._reporterState state.path = state.path.slice(0, index - 1) } Reporter.prototype.leaveKey = function leaveKey (index, key, value) { const state = this._reporterState this.exitKey(index) if (state.obj !== null) { state.obj[key] = value } } Reporter.prototype.path = function path () { return this._reporterState.path.join('/') } Reporter.prototype.enterObject = function enterObject () { const state = this._reporterState const prev = state.obj state.obj = {} return prev } Reporter.prototype.leaveObject = function leaveObject (prev) { const state = this._reporterState const now = state.obj state.obj = prev return now } Reporter.prototype.error = function error (msg) { let err const state = this._reporterState const inherited = msg instanceof ReporterError if (inherited) { err = msg } else { err = new ReporterError(state.path.map(function (elem) { return `[${JSON.stringify(elem)}]` }).join(''), msg.message || msg, msg.stack) } if (!state.options.partial) { throw err } if (!inherited) { state.errors.push(err) } return err } Reporter.prototype.wrapResult = function wrapResult (result) { const state = this._reporterState if (!state.options.partial) { return result } return { result: this.isError(result) ? null : result, errors: state.errors } } function ReporterError (path, msg) { this.path = path this.rethrow(msg) } inherits(ReporterError, Error) ReporterError.prototype.rethrow = function rethrow (msg) { this.message = `${msg} at: ${this.path || '(shallow)'}` if (Error.captureStackTrace) { Error.captureStackTrace(this, ReporterError) } if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message) } catch (e) { this.stack = e.stack } } return this } exports.Reporter = Reporter
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/node.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/base/node.js
const { strict: assert } = require('assert') const { Reporter } = require('../base/reporter') const { DecoderBuffer, EncoderBuffer } = require('../base/buffer') // Supported tags const tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ] // Public methods list const methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags) // Overrided methods list const overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ] function Node (enc, parent, name) { const state = {} this._baseState = state state.name = name state.enc = enc state.parent = parent || null state.children = null // State state.tag = null state.args = null state.reverseArgs = null state.choice = null state.optional = false state.any = false state.obj = false state.use = null state.useDecoder = null state.key = null state.default = null state.explicit = null state.implicit = null state.contains = null // Should create new instance on each method if (!state.parent) { state.children = [] this._wrap() } } const stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ] Node.prototype.clone = function clone () { const state = this._baseState const cstate = {} stateProps.forEach(function (prop) { cstate[prop] = state[prop] }) const res = new this.constructor(cstate.parent) res._baseState = cstate return res } Node.prototype._wrap = function wrap () { const state = this._baseState methods.forEach(function (method) { this[method] = function _wrappedMethod () { const clone = new this.constructor(this) state.children.push(clone) return clone[method].apply(clone, arguments) } }, this) } Node.prototype._init = function init (body) { const state = this._baseState assert(state.parent === null) body.call(this) // Filter children state.children = state.children.filter(function (child) { return child._baseState.parent === this }, this) assert.equal(state.children.length, 1, 'Root node can have only one child') } Node.prototype._useArgs = function useArgs (args) { const state = this._baseState // Filter children and args const children = args.filter(function (arg) { return arg instanceof this.constructor }, this) args = args.filter(function (arg) { return !(arg instanceof this.constructor) }, this) if (children.length !== 0) { assert(state.children === null) state.children = children // Replace parent to maintain backward link children.forEach(function (child) { child._baseState.parent = this }, this) } if (args.length !== 0) { assert(state.args === null) state.args = args state.reverseArgs = args.map(function (arg) { if (typeof arg !== 'object' || arg.constructor !== Object) { return arg } const res = {} Object.keys(arg).forEach(function (key) { if (key == (key | 0)) { key |= 0 } // eslint-disable-line eqeqeq const value = arg[key] res[value] = key }) return res }) } } // // Overrided methods // overrided.forEach(function (method) { Node.prototype[method] = function _overrided () { const state = this._baseState throw new Error(`${method} not implemented for encoding: ${state.enc}`) } }) // // Public methods // tags.forEach(function (tag) { Node.prototype[tag] = function _tagMethod () { const state = this._baseState const args = Array.prototype.slice.call(arguments) assert(state.tag === null) state.tag = tag this._useArgs(args) return this } }) Node.prototype.use = function use (item) { assert(item) const state = this._baseState assert(state.use === null) state.use = item return this } Node.prototype.optional = function optional () { const state = this._baseState state.optional = true return this } Node.prototype.def = function def (val) { const state = this._baseState assert(state.default === null) state.default = val state.optional = true return this } Node.prototype.explicit = function explicit (num) { const state = this._baseState assert(state.explicit === null && state.implicit === null) state.explicit = num return this } Node.prototype.implicit = function implicit (num) { const state = this._baseState assert(state.explicit === null && state.implicit === null) state.implicit = num return this } Node.prototype.obj = function obj () { const state = this._baseState const args = Array.prototype.slice.call(arguments) state.obj = true if (args.length !== 0) { this._useArgs(args) } return this } Node.prototype.key = function key (newKey) { const state = this._baseState assert(state.key === null) state.key = newKey return this } Node.prototype.any = function any () { const state = this._baseState state.any = true return this } Node.prototype.choice = function choice (obj) { const state = this._baseState assert(state.choice === null) state.choice = obj this._useArgs(Object.keys(obj).map(function (key) { return obj[key] })) return this } Node.prototype.contains = function contains (item) { const state = this._baseState assert(state.use === null) state.contains = item return this } // // Decoding // Node.prototype._decode = function decode (input, options) { const state = this._baseState // Decode root node if (state.parent === null) { return input.wrapResult(state.children[0]._decode(input, options)) } let result = state.default let present = true let prevKey = null if (state.key !== null) { prevKey = input.enterKey(state.key) } // Check if tag is there if (state.optional) { let tag = null if (state.explicit !== null) { tag = state.explicit } else if (state.implicit !== null) { tag = state.implicit } else if (state.tag !== null) { tag = state.tag } if (tag === null && !state.any) { // Trial and Error const save = input.save() try { if (state.choice === null) { this._decodeGeneric(state.tag, input, options) } else { this._decodeChoice(input, options) } present = true } catch (e) { present = false } input.restore(save) } else { present = this._peekTag(input, tag, state.any) if (input.isError(present)) { return present } } } // Push object on stack let prevObj if (state.obj && present) { prevObj = input.enterObject() } if (present) { // Unwrap explicit values if (state.explicit !== null) { const explicit = this._decodeTag(input, state.explicit) if (input.isError(explicit)) { return explicit } input = explicit } const start = input.offset // Unwrap implicit and normal values if (state.use === null && state.choice === null) { let save if (state.any) { save = input.save() } const body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ) if (input.isError(body)) { return body } if (state.any) { result = input.raw(save) } else { input = body } } if (options && options.track && state.tag !== null) { options.track(input.path(), start, input.length, 'tagged') } if (options && options.track && state.tag !== null) { options.track(input.path(), input.offset, input.length, 'content') } // Select proper method for tag if (state.any) { // no-op } else if (state.choice === null) { result = this._decodeGeneric(state.tag, input, options) } else { result = this._decodeChoice(input, options) } if (input.isError(result)) { return result } // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren (child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options) }) } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { const data = new DecoderBuffer(result) result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options) } } // Pop object if (state.obj && present) { result = input.leaveObject(prevObj) } // Set key if (state.key !== null && (result !== null || present === true)) { input.leaveKey(prevKey, state.key, result) } else if (prevKey !== null) { input.exitKey(prevKey) } return result } Node.prototype._decodeGeneric = function decodeGeneric (tag, input, options) { const state = this._baseState if (tag === 'seq' || tag === 'set') { return null } if (tag === 'seqof' || tag === 'setof') { return this._decodeList(input, tag, state.args[0], options) } else if (/str$/.test(tag)) { return this._decodeStr(input, tag, options) } else if (tag === 'objid' && state.args) { return this._decodeObjid(input, state.args[0], state.args[1], options) } else if (tag === 'objid') { return this._decodeObjid(input, null, null, options) } else if (tag === 'gentime' || tag === 'utctime') { return this._decodeTime(input, tag, options) } else if (tag === 'null_') { return this._decodeNull(input, options) } else if (tag === 'bool') { return this._decodeBool(input, options) } else if (tag === 'objDesc') { return this._decodeStr(input, tag, options) } else if (tag === 'int' || tag === 'enum') { return this._decodeInt(input, state.args && state.args[0], options) } if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options) } else { return input.error(`unknown tag: ${tag}`) } } Node.prototype._getUse = function _getUse (entity, obj) { const state = this._baseState // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj) assert(state.useDecoder._baseState.parent === null) state.useDecoder = state.useDecoder._baseState.children[0] if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone() state.useDecoder._baseState.implicit = state.implicit } return state.useDecoder } Node.prototype._decodeChoice = function decodeChoice (input, options) { const state = this._baseState let result = null let match = false Object.keys(state.choice).some(function (key) { const save = input.save() const node = state.choice[key] try { const value = node._decode(input, options) if (input.isError(value)) { return false } result = { type: key, value: value } match = true } catch (e) { input.restore(save) return false } return true }, this) if (!match) { return input.error('Choice not matched') } return result } // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer (data) { return new EncoderBuffer(data, this.reporter) } Node.prototype._encode = function encode (data, reporter, parent) { const state = this._baseState if (state.default !== null && state.default === data) { return } const result = this._encodeValue(data, reporter, parent) if (result === undefined) { return } if (this._skipDefault(result, reporter, parent)) { return } return result } Node.prototype._encodeValue = function encode (data, reporter, parent) { const state = this._baseState // Decode root node if (state.parent === null) { return state.children[0]._encode(data, reporter || new Reporter()) } let result = null // Set reporter to share it with a child class this.reporter = reporter // Check if data is there if (state.optional && data === undefined) { if (state.default !== null) { data = state.default } else { return } } // Encode children first let content = null let primitive = false if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data) } else if (state.choice) { result = this._encodeChoice(data, reporter) } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter) primitive = true } else if (state.children) { content = state.children.map(function (child) { if (child._baseState.tag === 'null_') { return child._encode(null, reporter, data) } if (child._baseState.key === null) { return reporter.error('Child should have a key') } const prevKey = reporter.enterKey(child._baseState.key) if (typeof data !== 'object') { return reporter.error('Child expected, but input is not object') } const res = child._encode(data[child._baseState.key], reporter, data) reporter.leaveKey(prevKey) return res }, this).filter(function (child) { return child }) content = this._createEncoderBuffer(content) } else { if (state.tag === 'seqof' || state.tag === 'setof') { if (!(state.args && state.args.length === 1)) { return reporter.error(`Too many args for: ${state.tag}`) } if (!Array.isArray(data)) { return reporter.error('seqof/setof, but data is not Array') } const child = this.clone() child._baseState.implicit = null content = this._createEncoderBuffer(data.map(function (item) { const state = this._baseState return this._getUse(state.args[0], data)._encode(item, reporter) }, child)) } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter) } else { content = this._encodePrimitive(state.tag, data) primitive = true } } // Encode data itself if (!state.any && state.choice === null) { const tag = state.implicit !== null ? state.implicit : state.tag const cls = state.implicit === null ? 'universal' : 'context' if (tag === null) { if (state.use === null) { reporter.error('Tag could be omitted only for .use()') } } else { if (state.use === null) { result = this._encodeComposite(tag, primitive, cls, content) } } } // Wrap in explicit if (state.explicit !== null) { result = this._encodeComposite(state.explicit, false, 'context', result) } return result } Node.prototype._encodeChoice = function encodeChoice (data, reporter) { const state = this._baseState const node = state.choice[data.type] if (!node) { assert( false, `${data.type} not found in ${JSON.stringify(Object.keys(state.choice))}` ) } return node._encode(data.value, reporter) } Node.prototype._encodePrimitive = function encodePrimitive (tag, data) { const state = this._baseState if (/str$/.test(tag)) { return this._encodeStr(data, tag) } else if (tag === 'objid' && state.args) { return this._encodeObjid(data, state.reverseArgs[0], state.args[1]) } else if (tag === 'objid') { return this._encodeObjid(data, null, null) } else if (tag === 'gentime' || tag === 'utctime') { return this._encodeTime(data, tag) } else if (tag === 'null_') { return this._encodeNull() } else if (tag === 'int' || tag === 'enum') { return this._encodeInt(data, state.args && state.reverseArgs[0]) } else if (tag === 'bool') { return this._encodeBool(data) } else if (tag === 'objDesc') { return this._encodeStr(data, tag) } else { throw new Error(`Unsupported tag: ${tag}`) } } Node.prototype._isNumstr = function isNumstr (str) { return /^[0-9 ]*$/.test(str) } Node.prototype._isPrintstr = function isPrintstr (str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str) } module.exports = Node
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/encoders/index.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/encoders/index.js
module.exports = { der: require('./der'), pem: require('./pem') }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/encoders/der.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/encoders/der.js
/* global BigInt */ const { inherits } = require('util') const Node = require('../base/node') const der = require('../constants/der') function DEREncoder (entity) { this.enc = 'der' this.name = entity.name this.entity = entity // Construct base tree this.tree = new DERNode() this.tree._init(entity.body) } DEREncoder.prototype.encode = function encode (data, reporter) { return this.tree._encode(data, reporter).join() } // Tree methods function DERNode (parent) { Node.call(this, 'der', parent) } inherits(DERNode, Node) DERNode.prototype._encodeComposite = function encodeComposite (tag, primitive, cls, content) { const encodedTag = encodeTag(tag, primitive, cls, this.reporter) // Short form if (content.length < 0x80) { const header = Buffer.alloc(2) header[0] = encodedTag header[1] = content.length return this._createEncoderBuffer([header, content]) } // Long form // Count octets required to store length let lenOctets = 1 for (let i = content.length; i >= 0x100; i >>= 8) { lenOctets++ } const header = Buffer.alloc(1 + 1 + lenOctets) header[0] = encodedTag header[1] = 0x80 | lenOctets for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) { header[i] = j & 0xff } return this._createEncoderBuffer([header, content]) } DERNode.prototype._encodeStr = function encodeStr (str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([str.unused | 0, str.data]) } else if (tag === 'bmpstr') { const buf = Buffer.alloc(str.length * 2) for (let i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2) } return this._createEncoderBuffer(buf) } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports only digits and space') } return this._createEncoderBuffer(str) } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark') } return this._createEncoderBuffer(str) } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str) } else if (tag === 'objDesc') { return this._createEncoderBuffer(str) } else { return this.reporter.error(`Encoding of string type: ${tag} unsupported`) } } DERNode.prototype._encodeObjid = function encodeObjid (id, values, relative) { if (typeof id === 'string') { if (!values) { return this.reporter.error('string objid given, but no values map found') } if (!Object.prototype.hasOwnProperty.call(values, id)) { return this.reporter.error('objid not found in values map') } id = values[id].split(/[\s.]+/g) for (let i = 0; i < id.length; i++) { id[i] |= 0 } } else if (Array.isArray(id)) { id = id.slice() for (let i = 0; i < id.length; i++) { id[i] |= 0 } } if (!Array.isArray(id)) { return this.reporter.error(`objid() should be either array or string, got: ${JSON.stringify(id)}`) } if (!relative) { if (id[1] >= 40) { return this.reporter.error('Second objid identifier OOB') } id.splice(0, 2, id[0] * 40 + id[1]) } // Count number of octets let size = 0 for (let i = 0; i < id.length; i++) { let ident = id[i] for (size++; ident >= 0x80; ident >>= 7) { size++ } } const objid = Buffer.alloc(size) let offset = objid.length - 1 for (let i = id.length - 1; i >= 0; i--) { let ident = id[i] objid[offset--] = ident & 0x7f while ((ident >>= 7) > 0) { objid[offset--] = 0x80 | (ident & 0x7f) } } return this._createEncoderBuffer(objid) } function two (num) { if (num < 10) { return `0${num}` } else { return num } } DERNode.prototype._encodeTime = function encodeTime (time, tag) { let str const date = new Date(time) if (tag === 'gentime') { str = [ two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join('') } else if (tag === 'utctime') { str = [ two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join('') } else { this.reporter.error(`Encoding ${tag} time is not supported yet`) } return this._encodeStr(str, 'octstr') } DERNode.prototype._encodeNull = function encodeNull () { return this._createEncoderBuffer('') } function bnToBuf (bn) { var hex = BigInt(bn).toString(16) if (hex.length % 2) { hex = '0' + hex } var len = hex.length / 2 var u8 = new Uint8Array(len) var i = 0 var j = 0 while (i < len) { u8[i] = parseInt(hex.slice(j, j + 2), 16) i += 1 j += 2 } return u8 } DERNode.prototype._encodeInt = function encodeInt (num, values) { if (typeof num === 'string') { if (!values) { return this.reporter.error('String int or enum given, but no values map') } if (!Object.prototype.hasOwnProperty.call(values, num)) { return this.reporter.error(`Values map doesn't contain: ${JSON.stringify(num)}`) } num = values[num] } if (typeof num === 'bigint') { const numArray = [...bnToBuf(num)] if (numArray[0] & 0x80) { numArray.unshift(0) } num = Buffer.from(numArray) } if (Buffer.isBuffer(num)) { let size = num.length if (num.length === 0) { size++ } const out = Buffer.alloc(size) num.copy(out) if (num.length === 0) { out[0] = 0 } return this._createEncoderBuffer(out) } if (num < 0x80) { return this._createEncoderBuffer(num) } if (num < 0x100) { return this._createEncoderBuffer([0, num]) } let size = 1 for (let i = num; i >= 0x100; i >>= 8) { size++ } const out = new Array(size) for (let i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff num >>= 8 } if (out[0] & 0x80) { out.unshift(0) } return this._createEncoderBuffer(Buffer.from(out)) } DERNode.prototype._encodeBool = function encodeBool (value) { return this._createEncoderBuffer(value ? 0xff : 0) } DERNode.prototype._use = function use (entity, obj) { if (typeof entity === 'function') { entity = entity(obj) } return entity._getEncoder('der').tree } DERNode.prototype._skipDefault = function skipDefault (dataBuffer, reporter, parent) { const state = this._baseState let i if (state.default === null) { return false } const data = dataBuffer.join() if (state.defaultBuffer === undefined) { state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join() } if (data.length !== state.defaultBuffer.length) { return false } for (i = 0; i < data.length; i++) { if (data[i] !== state.defaultBuffer[i]) { return false } } return true } // Utility methods function encodeTag (tag, primitive, cls, reporter) { let res if (tag === 'seqof') { tag = 'seq' } else if (tag === 'setof') { tag = 'set' } if (Object.prototype.hasOwnProperty.call(der.tagByName, tag)) { res = der.tagByName[tag] } else if (typeof tag === 'number' && (tag | 0) === tag) { res = tag } else { return reporter.error(`Unknown tag: ${tag}`) } if (res >= 0x1f) { return reporter.error('Multi-octet tag encoding unsupported') } if (!primitive) { res |= 0x20 } res |= (der.tagClassByName[cls || 'universal'] << 6) return res } module.exports = DEREncoder
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/encoders/pem.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/encoders/pem.js
const { inherits } = require('util') const DEREncoder = require('./der') function PEMEncoder (entity) { DEREncoder.call(this, entity) this.enc = 'pem' } inherits(PEMEncoder, DEREncoder) PEMEncoder.prototype.encode = function encode (data, options) { const buf = DEREncoder.prototype.encode.call(this, data) const p = buf.toString('base64') const out = [`-----BEGIN ${options.label}-----`] for (let i = 0; i < p.length; i += 64) { out.push(p.slice(i, i + 64)) } out.push(`-----END ${options.label}-----`) return out.join('\n') } module.exports = PEMEncoder
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/decoders/index.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/decoders/index.js
module.exports = { der: require('./der'), pem: require('./pem') }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/decoders/der.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/decoders/der.js
/* global BigInt */ const { inherits } = require('util') const { DecoderBuffer } = require('../base/buffer') const Node = require('../base/node') // Import DER constants const der = require('../constants/der') function DERDecoder (entity) { this.enc = 'der' this.name = entity.name this.entity = entity // Construct base tree this.tree = new DERNode() this.tree._init(entity.body) } DERDecoder.prototype.decode = function decode (data, options) { if (!DecoderBuffer.isDecoderBuffer(data)) { data = new DecoderBuffer(data, options) } return this.tree._decode(data, options) } // Tree methods function DERNode (parent) { Node.call(this, 'der', parent) } inherits(DERNode, Node) DERNode.prototype._peekTag = function peekTag (buffer, tag, any) { if (buffer.isEmpty()) { return false } const state = buffer.save() const decodedTag = derDecodeTag(buffer, `Failed to peek tag: "${tag}"`) if (buffer.isError(decodedTag)) { return decodedTag } buffer.restore(state) return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any } DERNode.prototype._decodeTag = function decodeTag (buffer, tag, any) { const decodedTag = derDecodeTag(buffer, `Failed to decode tag of "${tag}"`) if (buffer.isError(decodedTag)) { return decodedTag } let len = derDecodeLen(buffer, decodedTag.primitive, `Failed to get length of "${tag}"`) // Failure if (buffer.isError(len)) { return len } if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error(`Failed to match tag: "${tag}"`) } if (decodedTag.primitive || len !== null) { return buffer.skip(len, `Failed to match body of: "${tag}"`) } // Indefinite length... find END tag const state = buffer.save() const res = this._skipUntilEnd( buffer, `Failed to skip indefinite length body: "${this.tag}"`) if (buffer.isError(res)) { return res } len = buffer.offset - state.offset buffer.restore(state) return buffer.skip(len, `Failed to match body of: "${tag}"`) } DERNode.prototype._skipUntilEnd = function skipUntilEnd (buffer, fail) { for (;;) { const tag = derDecodeTag(buffer, fail) if (buffer.isError(tag)) { return tag } const len = derDecodeLen(buffer, tag.primitive, fail) if (buffer.isError(len)) { return len } let res if (tag.primitive || len !== null) { res = buffer.skip(len) } else { res = this._skipUntilEnd(buffer, fail) } // Failure if (buffer.isError(res)) { return res } if (tag.tagStr === 'end') { break } } } DERNode.prototype._decodeList = function decodeList (buffer, tag, decoder, options) { const result = [] while (!buffer.isEmpty()) { const possibleEnd = this._peekTag(buffer, 'end') if (buffer.isError(possibleEnd)) { return possibleEnd } const res = decoder.decode(buffer, 'der', options) if (buffer.isError(res) && possibleEnd) { break } result.push(res) } return result } DERNode.prototype._decodeStr = function decodeStr (buffer, tag) { if (tag === 'bitstr') { const unused = buffer.readUInt8() if (buffer.isError(unused)) { return unused } return { unused: unused, data: buffer.raw() } } else if (tag === 'bmpstr') { const raw = buffer.raw() if (raw.length % 2 === 1) { return buffer.error('Decoding of string type: bmpstr length mismatch') } let str = '' for (let i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)) } return str } else if (tag === 'numstr') { const numstr = buffer.raw().toString('ascii') if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: numstr unsupported characters') } return numstr } else if (tag === 'octstr') { return buffer.raw() } else if (tag === 'objDesc') { return buffer.raw() } else if (tag === 'printstr') { const printstr = buffer.raw().toString('ascii') if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: printstr unsupported characters') } return printstr } else if (/str$/.test(tag)) { return buffer.raw().toString() } else { return buffer.error(`Decoding of string type: ${tag} unsupported`) } } DERNode.prototype._decodeObjid = function decodeObjid (buffer, values, relative) { let result const identifiers = [] let ident = 0 let subident = 0 while (!buffer.isEmpty()) { subident = buffer.readUInt8() ident <<= 7 ident |= subident & 0x7f if ((subident & 0x80) === 0) { identifiers.push(ident) ident = 0 } } if (subident & 0x80) { identifiers.push(ident) } const first = (identifiers[0] / 40) | 0 const second = identifiers[0] % 40 if (relative) { result = identifiers } else { result = [first, second].concat(identifiers.slice(1)) } if (values) { let tmp = values[result.join(' ')] if (tmp === undefined) { tmp = values[result.join('.')] } if (tmp !== undefined) { result = tmp } } return result } DERNode.prototype._decodeTime = function decodeTime (buffer, tag) { const str = buffer.raw().toString() let year let mon let day let hour let min let sec if (tag === 'gentime') { year = str.slice(0, 4) | 0 mon = str.slice(4, 6) | 0 day = str.slice(6, 8) | 0 hour = str.slice(8, 10) | 0 min = str.slice(10, 12) | 0 sec = str.slice(12, 14) | 0 } else if (tag === 'utctime') { year = str.slice(0, 2) | 0 mon = str.slice(2, 4) | 0 day = str.slice(4, 6) | 0 hour = str.slice(6, 8) | 0 min = str.slice(8, 10) | 0 sec = str.slice(10, 12) | 0 if (year < 70) { year = 2000 + year } else { year = 1900 + year } } else { return buffer.error(`Decoding ${tag} time is not supported yet`) } return Date.UTC(year, mon - 1, day, hour, min, sec, 0) } DERNode.prototype._decodeNull = function decodeNull () { return null } DERNode.prototype._decodeBool = function decodeBool (buffer) { const res = buffer.readUInt8() if (buffer.isError(res)) { return res } else { return res !== 0 } } DERNode.prototype._decodeInt = function decodeInt (buffer, values) { // Bigint, return as it is (assume big endian) const raw = buffer.raw() let res = BigInt(`0x${raw.toString('hex')}`) if (values) { res = values[res.toString(10)] || res } return res } DERNode.prototype._use = function use (entity, obj) { if (typeof entity === 'function') { entity = entity(obj) } return entity._getDecoder('der').tree } // Utility methods function derDecodeTag (buf, fail) { let tag = buf.readUInt8(fail) if (buf.isError(tag)) { return tag } const cls = der.tagClass[tag >> 6] const primitive = (tag & 0x20) === 0 // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { let oct = tag tag = 0 while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail) if (buf.isError(oct)) { return oct } tag <<= 7 tag |= oct & 0x7f } } else { tag &= 0x1f } const tagStr = der.tag[tag] return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr } } function derDecodeLen (buf, primitive, fail) { let len = buf.readUInt8(fail) if (buf.isError(len)) { return len } // Indefinite form if (!primitive && len === 0x80) { return null } // Definite form if ((len & 0x80) === 0) { // Short form return len } // Long form const num = len & 0x7f if (num > 4) { return buf.error('length octect is too long') } len = 0 for (let i = 0; i < num; i++) { len <<= 8 const j = buf.readUInt8(fail) if (buf.isError(j)) { return j } len |= j } return len } module.exports = DERDecoder
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/decoders/pem.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/decoders/pem.js
const { inherits } = require('util') const DERDecoder = require('./der') function PEMDecoder (entity) { DERDecoder.call(this, entity) this.enc = 'pem' } inherits(PEMDecoder, DERDecoder) PEMDecoder.prototype.decode = function decode (data, options) { const lines = data.toString().split(/[\r\n]+/g) const label = options.label.toUpperCase() const re = /^-----(BEGIN|END) ([^-]+)-----$/ let start = -1 let end = -1 for (let i = 0; i < lines.length; i++) { const match = lines[i].match(re) if (match === null) { continue } if (match[2] !== label) { continue } if (start === -1) { if (match[1] !== 'BEGIN') { break } start = i } else { if (match[1] !== 'END') { break } end = i break } } if (start === -1 || end === -1) { throw new Error(`PEM section not found for: ${label}`) } const base64 = lines.slice(start + 1, end).join('') // Remove excessive symbols base64.replace(/[^a-z0-9+/=]+/gi, '') const input = Buffer.from(base64, 'base64') return DERDecoder.prototype.decode.call(this, input, options) } module.exports = PEMDecoder
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/constants/index.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/constants/index.js
module.exports = { der: require('./der') }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/constants/der.js
aws/lti-middleware/node_modules/@panva/asn1.js/lib/asn1/constants/der.js
// Helper function reverse (map) { const res = {} Object.keys(map).forEach(function (key) { // Convert key to integer if it is stringified if ((key | 0) == key) { key = key | 0 } // eslint-disable-line eqeqeq const value = map[key] res[value] = key }) return res } exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' } exports.tagClassByName = reverse(exports.tagClass) exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' } exports.tagByName = reverse(exports.tag)
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/utils-merge/index.js
aws/lti-middleware/node_modules/utils-merge/index.js
/** * Merge object b with object a. * * var a = { foo: 'bar' } * , b = { bar: 'baz' }; * * merge(a, b); * // => { foo: 'bar', bar: 'baz' } * * @param {Object} a * @param {Object} b * @return {Object} * @api public */ exports = module.exports = function(a, b){ if (a && b) { for (var key in b) { a[key] = b[key]; } } return a; };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/lodash.isboolean/index.js
aws/lti-middleware/node_modules/lodash.isboolean/index.js
/** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var boolTag = '[object Boolean]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && objectToString.call(value) == boolTag); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isBoolean;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/lodash.memoize/index.js
aws/lti-middleware/node_modules/lodash.memoize/index.js
/** * lodash (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors <https://jquery.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var splice = arrayProto.splice; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), nativeCreate = getNative(Object, 'create'); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = memoize;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-gyp-build/index.js
aws/lti-middleware/node_modules/node-gyp-build/index.js
var fs = require('fs') var path = require('path') var os = require('os') // Workaround to fix webpack's build warnings: 'the request of a dependency is an expression' var runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line var vars = (process.config && process.config.variables) || {} var prebuildsOnly = !!process.env.PREBUILDS_ONLY var abi = process.versions.modules // TODO: support old node where this is undef var runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node') var arch = os.arch() var platform = os.platform() var libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc') var armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || '' var uv = (process.versions.uv || '').split('.')[0] module.exports = load function load (dir) { return runtimeRequire(load.path(dir)) } load.path = function (dir) { dir = path.resolve(dir || '.') try { var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_') if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD'] } catch (err) {} if (!prebuildsOnly) { var release = getFirst(path.join(dir, 'build/Release'), matchBuild) if (release) return release var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild) if (debug) return debug } var prebuild = resolve(dir) if (prebuild) return prebuild var nearby = resolve(path.dirname(process.execPath)) if (nearby) return nearby var target = [ 'platform=' + platform, 'arch=' + arch, 'runtime=' + runtime, 'abi=' + abi, 'uv=' + uv, armv ? 'armv=' + armv : '', 'libc=' + libc, 'node=' + process.versions.node, process.versions.electron ? 'electron=' + process.versions.electron : '', typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line ].filter(Boolean).join(' ') throw new Error('No native build was found for ' + target + '\n loaded from: ' + dir + '\n') function resolve (dir) { // Find matching "prebuilds/<platform>-<arch>" directory var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple) var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0] if (!tuple) return // Find most specific flavor first var prebuilds = path.join(dir, 'prebuilds', tuple.name) var parsed = readdirSync(prebuilds).map(parseTags) var candidates = parsed.filter(matchTags(runtime, abi)) var winner = candidates.sort(compareTags(runtime))[0] if (winner) return path.join(prebuilds, winner.file) } } function readdirSync (dir) { try { return fs.readdirSync(dir) } catch (err) { return [] } } function getFirst (dir, filter) { var files = readdirSync(dir).filter(filter) return files[0] && path.join(dir, files[0]) } function matchBuild (name) { return /\.node$/.test(name) } function parseTuple (name) { // Example: darwin-x64+arm64 var arr = name.split('-') if (arr.length !== 2) return var platform = arr[0] var architectures = arr[1].split('+') if (!platform) return if (!architectures.length) return if (!architectures.every(Boolean)) return return { name, platform, architectures } } function matchTuple (platform, arch) { return function (tuple) { if (tuple == null) return false if (tuple.platform !== platform) return false return tuple.architectures.includes(arch) } } function compareTuples (a, b) { // Prefer single-arch prebuilds over multi-arch return a.architectures.length - b.architectures.length } function parseTags (file) { var arr = file.split('.') var extension = arr.pop() var tags = { file: file, specificity: 0 } if (extension !== 'node') return for (var i = 0; i < arr.length; i++) { var tag = arr[i] if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') { tags.runtime = tag } else if (tag === 'napi') { tags.napi = true } else if (tag.slice(0, 3) === 'abi') { tags.abi = tag.slice(3) } else if (tag.slice(0, 2) === 'uv') { tags.uv = tag.slice(2) } else if (tag.slice(0, 4) === 'armv') { tags.armv = tag.slice(4) } else if (tag === 'glibc' || tag === 'musl') { tags.libc = tag } else { continue } tags.specificity++ } return tags } function matchTags (runtime, abi) { return function (tags) { if (tags == null) return false if (tags.runtime !== runtime && !runtimeAgnostic(tags)) return false if (tags.abi !== abi && !tags.napi) return false if (tags.uv && tags.uv !== uv) return false if (tags.armv && tags.armv !== armv) return false if (tags.libc && tags.libc !== libc) return false return true } } function runtimeAgnostic (tags) { return tags.runtime === 'node' && tags.napi } function compareTags (runtime) { // Precedence: non-agnostic runtime, abi over napi, then by specificity. return function (a, b) { if (a.runtime !== b.runtime) { return a.runtime === runtime ? -1 : 1 } else if (a.abi !== b.abi) { return a.abi ? -1 : 1 } else if (a.specificity !== b.specificity) { return a.specificity > b.specificity ? -1 : 1 } else { return 0 } } } function isNwjs () { return !!(process.versions && process.versions.nw) } function isElectron () { if (process.versions && process.versions.electron) return true if (process.env.ELECTRON_RUN_AS_NODE) return true return typeof window !== 'undefined' && window.process && window.process.type === 'renderer' } function isAlpine (platform) { return platform === 'linux' && fs.existsSync('/etc/alpine-release') } // Exposed for unit tests // TODO: move to lib load.parseTags = parseTags load.matchTags = matchTags load.compareTags = compareTags load.parseTuple = parseTuple load.matchTuple = matchTuple load.compareTuples = compareTuples
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-gyp-build/bin.js
aws/lti-middleware/node_modules/node-gyp-build/bin.js
#!/usr/bin/env node var proc = require('child_process') var os = require('os') var path = require('path') if (!buildFromSource()) { proc.exec('node-gyp-build-test', function (err, stdout, stderr) { if (err) { if (verbose()) console.error(stderr) preinstall() } }) } else { preinstall() } function build () { var args = [os.platform() === 'win32' ? 'node-gyp.cmd' : 'node-gyp', 'rebuild'] try { args = [ process.execPath, path.join(require.resolve('node-gyp/package.json'), '..', require('node-gyp/package.json').bin['node-gyp']), 'rebuild' ] } catch (_) {} proc.spawn(args[0], args.slice(1), { stdio: 'inherit' }).on('exit', function (code) { if (code || !process.argv[3]) process.exit(code) exec(process.argv[3]).on('exit', function (code) { process.exit(code) }) }) } function preinstall () { if (!process.argv[2]) return build() exec(process.argv[2]).on('exit', function (code) { if (code) process.exit(code) build() }) } function exec (cmd) { if (process.platform !== 'win32') { var shell = os.platform() === 'android' ? 'sh' : '/bin/sh' return proc.spawn(shell, ['-c', '--', cmd], { stdio: 'inherit' }) } return proc.spawn(process.env.comspec || 'cmd.exe', ['/s', '/c', '"' + cmd + '"'], { windowsVerbatimArguments: true, stdio: 'inherit' }) } function buildFromSource () { return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true' } function verbose () { return hasFlag('--verbose') || process.env.npm_config_loglevel === 'verbose' } // TODO (next major): remove in favor of env.npm_config_* which works since npm // 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90 function hasFlag (flag) { if (!process.env.npm_config_argv) return false try { return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1 } catch (_) { return false } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-gyp-build/build-test.js
aws/lti-middleware/node_modules/node-gyp-build/build-test.js
#!/usr/bin/env node process.env.NODE_ENV = 'test' var path = require('path') var test = null try { var pkg = require(path.join(process.cwd(), 'package.json')) if (pkg.name && process.env[pkg.name.toUpperCase().replace(/-/g, '_')]) { process.exit(0) } test = pkg.prebuild.test } catch (err) { // do nothing } if (test) require(path.join(process.cwd(), test)) else require('./')()
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-gyp-build/optional.js
aws/lti-middleware/node_modules/node-gyp-build/optional.js
#!/usr/bin/env node /* I am only useful as an install script to make node-gyp not compile for purely optional native deps */ process.exit(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/cookie-signature/index.js
aws/lti-middleware/node_modules/cookie-signature/index.js
/** * Module dependencies. */ var crypto = require('crypto'); /** * Sign the given `val` with `secret`. * * @param {String} val * @param {String} secret * @return {String} * @api private */ exports.sign = function(val, secret){ if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); return val + '.' + crypto .createHmac('sha256', secret) .update(val) .digest('base64') .replace(/\=+$/, ''); }; /** * Unsign and decode the given `val` with `secret`, * returning `false` if the signature is invalid. * * @param {String} val * @param {String} secret * @return {String|Boolean} * @api private */ exports.unsign = function(val, secret){ if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); var str = val.slice(0, val.lastIndexOf('.')) , mac = exports.sign(str, secret); return sha1(mac) == sha1(val) ? str : false; }; /** * Private */ function sha1(str){ return crypto.createHash('sha1').update(str).digest('hex'); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/websocket_extensions.js
aws/lti-middleware/node_modules/websocket-extensions/lib/websocket_extensions.js
'use strict'; var Parser = require('./parser'), Pipeline = require('./pipeline'); var Extensions = function() { this._rsv1 = this._rsv2 = this._rsv3 = null; this._byName = {}; this._inOrder = []; this._sessions = []; this._index = {}; }; Extensions.MESSAGE_OPCODES = [1, 2]; var instance = { add: function(ext) { if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string'); if (ext.type !== 'permessage') throw new TypeError('extension.type must be "permessage"'); if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false'); if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false'); if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false'); if (this._byName.hasOwnProperty(ext.name)) throw new TypeError('An extension with name "' + ext.name + '" is already registered'); this._byName[ext.name] = ext; this._inOrder.push(ext); }, generateOffer: function() { var sessions = [], offer = [], index = {}; this._inOrder.forEach(function(ext) { var session = ext.createClientSession(); if (!session) return; var record = [ext, session]; sessions.push(record); index[ext.name] = record; var offers = session.generateOffer(); offers = offers ? [].concat(offers) : []; offers.forEach(function(off) { offer.push(Parser.serializeParams(ext.name, off)); }, this); }, this); this._sessions = sessions; this._index = index; return offer.length > 0 ? offer.join(', ') : null; }, activate: function(header) { var responses = Parser.parseHeader(header), sessions = []; responses.eachOffer(function(name, params) { var record = this._index[name]; if (!record) throw new Error('Server sent an extension response for unknown extension "' + name + '"'); var ext = record[0], session = record[1], reserved = this._reserved(ext); if (reserved) throw new Error('Server sent two extension responses that use the RSV' + reserved[0] + ' bit: "' + reserved[1] + '" and "' + ext.name + '"'); if (session.activate(params) !== true) throw new Error('Server sent unacceptable extension parameters: ' + Parser.serializeParams(name, params)); this._reserve(ext); sessions.push(record); }, this); this._sessions = sessions; this._pipeline = new Pipeline(sessions); }, generateResponse: function(header) { var sessions = [], response = [], offers = Parser.parseHeader(header); this._inOrder.forEach(function(ext) { var offer = offers.byName(ext.name); if (offer.length === 0 || this._reserved(ext)) return; var session = ext.createServerSession(offer); if (!session) return; this._reserve(ext); sessions.push([ext, session]); response.push(Parser.serializeParams(ext.name, session.generateResponse())); }, this); this._sessions = sessions; this._pipeline = new Pipeline(sessions); return response.length > 0 ? response.join(', ') : null; }, validFrameRsv: function(frame) { var allowed = { rsv1: false, rsv2: false, rsv3: false }, ext; if (Extensions.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) { for (var i = 0, n = this._sessions.length; i < n; i++) { ext = this._sessions[i][0]; allowed.rsv1 = allowed.rsv1 || ext.rsv1; allowed.rsv2 = allowed.rsv2 || ext.rsv2; allowed.rsv3 = allowed.rsv3 || ext.rsv3; } } return (allowed.rsv1 || !frame.rsv1) && (allowed.rsv2 || !frame.rsv2) && (allowed.rsv3 || !frame.rsv3); }, processIncomingMessage: function(message, callback, context) { this._pipeline.processIncomingMessage(message, callback, context); }, processOutgoingMessage: function(message, callback, context) { this._pipeline.processOutgoingMessage(message, callback, context); }, close: function(callback, context) { if (!this._pipeline) return callback.call(context); this._pipeline.close(callback, context); }, _reserve: function(ext) { this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name); this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name); this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name); }, _reserved: function(ext) { if (this._rsv1 && ext.rsv1) return [1, this._rsv1]; if (this._rsv2 && ext.rsv2) return [2, this._rsv2]; if (this._rsv3 && ext.rsv3) return [3, this._rsv3]; return false; } }; for (var key in instance) Extensions.prototype[key] = instance[key]; module.exports = Extensions;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/parser.js
aws/lti-middleware/node_modules/websocket-extensions/lib/parser.js
'use strict'; var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/, NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g, QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/, PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'), EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'), EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'), NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/; var hasOwnProperty = Object.prototype.hasOwnProperty; var Parser = { parseHeader: function(header) { var offers = new Offers(); if (header === '' || header === undefined) return offers; if (!EXT_LIST.test(header)) throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header); var values = header.match(EXT); values.forEach(function(value) { var params = value.match(new RegExp(PARAM.source, 'g')), name = params.shift(), offer = {}; params.forEach(function(param) { var args = param.match(PARAM), key = args[1], data; if (args[2] !== undefined) { data = args[2]; } else if (args[3] !== undefined) { data = args[3].replace(/\\/g, ''); } else { data = true; } if (NUMBER.test(data)) data = parseFloat(data); if (hasOwnProperty.call(offer, key)) { offer[key] = [].concat(offer[key]); offer[key].push(data); } else { offer[key] = data; } }, this); offers.push(name, offer); }, this); return offers; }, serializeParams: function(name, params) { var values = []; var print = function(key, value) { if (value instanceof Array) { value.forEach(function(v) { print(key, v) }); } else if (value === true) { values.push(key); } else if (typeof value === 'number') { values.push(key + '=' + value); } else if (NOTOKEN.test(value)) { values.push(key + '="' + value.replace(/"/g, '\\"') + '"'); } else { values.push(key + '=' + value); } }; for (var key in params) print(key, params[key]); return [name].concat(values).join('; '); } }; var Offers = function() { this._byName = {}; this._inOrder = []; }; Offers.prototype.push = function(name, params) { if (!hasOwnProperty.call(this._byName, name)) this._byName[name] = []; this._byName[name].push(params); this._inOrder.push({ name: name, params: params }); }; Offers.prototype.eachOffer = function(callback, context) { var list = this._inOrder; for (var i = 0, n = list.length; i < n; i++) callback.call(context, list[i].name, list[i].params); }; Offers.prototype.byName = function(name) { return this._byName[name] || []; }; Offers.prototype.toArray = function() { return this._inOrder.slice(); }; module.exports = Parser;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/index.js
aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/index.js
'use strict'; var Cell = require('./cell'), Pledge = require('./pledge'); var Pipeline = function(sessions) { this._cells = sessions.map(function(session) { return new Cell(session) }); this._stopped = { incoming: false, outgoing: false }; }; Pipeline.prototype.processIncomingMessage = function(message, callback, context) { if (this._stopped.incoming) return; this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context); }; Pipeline.prototype.processOutgoingMessage = function(message, callback, context) { if (this._stopped.outgoing) return; this._loop('outgoing', 0, this._cells.length, 1, message, callback, context); }; Pipeline.prototype.close = function(callback, context) { this._stopped = { incoming: true, outgoing: true }; var closed = this._cells.map(function(a) { return a.close() }); if (callback) Pledge.all(closed).then(function() { callback.call(context) }); }; Pipeline.prototype._loop = function(direction, start, end, step, message, callback, context) { var cells = this._cells, n = cells.length, self = this; while (n--) cells[n].pending(direction); var pipe = function(index, error, msg) { if (index === end) return callback.call(context, error, msg); cells[index][direction](error, msg, function(err, m) { if (err) self._stopped[direction] = true; pipe(index + step, err, m); }); }; pipe(start, null, message); }; module.exports = Pipeline;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/cell.js
aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/cell.js
'use strict'; var Functor = require('./functor'), Pledge = require('./pledge'); var Cell = function(tuple) { this._ext = tuple[0]; this._session = tuple[1]; this._functors = { incoming: new Functor(this._session, 'processIncomingMessage'), outgoing: new Functor(this._session, 'processOutgoingMessage') }; }; Cell.prototype.pending = function(direction) { var functor = this._functors[direction]; if (!functor._stopped) functor.pending += 1; }; Cell.prototype.incoming = function(error, message, callback, context) { this._exec('incoming', error, message, callback, context); }; Cell.prototype.outgoing = function(error, message, callback, context) { this._exec('outgoing', error, message, callback, context); }; Cell.prototype.close = function() { this._closed = this._closed || new Pledge(); this._doClose(); return this._closed; }; Cell.prototype._exec = function(direction, error, message, callback, context) { this._functors[direction].call(error, message, function(err, msg) { if (err) err.message = this._ext.name + ': ' + err.message; callback.call(context, err, msg); this._doClose(); }, this); }; Cell.prototype._doClose = function() { var fin = this._functors.incoming, fout = this._functors.outgoing; if (!this._closed || fin.pending + fout.pending !== 0) return; if (this._session) this._session.close(); this._session = null; this._closed.done(); }; module.exports = Cell;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/pledge.js
aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/pledge.js
'use strict'; var RingBuffer = require('./ring_buffer'); var Pledge = function() { this._complete = false; this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE); }; Pledge.QUEUE_SIZE = 4; Pledge.all = function(list) { var pledge = new Pledge(), pending = list.length, n = pending; if (pending === 0) pledge.done(); while (n--) list[n].then(function() { pending -= 1; if (pending === 0) pledge.done(); }); return pledge; }; Pledge.prototype.then = function(callback) { if (this._complete) callback(); else this._callbacks.push(callback); }; Pledge.prototype.done = function() { this._complete = true; var callbacks = this._callbacks, callback; while (callback = callbacks.shift()) callback(); }; module.exports = Pledge;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js
aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js
'use strict'; var RingBuffer = function(bufferSize) { this._bufferSize = bufferSize; this.clear(); }; RingBuffer.prototype.clear = function() { this._buffer = new Array(this._bufferSize); this._ringOffset = 0; this._ringSize = this._bufferSize; this._head = 0; this._tail = 0; this.length = 0; }; RingBuffer.prototype.push = function(value) { var expandBuffer = false, expandRing = false; if (this._ringSize < this._bufferSize) { expandBuffer = (this._tail === 0); } else if (this._ringOffset === this._ringSize) { expandBuffer = true; expandRing = (this._tail === 0); } if (expandBuffer) { this._tail = this._bufferSize; this._buffer = this._buffer.concat(new Array(this._bufferSize)); this._bufferSize = this._buffer.length; if (expandRing) this._ringSize = this._bufferSize; } this._buffer[this._tail] = value; this.length += 1; if (this._tail < this._ringSize) this._ringOffset += 1; this._tail = (this._tail + 1) % this._bufferSize; }; RingBuffer.prototype.peek = function() { if (this.length === 0) return void 0; return this._buffer[this._head]; }; RingBuffer.prototype.shift = function() { if (this.length === 0) return void 0; var value = this._buffer[this._head]; this._buffer[this._head] = void 0; this.length -= 1; this._ringOffset -= 1; if (this._ringOffset === 0 && this.length > 0) { this._head = this._ringSize; this._ringOffset = this.length; this._ringSize = this._bufferSize; } else { this._head = (this._head + 1) % this._ringSize; } return value; }; module.exports = RingBuffer;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/functor.js
aws/lti-middleware/node_modules/websocket-extensions/lib/pipeline/functor.js
'use strict'; var RingBuffer = require('./ring_buffer'); var Functor = function(session, method) { this._session = session; this._method = method; this._queue = new RingBuffer(Functor.QUEUE_SIZE); this._stopped = false; this.pending = 0; }; Functor.QUEUE_SIZE = 8; Functor.prototype.call = function(error, message, callback, context) { if (this._stopped) return; var record = { error: error, message: message, callback: callback, context: context, done: false }, called = false, self = this; this._queue.push(record); if (record.error) { record.done = true; this._stop(); return this._flushQueue(); } var handler = function(err, msg) { if (!(called ^ (called = true))) return; if (err) { self._stop(); record.error = err; record.message = null; } else { record.message = msg; } record.done = true; self._flushQueue(); }; try { this._session[this._method](message, handler); } catch (err) { handler(err); } }; Functor.prototype._stop = function() { this.pending = this._queue.length; this._stopped = true; }; Functor.prototype._flushQueue = function() { var queue = this._queue, record; while (queue.length > 0 && queue.peek().done) { record = queue.shift(); if (record.error) { this.pending = 0; queue.clear(); } else { this.pending -= 1; } record.callback.call(record.context, record.error, record.message); } }; module.exports = Functor;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/nonce-store.js
aws/lti-middleware/node_modules/ims-lti/lib/nonce-store.js
// Generated by CoffeeScript 1.10.0 (function() { var NonceStore, exports, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; NonceStore = (function() { function NonceStore() { this.setUsed = bind(this.setUsed, this); this.isNew = bind(this.isNew, this); } NonceStore.prototype.isNonceStore = function() { return true; }; NonceStore.prototype.isNew = function() { var arg, i; for (i in arguments) { arg = arguments[i]; if (typeof arg === 'function') { return arg(new Error("NOT IMPLEMENTED"), false); } } }; NonceStore.prototype.setUsed = function() { var arg, i; for (i in arguments) { arg = arguments[i]; if (typeof arg === 'function') { return arg(new Error("NOT IMPLEMENTED"), false); } } }; return NonceStore; })(); exports = module.exports = NonceStore; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/hmac-sha1.js
aws/lti-middleware/node_modules/ims-lti/lib/hmac-sha1.js
// Generated by CoffeeScript 1.10.0 (function() { var HMAC_SHA1, _clean_request_body, crypto, exports, url, utils; crypto = require('crypto'); url = require('url'); utils = require('./utils'); _clean_request_body = function(body, query) { var cleanParams, encodeParam, out; out = []; encodeParam = function(key, val) { return key + "=" + (utils.special_encode(val)); }; cleanParams = function(params) { var i, key, len, val, vals; if (typeof params !== 'object') { return; } for (key in params) { vals = params[key]; if (key === 'oauth_signature') { continue; } if (Array.isArray(vals) === true) { for (i = 0, len = vals.length; i < len; i++) { val = vals[i]; out.push(encodeParam(key, val)); } } else { out.push(encodeParam(key, vals)); } } }; cleanParams(body); cleanParams(query); return utils.special_encode(out.sort().join('&')); }; HMAC_SHA1 = (function() { function HMAC_SHA1() {} HMAC_SHA1.prototype.toString = function() { return 'HMAC_SHA1'; }; HMAC_SHA1.prototype.build_signature_raw = function(req_url, parsed_url, method, params, consumer_secret, token) { var sig; sig = [method.toUpperCase(), utils.special_encode(req_url), _clean_request_body(params, parsed_url.query)]; return this.sign_string(sig.join('&'), consumer_secret, token); }; HMAC_SHA1.prototype.build_signature = function(req, body, consumer_secret, token) { var encrypted, hapiRawReq, hitUrl, originalUrl, parsedUrl, protocol; hapiRawReq = req.raw && req.raw.req; if (hapiRawReq) { req = hapiRawReq; } originalUrl = req.originalUrl || req.url; protocol = req.protocol; if (body.tool_consumer_info_product_family_code === 'canvas') { originalUrl = url.parse(originalUrl).pathname; } if (protocol === void 0) { encrypted = req.connection.encrypted; protocol = (encrypted && 'https') || 'http'; } parsedUrl = url.parse(originalUrl, true); hitUrl = protocol + '://' + req.headers.host + parsedUrl.pathname; return this.build_signature_raw(hitUrl, parsedUrl, req.method, body, consumer_secret, token); }; HMAC_SHA1.prototype.sign_string = function(str, key, token) { key = key + "&"; if (token) { key += token; } return crypto.createHmac('sha1', key).update(str).digest('base64'); }; return HMAC_SHA1; })(); exports = module.exports = HMAC_SHA1; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/consumer.js
aws/lti-middleware/node_modules/ims-lti/lib/consumer.js
// Generated by CoffeeScript 1.10.0 (function() { var Consumer, exports; Consumer = (function() { function Consumer() { console.error('Consumer Not Implemented'); false; } return Consumer; })(); exports = module.exports = Consumer; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/ims-lti.js
aws/lti-middleware/node_modules/ims-lti/lib/ims-lti.js
// Generated by CoffeeScript 1.10.0 (function() { var exports, extensions; extensions = require('./extensions'); exports = module.exports = { version: '0.0.0', Provider: require('./provider'), Consumer: require('./consumer'), OutcomeService: extensions.Outcomes.OutcomeService, Errors: require('./errors'), Stores: { RedisStore: require('./redis-nonce-store'), MemoryStore: require('./memory-nonce-store'), NonceStore: require('./nonce-store') }, Extensions: extensions, supported_versions: ['LTI-1p0'] }; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/memory-nonce-store.js
aws/lti-middleware/node_modules/ims-lti/lib/memory-nonce-store.js
// Generated by CoffeeScript 1.10.0 (function() { var EXPIRE_IN_SEC, MemoryNonceStore, NonceStore, exports, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NonceStore = require('./nonce-store'); EXPIRE_IN_SEC = 5 * 60; MemoryNonceStore = (function(superClass) { extend(MemoryNonceStore, superClass); function MemoryNonceStore() { this.used = Object.create(null); } MemoryNonceStore.prototype.isNew = function(nonce, timestamp, next) { var firstTimeSeen; if (next == null) { next = function() {}; } if (typeof nonce === 'undefined' || nonce === null || typeof nonce === 'function' || typeof timestamp === 'function' || typeof timestamp === 'undefined') { return next(new Error('Invalid parameters'), false); } this._clearNonces(); firstTimeSeen = this.used[nonce] === void 0; if (!firstTimeSeen) { return next(new Error('Nonce already seen'), false); } return this.setUsed(nonce, timestamp, function(err) { var currentTime, timestampIsFresh; if (typeof timestamp !== 'undefined' && timestamp !== null) { timestamp = parseInt(timestamp, 10); currentTime = Math.round(Date.now() / 1000); timestampIsFresh = (currentTime - timestamp) <= EXPIRE_IN_SEC; if (timestampIsFresh) { return next(null, true); } else { return next(new Error('Expired timestamp'), false); } } else { return next(new Error('Timestamp required'), false); } }); }; MemoryNonceStore.prototype.setUsed = function(nonce, timestamp, next) { if (next == null) { next = function() {}; } this.used[nonce] = timestamp + EXPIRE_IN_SEC; return next(null); }; MemoryNonceStore.prototype._clearNonces = function() { var expiry, nonce, now, ref; now = Math.round(Date.now() / 1000); ref = this.used; for (nonce in ref) { expiry = ref[nonce]; if (expiry <= now) { delete this.used[nonce]; } } }; return MemoryNonceStore; })(NonceStore); exports = module.exports = MemoryNonceStore; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/redis-nonce-store.js
aws/lti-middleware/node_modules/ims-lti/lib/redis-nonce-store.js
// Generated by CoffeeScript 1.10.0 (function() { var EXPIRE_IN_SEC, NonceStore, RedisNonceStore, exports, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; NonceStore = require('./nonce-store'); EXPIRE_IN_SEC = 5 * 60; RedisNonceStore = (function(superClass) { extend(RedisNonceStore, superClass); function RedisNonceStore(redisClient) { if (typeof redisClient === 'string' && arguments.length === 2) { redisClient = arguments[1]; } this.redis = redisClient; } RedisNonceStore.prototype.isNew = function(nonce, timestamp, next) { var currentTime, freshTimestamp; if (next == null) { next = function() {}; } if (typeof nonce === 'undefined' || nonce === null || typeof nonce === 'function' || typeof timestamp === 'function' || typeof timestamp === 'undefined') { return next(new Error('Invalid parameters'), false); } if (typeof timestamp === 'undefined' || timestamp === null) { return next(new Error('Timestamp required'), false); } currentTime = Math.round(Date.now() / 1000); freshTimestamp = (currentTime - parseInt(timestamp, 10)) <= EXPIRE_IN_SEC; if (!freshTimestamp) { return next(new Error('Expired timestamp'), false); } return this.redis.get(nonce, (function(_this) { return function(err, seen) { if (seen) { return next(new Error('Nonce already seen'), false); } _this.setUsed(nonce, timestamp); return next(null, true); }; })(this)); }; RedisNonceStore.prototype.setUsed = function(nonce, timestamp, next) { if (next == null) { next = function() {}; } this.redis.set(nonce, timestamp); this.redis.expire(nonce, EXPIRE_IN_SEC); return next(null); }; return RedisNonceStore; })(NonceStore); exports = module.exports = RedisNonceStore; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/provider.js
aws/lti-middleware/node_modules/ims-lti/lib/provider.js
// Generated by CoffeeScript 1.10.0 (function() { var HMAC_SHA1, MemoryNonceStore, Provider, errors, exports, extensions, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; HMAC_SHA1 = require('./hmac-sha1'); MemoryNonceStore = require('./memory-nonce-store'); errors = require('./errors'); extensions = require('./extensions'); Provider = (function() { function Provider(consumer_key, consumer_secret, nonceStore, signature_method) { if (signature_method == null) { signature_method = new HMAC_SHA1(); } this.parse_request = bind(this.parse_request, this); this.valid_request = bind(this.valid_request, this); if (typeof consumer_key === 'undefined' || consumer_key === null) { throw new errors.ConsumerError('Must specify consumer_key'); } if (typeof consumer_secret === 'undefined' || consumer_secret === null) { throw new errors.ConsumerError('Must specify consumer_secret'); } if (!nonceStore) { nonceStore = new MemoryNonceStore(); } if (!(typeof nonceStore.isNonceStore === "function" ? nonceStore.isNonceStore() : void 0)) { throw new errors.ParameterError('Fourth argument must be a nonceStore object'); } this.consumer_key = consumer_key; this.consumer_secret = consumer_secret; this.signer = signature_method; this.nonceStore = nonceStore; this.body = {}; } Provider.prototype.valid_request = function(req, body, callback) { if (!callback) { callback = body; body = void 0; } body = body || req.body || req.payload; callback = callback || function() {}; this.parse_request(req, body); if (!this._valid_parameters(body)) { return callback(new errors.ParameterError('Invalid LTI parameters'), false); } return this._valid_oauth(req, body, callback); }; Provider.prototype._valid_parameters = function(body) { var correct_message_type, correct_version, has_resource_link_id; if (!body) { return false; } correct_message_type = body.lti_message_type === 'basic-lti-launch-request'; correct_version = require('./ims-lti').supported_versions.indexOf(body.lti_version) !== -1; has_resource_link_id = body.resource_link_id != null; return correct_message_type && correct_version && has_resource_link_id; }; Provider.prototype._valid_oauth = function(req, body, callback) { var generated, valid_signature; generated = this.signer.build_signature(req, body, this.consumer_secret); valid_signature = generated === body.oauth_signature; if (!valid_signature) { return callback(new errors.SignatureError('Invalid Signature'), false); } return this.nonceStore.isNew(body.oauth_nonce, body.oauth_timestamp, function(err, valid) { if (!valid) { return callback(new errors.NonceError('Expired nonce'), false); } else { return callback(null, true); } }); }; Provider.prototype.parse_request = function(req, body) { var extension, extension_name, id, key, results, val; body = body || req.body || req.payload; for (key in body) { val = body[key]; if (key.match(/^oauth_/)) { continue; } this.body[key] = val; } if (typeof this.body.roles === 'string') { this.body.roles = this.body.roles.split(','); } this.admin = this.has_role('Administrator'); this.alumni = this.has_role('Alumni'); this.content_developer = this.has_role('ContentDeveloper'); this.guest = this.has_role('Guest'); this.instructor = this.has_role('Instructor') || this.has_role('Faculty') || this.has_role('Staff'); this.manager = this.has_role('Manager'); this.member = this.has_role('Member'); this.mentor = this.has_role('Mentor'); this.none = this.has_role('None'); this.observer = this.has_role('Observer'); this.other = this.has_role('Other'); this.prospective_student = this.has_role('ProspectiveStudent'); this.student = this.has_role('Learner') || this.has_role('Student'); this.ta = this.has_role('TeachingAssistant'); this.launch_request = this.body.lti_message_type === 'basic-lti-launch-request'; this.username = this.body.lis_person_name_given || this.body.lis_person_name_family || this.body.lis_person_name_full || ''; this.userId = this.body.user_id; if (typeof this.body.role_scope_mentor === 'string') { this.mentor_user_ids = (function() { var i, len, ref, results; ref = this.body.role_scope_mentor.split(','); results = []; for (i = 0, len = ref.length; i < len; i++) { id = ref[i]; results.push(decodeURIComponent(id)); } return results; }).call(this); } this.context_id = this.body.context_id; this.context_label = this.body.context_label; this.context_title = this.body.context_title; results = []; for (extension_name in extensions) { extension = extensions[extension_name]; results.push(extension.init(this)); } return results; }; Provider.prototype.has_role = function(role) { var regex; regex = new RegExp("^(urn:lti:(sys|inst)?role:ims/lis/)?" + role + "(/.+)?$", 'i'); return this.body.roles && this.body.roles.some(function(r) { return regex.test(r); }); }; return Provider; })(); exports = module.exports = Provider; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/errors.js
aws/lti-middleware/node_modules/ims-lti/lib/errors.js
// Generated by CoffeeScript 1.10.0 (function() { var ConsumerError, ExtensionError, NonceError, OutcomeResponseError, ParameterError, SignatureError, StoreError, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ConsumerError = (function(superClass) { extend(ConsumerError, superClass); function ConsumerError(message) { this.message = message; ConsumerError.__super__.constructor.apply(this, arguments); } return ConsumerError; })(Error); ExtensionError = (function(superClass) { extend(ExtensionError, superClass); function ExtensionError(message) { this.message = message; ExtensionError.__super__.constructor.apply(this, arguments); } return ExtensionError; })(Error); StoreError = (function(superClass) { extend(StoreError, superClass); function StoreError(message) { this.message = message; StoreError.__super__.constructor.apply(this, arguments); } return StoreError; })(Error); ParameterError = (function(superClass) { extend(ParameterError, superClass); function ParameterError(message) { this.message = message; ParameterError.__super__.constructor.apply(this, arguments); } return ParameterError; })(Error); SignatureError = (function(superClass) { extend(SignatureError, superClass); function SignatureError(message) { this.message = message; SignatureError.__super__.constructor.apply(this, arguments); } return SignatureError; })(Error); NonceError = (function(superClass) { extend(NonceError, superClass); function NonceError(message) { this.message = message; NonceError.__super__.constructor.apply(this, arguments); } return NonceError; })(Error); OutcomeResponseError = (function(superClass) { extend(OutcomeResponseError, superClass); function OutcomeResponseError(message) { this.message = message; OutcomeResponseError.__super__.constructor.apply(this, arguments); } return OutcomeResponseError; })(Error); module.exports = { ConsumerError: ConsumerError, ExtensionError: ExtensionError, StoreError: StoreError, ParameterError: ParameterError, SignatureError: SignatureError, NonceError: NonceError, OutcomeResponseError: OutcomeResponseError }; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/utils.js
aws/lti-middleware/node_modules/ims-lti/lib/utils.js
// Generated by CoffeeScript 1.10.0 (function() { exports.special_encode = function(string) { return encodeURIComponent(string).replace(/[!'()]/g, escape).replace(/\*/g, '%2A'); }; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/extensions/index.js
aws/lti-middleware/node_modules/ims-lti/lib/extensions/index.js
// Generated by CoffeeScript 1.10.0 (function() { exports.Content = require('./content'); exports.Outcomes = require('./outcomes'); }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/extensions/outcomes.js
aws/lti-middleware/node_modules/ims-lti/lib/extensions/outcomes.js
// Generated by CoffeeScript 1.10.0 (function() { var HMAC_SHA1, OutcomeDocument, OutcomeService, crypto, errors, http, https, navigateXml, url, utils, uuid, xml2js, xml_builder; crypto = require('crypto'); http = require('http'); https = require('https'); url = require('url'); uuid = require('node-uuid'); xml2js = require('xml2js'); xml_builder = require('xmlbuilder'); errors = require('../errors'); HMAC_SHA1 = require('../hmac-sha1'); utils = require('../utils'); navigateXml = function(xmlObject, path) { var i, len, part, ref, ref1; ref = path.split('.'); for (i = 0, len = ref.length; i < len; i++) { part = ref[i]; xmlObject = xmlObject != null ? (ref1 = xmlObject[part]) != null ? ref1[0] : void 0 : void 0; } return xmlObject; }; OutcomeDocument = (function() { function OutcomeDocument(type, source_did, outcome_service) { var xmldec; this.outcome_service = outcome_service; xmldec = { version: '1.0', encoding: 'UTF-8' }; this.doc = xml_builder.create('imsx_POXEnvelopeRequest', xmldec); this.doc.attribute('xmlns', 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'); this.head = this.doc.ele('imsx_POXHeader').ele('imsx_POXRequestHeaderInfo'); this.body = this.doc.ele('imsx_POXBody').ele(type + 'Request').ele('resultRecord'); this.head.ele('imsx_version', 'V1.0'); this.head.ele('imsx_messageIdentifier', uuid.v1()); this.body.ele('sourcedGUID').ele('sourcedId', source_did); } OutcomeDocument.prototype.add_score = function(score, language) { var eScore; if (typeof score !== 'number' || score < 0 || score > 1.0) { throw new errors.ParameterError('Score must be a floating point number >= 0 and <= 1'); } eScore = this._result_ele().ele('resultScore'); eScore.ele('language', language); return eScore.ele('textString', score); }; OutcomeDocument.prototype.add_text = function(text) { return this._add_payload('text', text); }; OutcomeDocument.prototype.add_url = function(url) { return this._add_payload('url', url); }; OutcomeDocument.prototype.finalize = function() { return this.doc.end({ pretty: true }); }; OutcomeDocument.prototype._result_ele = function() { return this.result || (this.result = this.body.ele('result')); }; OutcomeDocument.prototype._add_payload = function(type, value) { if (this.has_payload) { throw new errors.ExtensionError('Result data payload has already been set'); } if (!this.outcome_service.supports_result_data(type)) { throw new errors.ExtensionError('Result data type is not supported'); } this._result_ele().ele('resultData').ele(type, value); return this.has_payload = true; }; return OutcomeDocument; })(); OutcomeService = (function() { OutcomeService.prototype.REQUEST_REPLACE = 'replaceResult'; OutcomeService.prototype.REQUEST_READ = 'readResult'; OutcomeService.prototype.REQUEST_DELETE = 'deleteResult'; function OutcomeService(options) { var parts; if (options == null) { options = {}; } this.consumer_key = options.consumer_key; this.consumer_secret = options.consumer_secret; this.service_url = options.service_url; this.source_did = options.source_did; this.result_data_types = options.result_data_types || []; this.signer = options.signer || (new HMAC_SHA1()); this.cert_authority = options.cert_authority || null; this.language = options.language || 'en'; parts = this.service_url_parts = url.parse(this.service_url, true); this.service_url_oauth = parts.protocol + '//' + parts.host + parts.pathname; } OutcomeService.prototype.send_replace_result = function(score, callback) { var doc, err, error; doc = new OutcomeDocument(this.REQUEST_REPLACE, this.source_did, this); try { doc.add_score(score, this.language); return this._send_request(doc, callback); } catch (error) { err = error; return callback(err, false); } }; OutcomeService.prototype.send_replace_result_with_text = function(score, text, callback) { var doc, err, error; doc = new OutcomeDocument(this.REQUEST_REPLACE, this.source_did, this); try { doc.add_score(score, this.language, doc.add_text(text)); return this._send_request(doc, callback); } catch (error) { err = error; return callback(err, false); } }; OutcomeService.prototype.send_replace_result_with_url = function(score, url, callback) { var doc, err, error; doc = new OutcomeDocument(this.REQUEST_REPLACE, this.source_did, this); try { doc.add_score(score, this.language, doc.add_url(url)); return this._send_request(doc, callback); } catch (error) { err = error; return callback(err, false); } }; OutcomeService.prototype.send_read_result = function(callback) { var doc; doc = new OutcomeDocument(this.REQUEST_READ, this.source_did, this); return this._send_request(doc, (function(_this) { return function(err, result, xml) { var score; if (err) { return callback(err, result); } score = parseFloat(navigateXml(xml, 'imsx_POXBody.readResultResponse.result.resultScore.textString'), 10); if (isNaN(score)) { return callback(new errors.OutcomeResponseError('Invalid score response'), false); } else { return callback(null, score); } }; })(this)); }; OutcomeService.prototype.send_delete_result = function(callback) { var doc; doc = new OutcomeDocument(this.REQUEST_DELETE, this.source_did, this); return this._send_request(doc, callback); }; OutcomeService.prototype.supports_result_data = function(type) { return this.result_data_types.length && (!type || this.result_data_types.indexOf(type) !== -1); }; OutcomeService.prototype._send_request = function(doc, callback) { var body, is_ssl, options, req, xml; xml = doc.finalize(); body = ''; is_ssl = this.service_url_parts.protocol === 'https:'; options = { hostname: this.service_url_parts.hostname, path: this.service_url_parts.path, method: 'POST', headers: this._build_headers(xml) }; if (this.cert_authority && is_ssl) { options.ca = this.cert_authority; } else { options.agent = is_ssl ? https.globalAgent : http.globalAgent; } if (this.service_url_parts.port) { options.port = this.service_url_parts.port; } req = (is_ssl ? https : http).request(options, (function(_this) { return function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { return body += chunk; }); return res.on('end', function() { return _this._process_response(body, callback); }); }; })(this)); req.on('error', (function(_this) { return function(err) { return callback(err, false); }; })(this)); req.write(xml); return req.end(); }; OutcomeService.prototype._build_headers = function(body) { var headers, key, val; headers = { oauth_version: '1.0', oauth_nonce: uuid.v4(), oauth_timestamp: Math.round(Date.now() / 1000), oauth_consumer_key: this.consumer_key, oauth_body_hash: crypto.createHash('sha1').update(body).digest('base64'), oauth_signature_method: 'HMAC-SHA1' }; headers.oauth_signature = this.signer.build_signature_raw(this.service_url_oauth, this.service_url_parts, 'POST', headers, this.consumer_secret); return { Authorization: 'OAuth realm="",' + ((function() { var results; results = []; for (key in headers) { val = headers[key]; results.push(key + "=\"" + (utils.special_encode(val)) + "\""); } return results; })()).join(','), 'Content-Type': 'application/xml', 'Content-Length': body.length }; }; OutcomeService.prototype._process_response = function(body, callback) { return xml2js.parseString(body, { trim: true }, (function(_this) { return function(err, result) { var code, msg, response; if (err) { return callback(new errors.OutcomeResponseError('The server responsed with an invalid XML document'), false); } response = result != null ? result.imsx_POXEnvelopeResponse : void 0; code = navigateXml(response, 'imsx_POXHeader.imsx_POXResponseHeaderInfo.imsx_statusInfo.imsx_codeMajor'); if (code !== 'success') { msg = navigateXml(response, 'imsx_POXHeader.imsx_POXResponseHeaderInfo.imsx_statusInfo.imsx_description'); return callback(new errors.OutcomeResponseError(msg), false); } else { return callback(null, true, response); } }; })(this)); }; return OutcomeService; })(); exports.init = function(provider) { var accepted_vals; if (provider.body.lis_outcome_service_url && provider.body.lis_result_sourcedid) { accepted_vals = provider.body.ext_outcome_data_values_accepted; return provider.outcome_service = new OutcomeService({ consumer_key: provider.consumer_key, consumer_secret: provider.consumer_secret, service_url: provider.body.lis_outcome_service_url, source_did: provider.body.lis_result_sourcedid, result_data_types: accepted_vals && accepted_vals.split(',') || [], signer: provider.signer }); } else { return provider.outcome_service = false; } }; exports.OutcomeService = OutcomeService; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/ims-lti/lib/extensions/content.js
aws/lti-middleware/node_modules/ims-lti/lib/extensions/content.js
// Generated by CoffeeScript 1.10.0 (function() { var ContentExtension, FILE_RETURN_TYPE, IFRAME_RETURN_TYPE, IMAGE_URL_RETURN_TYPE, LTI_LAUNCH_URL_RETURN_TYPE, OEMBED_RETURN_TYPE, URL_RETURN_TYPE, errors, optional_url_property_setter, parse_url, url; url = require('url'); errors = require('../errors'); FILE_RETURN_TYPE = 'file'; IFRAME_RETURN_TYPE = 'iframe'; IMAGE_URL_RETURN_TYPE = 'image_url'; LTI_LAUNCH_URL_RETURN_TYPE = 'lti_launch_url'; OEMBED_RETURN_TYPE = 'oembed'; URL_RETURN_TYPE = 'url'; parse_url = function(raw_url) { var return_url; return_url = url.parse(raw_url, true); delete return_url.path; return return_url; }; optional_url_property_setter = function(return_url) { return function(property, value) { if (typeof value !== 'undefined') { return return_url.query[property] = value; } }; }; ContentExtension = (function() { function ContentExtension(params) { this.return_types = params.ext_content_return_types.split(','); this.return_url = params.ext_content_return_url || params.launch_presentation_return_url; this.file_extensions = (params.ext_content_file_extensions && params.ext_content_file_extensions.split(',')) || []; } ContentExtension.prototype.has_return_type = function(return_type) { return this.return_types.indexOf(return_type) !== -1; }; ContentExtension.prototype.has_file_extension = function(extension) { return this.file_extensions.indexOf(extension) !== -1; }; ContentExtension.prototype.send_file = function(res, file_url, text, content_type) { var return_url, set_if_exists; this._validate_return_type(FILE_RETURN_TYPE); return_url = parse_url(this.return_url, true); set_if_exists = optional_url_property_setter(return_url); return_url.query.return_type = FILE_RETURN_TYPE; return_url.query.url = file_url; return_url.query.text = text; set_if_exists('content_type', content_type); return exports.redirector(res, url.format(return_url)); }; ContentExtension.prototype.send_iframe = function(res, iframe_url, title, width, height) { var return_url, set_if_exists; this._validate_return_type(IFRAME_RETURN_TYPE); return_url = parse_url(this.return_url, true); set_if_exists = optional_url_property_setter(return_url); return_url.query.return_type = IFRAME_RETURN_TYPE; return_url.query.url = iframe_url; set_if_exists("title", title); set_if_exists("width", width); set_if_exists("height", height); return exports.redirector(res, url.format(return_url)); }; ContentExtension.prototype.send_image_url = function(res, image_url, text, width, height) { var return_url, set_if_exists; this._validate_return_type(IMAGE_URL_RETURN_TYPE); return_url = parse_url(this.return_url, true); set_if_exists = optional_url_property_setter(return_url); return_url.query.return_type = IMAGE_URL_RETURN_TYPE; return_url.query.url = image_url; set_if_exists("text", text); set_if_exists("width", width); set_if_exists("height", height); return exports.redirector(res, url.format(return_url)); }; ContentExtension.prototype.send_lti_launch_url = function(res, launch_url, title, text) { var return_url, set_if_exists; this._validate_return_type(LTI_LAUNCH_URL_RETURN_TYPE); return_url = parse_url(this.return_url, true); set_if_exists = optional_url_property_setter(return_url); return_url.query.return_type = LTI_LAUNCH_URL_RETURN_TYPE; return_url.query.url = launch_url; set_if_exists("title", title); set_if_exists("text", text); return exports.redirector(res, url.format(return_url)); }; ContentExtension.prototype.send_oembed = function(res, oembed_url, endpoint) { var return_url, set_if_exists; this._validate_return_type(OEMBED_RETURN_TYPE); return_url = parse_url(this.return_url, true); set_if_exists = optional_url_property_setter(return_url); return_url.query.return_type = OEMBED_RETURN_TYPE; return_url.query.url = oembed_url; set_if_exists("endpoint", endpoint); return exports.redirector(res, url.format(return_url)); }; ContentExtension.prototype.send_url = function(res, hyperlink, text, title, target) { var return_url, set_if_exists; this._validate_return_type(URL_RETURN_TYPE); return_url = parse_url(this.return_url, true); set_if_exists = optional_url_property_setter(return_url); return_url.query.return_type = URL_RETURN_TYPE; return_url.query.url = hyperlink; set_if_exists('text', text); set_if_exists('title', title); set_if_exists('target', target); return exports.redirector(res, url.format(return_url)); }; ContentExtension.prototype._validate_return_type = function(return_type) { if (this.has_return_type(return_type) === false) { throw new errors.ExtensionError('Invalid return type, valid options are ' + this.return_types.join(', ')); } }; return ContentExtension; })(); exports.init = function(provider) { if (provider.body.ext_content_return_types) { return provider.ext_content = new ContentExtension(provider.body); } else { return provider.ext_content = false; } }; exports.redirector = function(res, url) { return res.redirect(303, url); }; }).call(this);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/event-target-shim/dist/event-target-shim.umd.js
aws/lti-middleware/node_modules/event-target-shim/dist/event-target-shim.umd.js
/** * @author Toru Nagashima <https://github.com/mysticatea> * @copyright 2015 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.EventTargetShim={}))})(this,function(a){"use strict";function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a){var b=u.get(a);return console.assert(null!=b,"'this' is expected an Event object, but got",a),b}function d(a){return null==a.passiveListener?void(!a.event.cancelable||(a.canceled=!0,"function"==typeof a.event.preventDefault&&a.event.preventDefault())):void("undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",a.passiveListener))}function e(a,b){u.set(this,{eventTarget:a,event:b,eventPhase:2,currentTarget:a,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:b.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});for(var c,d=Object.keys(b),e=0;e<d.length;++e)c=d[e],c in this||Object.defineProperty(this,c,f(c))}function f(a){return{get:function(){return c(this).event[a]},set:function(b){c(this).event[a]=b},configurable:!0,enumerable:!0}}function g(a){return{value:function(){var b=c(this).event;return b[a].apply(b,arguments)},configurable:!0,enumerable:!0}}function h(a,b){function c(b,c){a.call(this,b,c)}var d=Object.keys(b);if(0===d.length)return a;c.prototype=Object.create(a.prototype,{constructor:{value:c,configurable:!0,writable:!0}});for(var e,h=0;h<d.length;++h)if(e=d[h],!(e in a.prototype)){var j=Object.getOwnPropertyDescriptor(b,e),k="function"==typeof j.value;Object.defineProperty(c.prototype,e,k?g(e):f(e))}return c}function i(a){if(null==a||a===Object.prototype)return e;var b=v.get(a);return null==b&&(b=h(i(Object.getPrototypeOf(a)),a),v.set(a,b)),b}function j(a,b){var c=i(Object.getPrototypeOf(b));return new c(a,b)}function k(a){return c(a).immediateStopped}function l(a,b){c(a).eventPhase=b}function m(a,b){c(a).currentTarget=b}function n(a,b){c(a).passiveListener=b}function o(a){return null!==a&&"object"===b(a)}function p(a){var b=w.get(a);if(null==b)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return b}function q(a){return{get:function(){for(var b=p(this),c=b.get(a);null!=c;){if(3===c.listenerType)return c.listener;c=c.next}return null},set:function(b){"function"==typeof b||o(b)||(b=null);for(var c=p(this),d=null,e=c.get(a);null!=e;)3===e.listenerType?null===d?null===e.next?c.delete(a):c.set(a,e.next):d.next=e.next:d=e,e=e.next;if(null!==b){var f={listener:b,listenerType:3,passive:!1,once:!1,next:null};null===d?c.set(a,f):d.next=f}},configurable:!0,enumerable:!0}}function r(a,b){Object.defineProperty(a,"on".concat(b),q(b))}function s(a){function b(){t.call(this)}b.prototype=Object.create(t.prototype,{constructor:{value:b,configurable:!0,writable:!0}});for(var c=0;c<a.length;++c)r(b.prototype,a[c]);return b}function t(){if(this instanceof t)return void w.set(this,new Map);if(1===arguments.length&&Array.isArray(arguments[0]))return s(arguments[0]);if(0<arguments.length){for(var a=Array(arguments.length),b=0;b<arguments.length;++b)a[b]=arguments[b];return s(a)}throw new TypeError("Cannot call a class as a function")}var u=new WeakMap,v=new WeakMap;e.prototype={get type(){return c(this).event.type},get target(){return c(this).eventTarget},get currentTarget(){return c(this).currentTarget},composedPath:function(){var a=c(this).currentTarget;return null==a?[]:[a]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return c(this).eventPhase},stopPropagation:function(){var a=c(this);a.stopped=!0,"function"==typeof a.event.stopPropagation&&a.event.stopPropagation()},stopImmediatePropagation:function(){var a=c(this);a.stopped=!0,a.immediateStopped=!0,"function"==typeof a.event.stopImmediatePropagation&&a.event.stopImmediatePropagation()},get bubbles(){return!!c(this).event.bubbles},get cancelable(){return!!c(this).event.cancelable},preventDefault:function(){d(c(this))},get defaultPrevented(){return c(this).canceled},get composed(){return!!c(this).event.composed},get timeStamp(){return c(this).timeStamp},get srcElement(){return c(this).eventTarget},get cancelBubble(){return c(this).stopped},set cancelBubble(a){if(a){var b=c(this);b.stopped=!0,"boolean"==typeof b.event.cancelBubble&&(b.event.cancelBubble=!0)}},get returnValue(){return!c(this).canceled},set returnValue(a){a||d(c(this))},initEvent:function(){}},Object.defineProperty(e.prototype,"constructor",{value:e,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.Event&&(Object.setPrototypeOf(e.prototype,window.Event.prototype),v.set(window.Event.prototype,e));var w=new WeakMap,x=1,y=2;if(t.prototype={addEventListener:function(a,b,c){if(null!=b){if("function"!=typeof b&&!o(b))throw new TypeError("'listener' should be a function or an object.");var d=p(this),e=o(c),f=e?!!c.capture:!!c,g=f?x:y,h={listener:b,listenerType:g,passive:e&&!!c.passive,once:e&&!!c.once,next:null},i=d.get(a);if(void 0===i)return void d.set(a,h);for(var j=null;null!=i;){if(i.listener===b&&i.listenerType===g)return;j=i,i=i.next}j.next=h}},removeEventListener:function(a,b,c){if(null!=b)for(var d=p(this),e=o(c)?!!c.capture:!!c,f=e?x:y,g=null,h=d.get(a);null!=h;){if(h.listener===b&&h.listenerType===f)return void(null===g?null===h.next?d.delete(a):d.set(a,h.next):g.next=h.next);g=h,h=h.next}},dispatchEvent:function(a){if(null==a||"string"!=typeof a.type)throw new TypeError("\"event.type\" should be a string.");var b=p(this),c=a.type,d=b.get(c);if(null==d)return!0;for(var e=j(this,a),f=null;null!=d;){if(d.once?null===f?null===d.next?b.delete(c):b.set(c,d.next):f.next=d.next:f=d,n(e,d.passive?d.listener:null),"function"==typeof d.listener)try{d.listener.call(this,e)}catch(a){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(a)}else d.listenerType!==3&&"function"==typeof d.listener.handleEvent&&d.listener.handleEvent(e);if(k(e))break;d=d.next}return n(e,null),l(e,0),m(e,null),!e.defaultPrevented}},Object.defineProperty(t.prototype,"constructor",{value:t,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.EventTarget&&Object.setPrototypeOf(t.prototype,window.EventTarget.prototype),a.defineEventAttribute=r,a.EventTarget=t,a.default=t,Object.defineProperty(a,"__esModule",{value:!0}),"undefined"==typeof module&&"undefined"==typeof define){var z=Function("return this")();z.EventTargetShim=t,z.EventTargetShim.defineEventAttribute=r}}); //# sourceMappingURL=event-target-shim.umd.js.map
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/event-target-shim/dist/event-target-shim.js
aws/lti-middleware/node_modules/event-target-shim/dist/event-target-shim.js
/** * @author Toru Nagashima <https://github.com/mysticatea> * @copyright 2015 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * @typedef {object} PrivateData * @property {EventTarget} eventTarget The event target. * @property {{type:string}} event The original event object. * @property {number} eventPhase The current event phase. * @property {EventTarget|null} currentTarget The current event target. * @property {boolean} canceled The flag to prevent default. * @property {boolean} stopped The flag to stop propagation. * @property {boolean} immediateStopped The flag to stop propagation immediately. * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. * @property {number} timeStamp The unix time. * @private */ /** * Private data for event wrappers. * @type {WeakMap<Event, PrivateData>} * @private */ const privateData = new WeakMap(); /** * Cache for wrapper classes. * @type {WeakMap<Object, Function>} * @private */ const wrappers = new WeakMap(); /** * Get private data. * @param {Event} event The event object to get private data. * @returns {PrivateData} The private data of the event. * @private */ function pd(event) { const retv = privateData.get(event); console.assert( retv != null, "'this' is expected an Event object, but got", event ); return retv } /** * https://dom.spec.whatwg.org/#set-the-canceled-flag * @param data {PrivateData} private data. */ function setCancelFlag(data) { if (data.passiveListener != null) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error( "Unable to preventDefault inside passive event listener invocation.", data.passiveListener ); } return } if (!data.event.cancelable) { return } data.canceled = true; if (typeof data.event.preventDefault === "function") { data.event.preventDefault(); } } /** * @see https://dom.spec.whatwg.org/#interface-event * @private */ /** * The event wrapper. * @constructor * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Event|{type:string}} event The original event to wrap. */ function Event(eventTarget, event) { privateData.set(this, { eventTarget, event, eventPhase: 2, currentTarget: eventTarget, canceled: false, stopped: false, immediateStopped: false, passiveListener: null, timeStamp: event.timeStamp || Date.now(), }); // https://heycam.github.io/webidl/#Unforgeable Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); // Define accessors const keys = Object.keys(event); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in this)) { Object.defineProperty(this, key, defineRedirectDescriptor(key)); } } } // Should be enumerable, but class methods are not enumerable. Event.prototype = { /** * The type of this event. * @type {string} */ get type() { return pd(this).event.type }, /** * The target of this event. * @type {EventTarget} */ get target() { return pd(this).eventTarget }, /** * The target of this event. * @type {EventTarget} */ get currentTarget() { return pd(this).currentTarget }, /** * @returns {EventTarget[]} The composed path of this event. */ composedPath() { const currentTarget = pd(this).currentTarget; if (currentTarget == null) { return [] } return [currentTarget] }, /** * Constant of NONE. * @type {number} */ get NONE() { return 0 }, /** * Constant of CAPTURING_PHASE. * @type {number} */ get CAPTURING_PHASE() { return 1 }, /** * Constant of AT_TARGET. * @type {number} */ get AT_TARGET() { return 2 }, /** * Constant of BUBBLING_PHASE. * @type {number} */ get BUBBLING_PHASE() { return 3 }, /** * The target of this event. * @type {number} */ get eventPhase() { return pd(this).eventPhase }, /** * Stop event bubbling. * @returns {void} */ stopPropagation() { const data = pd(this); data.stopped = true; if (typeof data.event.stopPropagation === "function") { data.event.stopPropagation(); } }, /** * Stop event bubbling. * @returns {void} */ stopImmediatePropagation() { const data = pd(this); data.stopped = true; data.immediateStopped = true; if (typeof data.event.stopImmediatePropagation === "function") { data.event.stopImmediatePropagation(); } }, /** * The flag to be bubbling. * @type {boolean} */ get bubbles() { return Boolean(pd(this).event.bubbles) }, /** * The flag to be cancelable. * @type {boolean} */ get cancelable() { return Boolean(pd(this).event.cancelable) }, /** * Cancel this event. * @returns {void} */ preventDefault() { setCancelFlag(pd(this)); }, /** * The flag to indicate cancellation state. * @type {boolean} */ get defaultPrevented() { return pd(this).canceled }, /** * The flag to be composed. * @type {boolean} */ get composed() { return Boolean(pd(this).event.composed) }, /** * The unix time of this event. * @type {number} */ get timeStamp() { return pd(this).timeStamp }, /** * The target of this event. * @type {EventTarget} * @deprecated */ get srcElement() { return pd(this).eventTarget }, /** * The flag to stop event bubbling. * @type {boolean} * @deprecated */ get cancelBubble() { return pd(this).stopped }, set cancelBubble(value) { if (!value) { return } const data = pd(this); data.stopped = true; if (typeof data.event.cancelBubble === "boolean") { data.event.cancelBubble = true; } }, /** * The flag to indicate cancellation state. * @type {boolean} * @deprecated */ get returnValue() { return !pd(this).canceled }, set returnValue(value) { if (!value) { setCancelFlag(pd(this)); } }, /** * Initialize this event object. But do nothing under event dispatching. * @param {string} type The event type. * @param {boolean} [bubbles=false] The flag to be possible to bubble up. * @param {boolean} [cancelable=false] The flag to be possible to cancel. * @deprecated */ initEvent() { // Do nothing. }, }; // `constructor` is not enumerable. Object.defineProperty(Event.prototype, "constructor", { value: Event, configurable: true, writable: true, }); // Ensure `event instanceof window.Event` is `true`. if (typeof window !== "undefined" && typeof window.Event !== "undefined") { Object.setPrototypeOf(Event.prototype, window.Event.prototype); // Make association for wrappers. wrappers.set(window.Event.prototype, Event); } /** * Get the property descriptor to redirect a given property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to redirect the property. * @private */ function defineRedirectDescriptor(key) { return { get() { return pd(this).event[key] }, set(value) { pd(this).event[key] = value; }, configurable: true, enumerable: true, } } /** * Get the property descriptor to call a given method property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to call the method property. * @private */ function defineCallDescriptor(key) { return { value() { const event = pd(this).event; return event[key].apply(event, arguments) }, configurable: true, enumerable: true, } } /** * Define new wrapper class. * @param {Function} BaseEvent The base wrapper class. * @param {Object} proto The prototype of the original event. * @returns {Function} The defined wrapper class. * @private */ function defineWrapper(BaseEvent, proto) { const keys = Object.keys(proto); if (keys.length === 0) { return BaseEvent } /** CustomEvent */ function CustomEvent(eventTarget, event) { BaseEvent.call(this, eventTarget, event); } CustomEvent.prototype = Object.create(BaseEvent.prototype, { constructor: { value: CustomEvent, configurable: true, writable: true }, }); // Define accessors. for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in BaseEvent.prototype)) { const descriptor = Object.getOwnPropertyDescriptor(proto, key); const isFunc = typeof descriptor.value === "function"; Object.defineProperty( CustomEvent.prototype, key, isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key) ); } } return CustomEvent } /** * Get the wrapper class of a given prototype. * @param {Object} proto The prototype of the original event to get its wrapper. * @returns {Function} The wrapper class. * @private */ function getWrapper(proto) { if (proto == null || proto === Object.prototype) { return Event } let wrapper = wrappers.get(proto); if (wrapper == null) { wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); wrappers.set(proto, wrapper); } return wrapper } /** * Wrap a given event to management a dispatching. * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Object} event The event to wrap. * @returns {Event} The wrapper instance. * @private */ function wrapEvent(eventTarget, event) { const Wrapper = getWrapper(Object.getPrototypeOf(event)); return new Wrapper(eventTarget, event) } /** * Get the immediateStopped flag of a given event. * @param {Event} event The event to get. * @returns {boolean} The flag to stop propagation immediately. * @private */ function isStopped(event) { return pd(event).immediateStopped } /** * Set the current event phase of a given event. * @param {Event} event The event to set current target. * @param {number} eventPhase New event phase. * @returns {void} * @private */ function setEventPhase(event, eventPhase) { pd(event).eventPhase = eventPhase; } /** * Set the current target of a given event. * @param {Event} event The event to set current target. * @param {EventTarget|null} currentTarget New current target. * @returns {void} * @private */ function setCurrentTarget(event, currentTarget) { pd(event).currentTarget = currentTarget; } /** * Set a passive listener of a given event. * @param {Event} event The event to set current target. * @param {Function|null} passiveListener New passive listener. * @returns {void} * @private */ function setPassiveListener(event, passiveListener) { pd(event).passiveListener = passiveListener; } /** * @typedef {object} ListenerNode * @property {Function} listener * @property {1|2|3} listenerType * @property {boolean} passive * @property {boolean} once * @property {ListenerNode|null} next * @private */ /** * @type {WeakMap<object, Map<string, ListenerNode>>} * @private */ const listenersMap = new WeakMap(); // Listener types const CAPTURE = 1; const BUBBLE = 2; const ATTRIBUTE = 3; /** * Check whether a given value is an object or not. * @param {any} x The value to check. * @returns {boolean} `true` if the value is an object. */ function isObject(x) { return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax } /** * Get listeners. * @param {EventTarget} eventTarget The event target to get. * @returns {Map<string, ListenerNode>} The listeners. * @private */ function getListeners(eventTarget) { const listeners = listenersMap.get(eventTarget); if (listeners == null) { throw new TypeError( "'this' is expected an EventTarget object, but got another value." ) } return listeners } /** * Get the property descriptor for the event attribute of a given event. * @param {string} eventName The event name to get property descriptor. * @returns {PropertyDescriptor} The property descriptor. * @private */ function defineEventAttributeDescriptor(eventName) { return { get() { const listeners = getListeners(this); let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { return node.listener } node = node.next; } return null }, set(listener) { if (typeof listener !== "function" && !isObject(listener)) { listener = null; // eslint-disable-line no-param-reassign } const listeners = getListeners(this); // Traverse to the tail while removing old value. let prev = null; let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { // Remove old value. if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } node = node.next; } // Add new value. if (listener !== null) { const newNode = { listener, listenerType: ATTRIBUTE, passive: false, once: false, next: null, }; if (prev === null) { listeners.set(eventName, newNode); } else { prev.next = newNode; } } }, configurable: true, enumerable: true, } } /** * Define an event attribute (e.g. `eventTarget.onclick`). * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. * @param {string} eventName The event name to define. * @returns {void} */ function defineEventAttribute(eventTargetPrototype, eventName) { Object.defineProperty( eventTargetPrototype, `on${eventName}`, defineEventAttributeDescriptor(eventName) ); } /** * Define a custom EventTarget with event attributes. * @param {string[]} eventNames Event names for event attributes. * @returns {EventTarget} The custom EventTarget. * @private */ function defineCustomEventTarget(eventNames) { /** CustomEventTarget */ function CustomEventTarget() { EventTarget.call(this); } CustomEventTarget.prototype = Object.create(EventTarget.prototype, { constructor: { value: CustomEventTarget, configurable: true, writable: true, }, }); for (let i = 0; i < eventNames.length; ++i) { defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); } return CustomEventTarget } /** * EventTarget. * * - This is constructor if no arguments. * - This is a function which returns a CustomEventTarget constructor if there are arguments. * * For example: * * class A extends EventTarget {} * class B extends EventTarget("message") {} * class C extends EventTarget("message", "error") {} * class D extends EventTarget(["message", "error"]) {} */ function EventTarget() { /*eslint-disable consistent-return */ if (this instanceof EventTarget) { listenersMap.set(this, new Map()); return } if (arguments.length === 1 && Array.isArray(arguments[0])) { return defineCustomEventTarget(arguments[0]) } if (arguments.length > 0) { const types = new Array(arguments.length); for (let i = 0; i < arguments.length; ++i) { types[i] = arguments[i]; } return defineCustomEventTarget(types) } throw new TypeError("Cannot call a class as a function") /*eslint-enable consistent-return */ } // Should be enumerable, but class methods are not enumerable. EventTarget.prototype = { /** * Add a given listener to this event target. * @param {string} eventName The event name to add. * @param {Function} listener The listener to add. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ addEventListener(eventName, listener, options) { if (listener == null) { return } if (typeof listener !== "function" && !isObject(listener)) { throw new TypeError("'listener' should be a function or an object.") } const listeners = getListeners(this); const optionsIsObj = isObject(options); const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; const newNode = { listener, listenerType, passive: optionsIsObj && Boolean(options.passive), once: optionsIsObj && Boolean(options.once), next: null, }; // Set it as the first node if the first node is null. let node = listeners.get(eventName); if (node === undefined) { listeners.set(eventName, newNode); return } // Traverse to the tail while checking duplication.. let prev = null; while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { // Should ignore duplication. return } prev = node; node = node.next; } // Add it. prev.next = newNode; }, /** * Remove a given listener from this event target. * @param {string} eventName The event name to remove. * @param {Function} listener The listener to remove. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ removeEventListener(eventName, listener, options) { if (listener == null) { return } const listeners = getListeners(this); const capture = isObject(options) ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; let prev = null; let node = listeners.get(eventName); while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } return } prev = node; node = node.next; } }, /** * Dispatch a given event. * @param {Event|{type:string}} event The event to dispatch. * @returns {boolean} `false` if canceled. */ dispatchEvent(event) { if (event == null || typeof event.type !== "string") { throw new TypeError('"event.type" should be a string.') } // If listeners aren't registered, terminate. const listeners = getListeners(this); const eventName = event.type; let node = listeners.get(eventName); if (node == null) { return true } // Since we cannot rewrite several properties, so wrap object. const wrappedEvent = wrapEvent(this, event); // This doesn't process capturing phase and bubbling phase. // This isn't participating in a tree. let prev = null; while (node != null) { // Remove this listener if it's once if (node.once) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } // Call this listener setPassiveListener( wrappedEvent, node.passive ? node.listener : null ); if (typeof node.listener === "function") { try { node.listener.call(this, wrappedEvent); } catch (err) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error(err); } } } else if ( node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function" ) { node.listener.handleEvent(wrappedEvent); } // Break if `event.stopImmediatePropagation` was called. if (isStopped(wrappedEvent)) { break } node = node.next; } setPassiveListener(wrappedEvent, null); setEventPhase(wrappedEvent, 0); setCurrentTarget(wrappedEvent, null); return !wrappedEvent.defaultPrevented }, }; // `constructor` is not enumerable. Object.defineProperty(EventTarget.prototype, "constructor", { value: EventTarget, configurable: true, writable: true, }); // Ensure `eventTarget instanceof window.EventTarget` is `true`. if ( typeof window !== "undefined" && typeof window.EventTarget !== "undefined" ) { Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); } exports.defineEventAttribute = defineEventAttribute; exports.EventTarget = EventTarget; exports.default = EventTarget; module.exports = EventTarget module.exports.EventTarget = module.exports["default"] = EventTarget module.exports.defineEventAttribute = defineEventAttribute //# sourceMappingURL=event-target-shim.js.map
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/level-codec/index.js
aws/lti-middleware/node_modules/level-codec/index.js
'use strict' const encodings = require('./lib/encodings') const rangeOptions = new Set(['lt', 'gt', 'lte', 'gte']) module.exports = Codec function Codec (opts) { if (!(this instanceof Codec)) { return new Codec(opts) } this.opts = opts || {} this.encodings = encodings } Codec.prototype._encoding = function (encoding) { if (typeof encoding === 'string') encoding = encodings[encoding] if (!encoding) encoding = encodings.id return encoding } Codec.prototype._keyEncoding = function (opts, batchOpts) { return this._encoding((batchOpts && batchOpts.keyEncoding) || (opts && opts.keyEncoding) || this.opts.keyEncoding) } Codec.prototype._valueEncoding = function (opts, batchOpts) { return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) || (opts && (opts.valueEncoding || opts.encoding)) || (this.opts.valueEncoding || this.opts.encoding)) } Codec.prototype.encodeKey = function (key, opts, batchOpts) { return this._keyEncoding(opts, batchOpts).encode(key) } Codec.prototype.encodeValue = function (value, opts, batchOpts) { return this._valueEncoding(opts, batchOpts).encode(value) } Codec.prototype.decodeKey = function (key, opts) { return this._keyEncoding(opts).decode(key) } Codec.prototype.decodeValue = function (value, opts) { return this._valueEncoding(opts).decode(value) } Codec.prototype.encodeBatch = function (ops, opts) { return ops.map((_op) => { const op = { type: _op.type, key: this.encodeKey(_op.key, opts, _op) } if (this.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary' if (_op.prefix) op.prefix = _op.prefix if ('value' in _op) { op.value = this.encodeValue(_op.value, opts, _op) if (this.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary' } return op }) } Codec.prototype.encodeLtgt = function (ltgt) { const ret = {} for (const key of Object.keys(ltgt)) { if (key === 'start' || key === 'end') { throw new Error('Legacy range options ("start" and "end") have been removed') } ret[key] = rangeOptions.has(key) ? this.encodeKey(ltgt[key], ltgt) : ltgt[key] } return ret } Codec.prototype.createStreamDecoder = function (opts) { if (opts.keys && opts.values) { return (key, value) => { return { key: this.decodeKey(key, opts), value: this.decodeValue(value, opts) } } } else if (opts.keys) { return (key) => { return this.decodeKey(key, opts) } } else if (opts.values) { return (_, value) => { return this.decodeValue(value, opts) } } else { return function () {} } } Codec.prototype.keyAsBuffer = function (opts) { return this._keyEncoding(opts).buffer } Codec.prototype.valueAsBuffer = function (opts) { return this._valueEncoding(opts).buffer }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/level-codec/lib/encodings.js
aws/lti-middleware/node_modules/level-codec/lib/encodings.js
'use strict' const { Buffer } = require('buffer') exports.utf8 = exports['utf-8'] = { encode: function (data) { return isBinary(data) ? data : String(data) }, decode: identity, buffer: false, type: 'utf8' } exports.json = { encode: JSON.stringify, decode: JSON.parse, buffer: false, type: 'json' } exports.binary = { encode: function (data) { return isBinary(data) ? data : Buffer.from(data) }, decode: identity, buffer: true, type: 'binary' } exports.none = { encode: identity, decode: identity, buffer: false, type: 'id' } exports.id = exports.none const bufferEncodings = [ 'hex', 'ascii', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le' ] for (const type of bufferEncodings) { exports[type] = { encode: function (data) { return isBinary(data) ? data : Buffer.from(data, type) }, decode: function (buffer) { return buffer.toString(type) }, buffer: true, type: type } } function identity (value) { return value } function isBinary (data) { return data === undefined || data === null || Buffer.isBuffer(data) }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/ssh.js
aws/lti-middleware/node_modules/node-forge/lib/ssh.js
/** * Functions to output keys in SSH-friendly formats. * * This is part of the Forge project which may be used under the terms of * either the BSD License or the GNU General Public License (GPL) Version 2. * * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE * * @author https://github.com/shellac */ var forge = require('./forge'); require('./aes'); require('./hmac'); require('./md5'); require('./sha1'); require('./util'); var ssh = module.exports = forge.ssh = forge.ssh || {}; /** * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. * * @param privateKey the key. * @param passphrase a passphrase to protect the key (falsy for no encryption). * @param comment a comment to include in the key file. * * @return the PPK file as a string. */ ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { comment = comment || ''; passphrase = passphrase || ''; var algorithm = 'ssh-rsa'; var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; ppk += 'Comment: ' + comment + '\r\n'; // public key into buffer for ppk var pubbuffer = forge.util.createBuffer(); _addStringToBuffer(pubbuffer, algorithm); _addBigIntegerToBuffer(pubbuffer, privateKey.e); _addBigIntegerToBuffer(pubbuffer, privateKey.n); // write public key var pub = forge.util.encode64(pubbuffer.bytes(), 64); var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n ppk += 'Public-Lines: ' + length + '\r\n'; ppk += pub; // private key into a buffer var privbuffer = forge.util.createBuffer(); _addBigIntegerToBuffer(privbuffer, privateKey.d); _addBigIntegerToBuffer(privbuffer, privateKey.p); _addBigIntegerToBuffer(privbuffer, privateKey.q); _addBigIntegerToBuffer(privbuffer, privateKey.qInv); // optionally encrypt the private key var priv; if(!passphrase) { // use the unencrypted buffer priv = forge.util.encode64(privbuffer.bytes(), 64); } else { // encrypt RSA key using passphrase var encLen = privbuffer.length() + 16 - 1; encLen -= encLen % 16; // pad private key with sha1-d data -- needs to be a multiple of 16 var padding = _sha1(privbuffer.bytes()); padding.truncate(padding.length() - encLen + privbuffer.length()); privbuffer.putBuffer(padding); var aeskey = forge.util.createBuffer(); aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); // encrypt some bytes using CBC mode // key is 40 bytes, so truncate *by* 8 bytes var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); cipher.update(privbuffer.copy()); cipher.finish(); var encrypted = cipher.output; // Note: this appears to differ from Putty -- is forge wrong, or putty? // due to padding we finish as an exact multiple of 16 encrypted.truncate(16); // all padding priv = forge.util.encode64(encrypted.bytes(), 64); } // output private key length = Math.floor(priv.length / 66) + 1; // 64 + \r\n ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; ppk += priv; // MAC var mackey = _sha1('putty-private-key-file-mac-key', passphrase); var macbuffer = forge.util.createBuffer(); _addStringToBuffer(macbuffer, algorithm); _addStringToBuffer(macbuffer, encryptionAlgorithm); _addStringToBuffer(macbuffer, comment); macbuffer.putInt32(pubbuffer.length()); macbuffer.putBuffer(pubbuffer); macbuffer.putInt32(privbuffer.length()); macbuffer.putBuffer(privbuffer); var hmac = forge.hmac.create(); hmac.start('sha1', mackey); hmac.update(macbuffer.bytes()); ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; return ppk; }; /** * Encodes a public RSA key as an OpenSSH file. * * @param key the key. * @param comment a comment. * * @return the public key in OpenSSH format. */ ssh.publicKeyToOpenSSH = function(key, comment) { var type = 'ssh-rsa'; comment = comment || ''; var buffer = forge.util.createBuffer(); _addStringToBuffer(buffer, type); _addBigIntegerToBuffer(buffer, key.e); _addBigIntegerToBuffer(buffer, key.n); return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment; }; /** * Encodes a private RSA key as an OpenSSH file. * * @param key the key. * @param passphrase a passphrase to protect the key (falsy for no encryption). * * @return the public key in OpenSSH format. */ ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { if(!passphrase) { return forge.pki.privateKeyToPem(privateKey); } // OpenSSH private key is just a legacy format, it seems return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, {legacy: true, algorithm: 'aes128'}); }; /** * Gets the SSH fingerprint for the given public key. * * @param options the options to use. * [md] the message digest object to use (defaults to forge.md.md5). * [encoding] an alternative output encoding, such as 'hex' * (defaults to none, outputs a byte buffer). * [delimiter] the delimiter to use between bytes for 'hex' encoded * output, eg: ':' (defaults to none). * * @return the fingerprint as a byte buffer or other encoding based on options. */ ssh.getPublicKeyFingerprint = function(key, options) { options = options || {}; var md = options.md || forge.md.md5.create(); var type = 'ssh-rsa'; var buffer = forge.util.createBuffer(); _addStringToBuffer(buffer, type); _addBigIntegerToBuffer(buffer, key.e); _addBigIntegerToBuffer(buffer, key.n); // hash public key bytes md.start(); md.update(buffer.getBytes()); var digest = md.digest(); if(options.encoding === 'hex') { var hex = digest.toHex(); if(options.delimiter) { return hex.match(/.{2}/g).join(options.delimiter); } return hex; } else if(options.encoding === 'binary') { return digest.getBytes(); } else if(options.encoding) { throw new Error('Unknown encoding "' + options.encoding + '".'); } return digest; }; /** * Adds len(val) then val to a buffer. * * @param buffer the buffer to add to. * @param val a big integer. */ function _addBigIntegerToBuffer(buffer, val) { var hexVal = val.toString(16); // ensure 2s complement +ve if(hexVal[0] >= '8') { hexVal = '00' + hexVal; } var bytes = forge.util.hexToBytes(hexVal); buffer.putInt32(bytes.length); buffer.putBytes(bytes); } /** * Adds len(val) then val to a buffer. * * @param buffer the buffer to add to. * @param val a string. */ function _addStringToBuffer(buffer, val) { buffer.putInt32(val.length); buffer.putString(val); } /** * Hashes the arguments into one value using SHA-1. * * @return the sha1 hash of the provided arguments. */ function _sha1() { var sha = forge.md.sha1.create(); var num = arguments.length; for (var i = 0; i < num; ++i) { sha.update(arguments[i]); } return sha.digest(); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/pkcs7asn1.js
aws/lti-middleware/node_modules/node-forge/lib/pkcs7asn1.js
/** * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. * * @author Dave Longley * @author Stefan Siegl * * Copyright (c) 2012-2015 Digital Bazaar, Inc. * Copyright (c) 2012 Stefan Siegl <[email protected]> * * The ASN.1 representation of PKCS#7 is as follows * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): * * A PKCS#7 message consists of a ContentInfo on root level, which may * contain any number of further ContentInfo nested into it. * * ContentInfo ::= SEQUENCE { * contentType ContentType, * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL * } * * ContentType ::= OBJECT IDENTIFIER * * EnvelopedData ::= SEQUENCE { * version Version, * recipientInfos RecipientInfos, * encryptedContentInfo EncryptedContentInfo * } * * EncryptedData ::= SEQUENCE { * version Version, * encryptedContentInfo EncryptedContentInfo * } * * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } * * SignedData ::= SEQUENCE { * version INTEGER, * digestAlgorithms DigestAlgorithmIdentifiers, * contentInfo ContentInfo, * certificates [0] IMPLICIT Certificates OPTIONAL, * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, * signerInfos SignerInfos * } * * SignerInfos ::= SET OF SignerInfo * * SignerInfo ::= SEQUENCE { * version Version, * issuerAndSerialNumber IssuerAndSerialNumber, * digestAlgorithm DigestAlgorithmIdentifier, * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, * encryptedDigest EncryptedDigest, * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL * } * * EncryptedDigest ::= OCTET STRING * * Attributes ::= SET OF Attribute * * Attribute ::= SEQUENCE { * attrType OBJECT IDENTIFIER, * attrValues SET OF AttributeValue * } * * AttributeValue ::= ANY * * Version ::= INTEGER * * RecipientInfos ::= SET OF RecipientInfo * * EncryptedContentInfo ::= SEQUENCE { * contentType ContentType, * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL * } * * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier * * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters * for the algorithm, if any. In the case of AES and DES3, there is only one, * the IV. * * AlgorithmIdentifer ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * EncryptedContent ::= OCTET STRING * * RecipientInfo ::= SEQUENCE { * version Version, * issuerAndSerialNumber IssuerAndSerialNumber, * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, * encryptedKey EncryptedKey * } * * IssuerAndSerialNumber ::= SEQUENCE { * issuer Name, * serialNumber CertificateSerialNumber * } * * CertificateSerialNumber ::= INTEGER * * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier * * EncryptedKey ::= OCTET STRING */ var forge = require('./forge'); require('./asn1'); require('./util'); // shortcut for ASN.1 API var asn1 = forge.asn1; // shortcut for PKCS#7 API var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; forge.pkcs7 = forge.pkcs7 || {}; forge.pkcs7.asn1 = p7v; var contentInfoValidator = { name: 'ContentInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'ContentInfo.ContentType', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'contentType' }, { name: 'ContentInfo.content', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, constructed: true, optional: true, captureAsn1: 'content' }] }; p7v.contentInfoValidator = contentInfoValidator; var encryptedContentInfoValidator = { name: 'EncryptedContentInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'EncryptedContentInfo.contentType', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'contentType' }, { name: 'EncryptedContentInfo.contentEncryptionAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'encAlgorithm' }, { name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', tagClass: asn1.Class.UNIVERSAL, captureAsn1: 'encParameter' }] }, { name: 'EncryptedContentInfo.encryptedContent', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, /* The PKCS#7 structure output by OpenSSL somewhat differs from what * other implementations do generate. * * OpenSSL generates a structure like this: * SEQUENCE { * ... * [0] * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 * ... * } * * Whereas other implementations (and this PKCS#7 module) generate: * SEQUENCE { * ... * [0] { * OCTET STRING * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 * ... * } * } * * In order to support both, we just capture the context specific * field here. The OCTET STRING bit is removed below. */ capture: 'encryptedContent', captureAsn1: 'encryptedContentAsn1' }] }; p7v.envelopedDataValidator = { name: 'EnvelopedData', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'EnvelopedData.Version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'version' }, { name: 'EnvelopedData.RecipientInfos', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SET, constructed: true, captureAsn1: 'recipientInfos' }].concat(encryptedContentInfoValidator) }; p7v.encryptedDataValidator = { name: 'EncryptedData', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'EncryptedData.Version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'version' }].concat(encryptedContentInfoValidator) }; var signerValidator = { name: 'SignerInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'SignerInfo.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false }, { name: 'SignerInfo.issuerAndSerialNumber', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'SignerInfo.issuerAndSerialNumber.issuer', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'issuer' }, { name: 'SignerInfo.issuerAndSerialNumber.serialNumber', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'serial' }] }, { name: 'SignerInfo.digestAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'SignerInfo.digestAlgorithm.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'digestAlgorithm' }, { name: 'SignerInfo.digestAlgorithm.parameter', tagClass: asn1.Class.UNIVERSAL, constructed: false, captureAsn1: 'digestParameter', optional: true }] }, { name: 'SignerInfo.authenticatedAttributes', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, constructed: true, optional: true, capture: 'authenticatedAttributes' }, { name: 'SignerInfo.digestEncryptionAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, capture: 'signatureAlgorithm' }, { name: 'SignerInfo.encryptedDigest', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'signature' }, { name: 'SignerInfo.unauthenticatedAttributes', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 1, constructed: true, optional: true, capture: 'unauthenticatedAttributes' }] }; p7v.signedDataValidator = { name: 'SignedData', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'SignedData.Version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'version' }, { name: 'SignedData.DigestAlgorithms', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SET, constructed: true, captureAsn1: 'digestAlgorithms' }, contentInfoValidator, { name: 'SignedData.Certificates', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, optional: true, captureAsn1: 'certificates' }, { name: 'SignedData.CertificateRevocationLists', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 1, optional: true, captureAsn1: 'crls' }, { name: 'SignedData.SignerInfos', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SET, capture: 'signerInfos', optional: true, value: [signerValidator] }] }; p7v.recipientInfoValidator = { name: 'RecipientInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'RecipientInfo.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'version' }, { name: 'RecipientInfo.issuerAndSerial', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'RecipientInfo.issuerAndSerial.issuer', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'issuer' }, { name: 'RecipientInfo.issuerAndSerial.serialNumber', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'serial' }] }, { name: 'RecipientInfo.keyEncryptionAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'encAlgorithm' }, { name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', tagClass: asn1.Class.UNIVERSAL, constructed: false, captureAsn1: 'encParameter', optional: true }] }, { name: 'RecipientInfo.encryptedKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'encKey' }] };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/pkcs1.js
aws/lti-middleware/node_modules/node-forge/lib/pkcs1.js
/** * Partial implementation of PKCS#1 v2.2: RSA-OEAP * * Modified but based on the following MIT and BSD licensed code: * * https://github.com/kjur/jsjws/blob/master/rsa.js: * * The 'jsjws'(JSON Web Signature JavaScript Library) License * * Copyright (c) 2012 Kenji Urushima * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: * * RSAES-OAEP.js * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. * Contact: [email protected] * Distributed under the BSD License. * * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 * * @author Evan Jones (http://evanjones.ca/) * @author Dave Longley * * Copyright (c) 2013-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); require('./random'); require('./sha1'); // shortcut for PKCS#1 API var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {}; /** * Encode the given RSAES-OAEP message (M) using key, with optional label (L) * and seed. * * This method does not perform RSA encryption, it only encodes the message * using RSAES-OAEP. * * @param key the RSA key to use. * @param message the message to encode. * @param options the options to use: * label an optional label to use. * seed the seed to use. * md the message digest object to use, undefined for SHA-1. * mgf1 optional mgf1 parameters: * md the message digest object to use for MGF1. * * @return the encoded message bytes. */ pkcs1.encode_rsa_oaep = function(key, message, options) { // parse arguments var label; var seed; var md; var mgf1Md; // legacy args (label, seed, md) if(typeof options === 'string') { label = options; seed = arguments[3] || undefined; md = arguments[4] || undefined; } else if(options) { label = options.label || undefined; seed = options.seed || undefined; md = options.md || undefined; if(options.mgf1 && options.mgf1.md) { mgf1Md = options.mgf1.md; } } // default OAEP to SHA-1 message digest if(!md) { md = forge.md.sha1.create(); } else { md.start(); } // default MGF-1 to same as OAEP if(!mgf1Md) { mgf1Md = md; } // compute length in bytes and check output var keyLength = Math.ceil(key.n.bitLength() / 8); var maxLength = keyLength - 2 * md.digestLength - 2; if(message.length > maxLength) { var error = new Error('RSAES-OAEP input message length is too long.'); error.length = message.length; error.maxLength = maxLength; throw error; } if(!label) { label = ''; } md.update(label, 'raw'); var lHash = md.digest(); var PS = ''; var PS_length = maxLength - message.length; for(var i = 0; i < PS_length; i++) { PS += '\x00'; } var DB = lHash.getBytes() + PS + '\x01' + message; if(!seed) { seed = forge.random.getBytes(md.digestLength); } else if(seed.length !== md.digestLength) { var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + 'match the digest length.'); error.seedLength = seed.length; error.digestLength = md.digestLength; throw error; } var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); // return encoded message return '\x00' + maskedSeed + maskedDB; }; /** * Decode the given RSAES-OAEP encoded message (EM) using key, with optional * label (L). * * This method does not perform RSA decryption, it only decodes the message * using RSAES-OAEP. * * @param key the RSA key to use. * @param em the encoded message to decode. * @param options the options to use: * label an optional label to use. * md the message digest object to use for OAEP, undefined for SHA-1. * mgf1 optional mgf1 parameters: * md the message digest object to use for MGF1. * * @return the decoded message bytes. */ pkcs1.decode_rsa_oaep = function(key, em, options) { // parse args var label; var md; var mgf1Md; // legacy args if(typeof options === 'string') { label = options; md = arguments[3] || undefined; } else if(options) { label = options.label || undefined; md = options.md || undefined; if(options.mgf1 && options.mgf1.md) { mgf1Md = options.mgf1.md; } } // compute length in bytes var keyLength = Math.ceil(key.n.bitLength() / 8); if(em.length !== keyLength) { var error = new Error('RSAES-OAEP encoded message length is invalid.'); error.length = em.length; error.expectedLength = keyLength; throw error; } // default OAEP to SHA-1 message digest if(md === undefined) { md = forge.md.sha1.create(); } else { md.start(); } // default MGF-1 to same as OAEP if(!mgf1Md) { mgf1Md = md; } if(keyLength < 2 * md.digestLength + 2) { throw new Error('RSAES-OAEP key is too short for the hash function.'); } if(!label) { label = ''; } md.update(label, 'raw'); var lHash = md.digest().getBytes(); // split the message into its parts var y = em.charAt(0); var maskedSeed = em.substring(1, md.digestLength + 1); var maskedDB = em.substring(1 + md.digestLength); var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); var lHashPrime = db.substring(0, md.digestLength); // constant time check that all values match what is expected var error = (y !== '\x00'); // constant time check lHash vs lHashPrime for(var i = 0; i < md.digestLength; ++i) { error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); } // "constant time" find the 0x1 byte separating the padding (zeros) from the // message // TODO: It must be possible to do this in a better/smarter way? var in_ps = 1; var index = md.digestLength; for(var j = md.digestLength; j < db.length; j++) { var code = db.charCodeAt(j); var is_0 = (code & 0x1) ^ 0x1; // non-zero if not 0 or 1 in the ps section var error_mask = in_ps ? 0xfffe : 0x0000; error |= (code & error_mask); // latch in_ps to zero after we find 0x1 in_ps = in_ps & is_0; index += in_ps; } if(error || db.charCodeAt(index) !== 0x1) { throw new Error('Invalid RSAES-OAEP padding.'); } return db.substring(index + 1); }; function rsa_mgf1(seed, maskLength, hash) { // default to SHA-1 message digest if(!hash) { hash = forge.md.sha1.create(); } var t = ''; var count = Math.ceil(maskLength / hash.digestLength); for(var i = 0; i < count; ++i) { var c = String.fromCharCode( (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); hash.start(); hash.update(seed + c); t += hash.digest().getBytes(); } return t.substring(0, maskLength); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/cipher.js
aws/lti-middleware/node_modules/node-forge/lib/cipher.js
/** * Cipher base API. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); module.exports = forge.cipher = forge.cipher || {}; // registered algorithms forge.cipher.algorithms = forge.cipher.algorithms || {}; /** * Creates a cipher object that can be used to encrypt data using the given * algorithm and key. The algorithm may be provided as a string value for a * previously registered algorithm or it may be given as a cipher algorithm * API object. * * @param algorithm the algorithm to use, either a string or an algorithm API * object. * @param key the key to use, as a binary-encoded string of bytes or a * byte buffer. * * @return the cipher. */ forge.cipher.createCipher = function(algorithm, key) { var api = algorithm; if(typeof api === 'string') { api = forge.cipher.getAlgorithm(api); if(api) { api = api(); } } if(!api) { throw new Error('Unsupported algorithm: ' + algorithm); } // assume block cipher return new forge.cipher.BlockCipher({ algorithm: api, key: key, decrypt: false }); }; /** * Creates a decipher object that can be used to decrypt data using the given * algorithm and key. The algorithm may be provided as a string value for a * previously registered algorithm or it may be given as a cipher algorithm * API object. * * @param algorithm the algorithm to use, either a string or an algorithm API * object. * @param key the key to use, as a binary-encoded string of bytes or a * byte buffer. * * @return the cipher. */ forge.cipher.createDecipher = function(algorithm, key) { var api = algorithm; if(typeof api === 'string') { api = forge.cipher.getAlgorithm(api); if(api) { api = api(); } } if(!api) { throw new Error('Unsupported algorithm: ' + algorithm); } // assume block cipher return new forge.cipher.BlockCipher({ algorithm: api, key: key, decrypt: true }); }; /** * Registers an algorithm by name. If the name was already registered, the * algorithm API object will be overwritten. * * @param name the name of the algorithm. * @param algorithm the algorithm API object. */ forge.cipher.registerAlgorithm = function(name, algorithm) { name = name.toUpperCase(); forge.cipher.algorithms[name] = algorithm; }; /** * Gets a registered algorithm by name. * * @param name the name of the algorithm. * * @return the algorithm, if found, null if not. */ forge.cipher.getAlgorithm = function(name) { name = name.toUpperCase(); if(name in forge.cipher.algorithms) { return forge.cipher.algorithms[name]; } return null; }; var BlockCipher = forge.cipher.BlockCipher = function(options) { this.algorithm = options.algorithm; this.mode = this.algorithm.mode; this.blockSize = this.mode.blockSize; this._finish = false; this._input = null; this.output = null; this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; this._decrypt = options.decrypt; this.algorithm.initialize(options); }; /** * Starts or restarts the encryption or decryption process, whichever * was previously configured. * * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in * bytes, then it must be Nb (16) bytes in length. If the IV is given in as * 32-bit integers, then it must be 4 integers long. * * Note: an IV is not required or used in ECB mode. * * For GCM-mode, the IV must be given as a binary-encoded string of bytes or * a byte buffer. The number of bytes should be 12 (96 bits) as recommended * by NIST SP-800-38D but another length may be given. * * @param options the options to use: * iv the initialization vector to use as a binary-encoded string of * bytes, null to reuse the last ciphered block from a previous * update() (this "residue" method is for legacy support only). * additionalData additional authentication data as a binary-encoded * string of bytes, for 'GCM' mode, (default: none). * tagLength desired length of authentication tag, in bits, for * 'GCM' mode (0-128, default: 128). * tag the authentication tag to check if decrypting, as a * binary-encoded string of bytes. * output the output the buffer to write to, null to create one. */ BlockCipher.prototype.start = function(options) { options = options || {}; var opts = {}; for(var key in options) { opts[key] = options[key]; } opts.decrypt = this._decrypt; this._finish = false; this._input = forge.util.createBuffer(); this.output = options.output || forge.util.createBuffer(); this.mode.start(opts); }; /** * Updates the next block according to the cipher mode. * * @param input the buffer to read from. */ BlockCipher.prototype.update = function(input) { if(input) { // input given, so empty it into the input buffer this._input.putBuffer(input); } // do cipher operation until it needs more input and not finished while(!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) {} // free consumed memory from input buffer this._input.compact(); }; /** * Finishes encrypting or decrypting. * * @param pad a padding function to use in CBC mode, null for default, * signature(blockSize, buffer, decrypt). * * @return true if successful, false on error. */ BlockCipher.prototype.finish = function(pad) { // backwards-compatibility w/deprecated padding API // Note: will overwrite padding functions even after another start() call if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { this.mode.pad = function(input) { return pad(this.blockSize, input, false); }; this.mode.unpad = function(output) { return pad(this.blockSize, output, true); }; } // build options for padding and afterFinish functions var options = {}; options.decrypt = this._decrypt; // get # of bytes that won't fill a block options.overflow = this._input.length() % this.blockSize; if(!this._decrypt && this.mode.pad) { if(!this.mode.pad(this._input, options)) { return false; } } // do final update this._finish = true; this.update(); if(this._decrypt && this.mode.unpad) { if(!this.mode.unpad(this.output, options)) { return false; } } if(this.mode.afterFinish) { if(!this.mode.afterFinish(this.output, options)) { return false; } } return 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/node-forge/lib/sha512.js
aws/lti-middleware/node_modules/node-forge/lib/sha512.js
/** * Secure Hash Algorithm with a 1024-bit block size implementation. * * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For * SHA-256 (block size 512 bits), see sha256.js. * * See FIPS 180-4 for details. * * @author Dave Longley * * Copyright (c) 2014-2015 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./md'); require('./util'); var sha512 = module.exports = forge.sha512 = forge.sha512 || {}; // SHA-512 forge.md.sha512 = forge.md.algorithms.sha512 = sha512; // SHA-384 var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; sha384.create = function() { return sha512.create('SHA-384'); }; forge.md.sha384 = forge.md.algorithms.sha384 = sha384; // SHA-512/256 forge.sha512.sha256 = forge.sha512.sha256 || { create: function() { return sha512.create('SHA-512/256'); } }; forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = forge.sha512.sha256; // SHA-512/224 forge.sha512.sha224 = forge.sha512.sha224 || { create: function() { return sha512.create('SHA-512/224'); } }; forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = forge.sha512.sha224; /** * Creates a SHA-2 message digest object. * * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, * SHA-512/256). * * @return a message digest object. */ sha512.create = function(algorithm) { // do initialization as necessary if(!_initialized) { _init(); } if(typeof algorithm === 'undefined') { algorithm = 'SHA-512'; } if(!(algorithm in _states)) { throw new Error('Invalid SHA-512 algorithm: ' + algorithm); } // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) var _state = _states[algorithm]; var _h = null; // input buffer var _input = forge.util.createBuffer(); // used for 64-bit word storage var _w = new Array(80); for(var wi = 0; wi < 80; ++wi) { _w[wi] = new Array(2); } // determine digest length by algorithm name (default) var digestLength = 64; switch(algorithm) { case 'SHA-384': digestLength = 48; break; case 'SHA-512/256': digestLength = 32; break; case 'SHA-512/224': digestLength = 28; break; } // message digest object var md = { // SHA-512 => sha512 algorithm: algorithm.replace('-', '').toLowerCase(), blockLength: 128, digestLength: digestLength, // 56-bit length of message so far (does not including padding) messageLength: 0, // true message length fullMessageLength: null, // size of message length in bytes messageLengthSize: 16 }; /** * Starts the digest. * * @return this digest object. */ md.start = function() { // up to 56-bit message length for convenience md.messageLength = 0; // full message length (set md.messageLength128 for backwards-compatibility) md.fullMessageLength = md.messageLength128 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _h = new Array(_state.length); for(var i = 0; i < _state.length; ++i) { _h[i] = _state[i].slice(0); } return md; }; // start digest automatically for first time md.start(); /** * Updates the digest with the given message input. The given input can * treated as raw input (no encoding will be applied) or an encoding of * 'utf8' maybe given to encode the input using UTF-8. * * @param msg the message input to update with. * @param encoding the encoding to use (default: 'raw', other: 'utf8'). * * @return this digest object. */ md.update = function(msg, encoding) { if(encoding === 'utf8') { msg = forge.util.encodeUtf8(msg); } // update message length var len = msg.length; md.messageLength += len; len = [(len / 0x100000000) >>> 0, len >>> 0]; for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { md.fullMessageLength[i] += len[1]; len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; len[0] = ((len[1] / 0x100000000) >>> 0); } // add bytes to input buffer _input.putBytes(msg); // process bytes _update(_h, _w, _input); // compact input buffer every 2K or if empty if(_input.read > 2048 || _input.length() === 0) { _input.compact(); } return md; }; /** * Produces the digest. * * @return a byte buffer containing the digest value. */ md.digest = function() { /* Note: Here we copy the remaining bytes in the input buffer and add the appropriate SHA-512 padding. Then we do the final update on a copy of the state so that if the user wants to get intermediate digests they can do so. */ /* Determine the number of bytes that must be added to the message to ensure its length is congruent to 896 mod 1024. In other words, the data to be digested must be a multiple of 1024 bits (or 128 bytes). This data includes the message, some padding, and the length of the message. Since the length of the message will be encoded as 16 bytes (128 bits), that means that the last segment of the data must have 112 bytes (896 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 896 mod 1024 because 1024 - 128 = 896. In order to fill up the message length it must be filled with padding that begins with 1 bit followed by all 0 bits. Padding must *always* be present, so if the message length is already congruent to 896 mod 1024, then 1024 padding bits must be added. */ var finalBlock = forge.util.createBuffer(); finalBlock.putBytes(_input.bytes()); // compute remaining size to be digested (include message length size) var remaining = ( md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize); // add padding for overflow blockSize - overflow // _padding starts with 1 byte with first bit is set (byte value 128), then // there may be up to (blockSize - 1) other pad bytes var overflow = remaining & (md.blockLength - 1); finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); // serialize message length in bits in big-endian order; since length // is stored in bytes we multiply by 8 and add carry from next int var next, carry; var bits = md.fullMessageLength[0] * 8; for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { next = md.fullMessageLength[i + 1] * 8; carry = (next / 0x100000000) >>> 0; bits += carry; finalBlock.putInt32(bits >>> 0); bits = next >>> 0; } finalBlock.putInt32(bits); var h = new Array(_h.length); for(var i = 0; i < _h.length; ++i) { h[i] = _h[i].slice(0); } _update(h, _w, finalBlock); var rval = forge.util.createBuffer(); var hlen; if(algorithm === 'SHA-512') { hlen = h.length; } else if(algorithm === 'SHA-384') { hlen = h.length - 2; } else { hlen = h.length - 4; } for(var i = 0; i < hlen; ++i) { rval.putInt32(h[i][0]); if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { rval.putInt32(h[i][1]); } } return rval; }; return md; }; // sha-512 padding bytes not initialized yet var _padding = null; var _initialized = false; // table of constants var _k = null; // initial hash states var _states = null; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 128); // create K table for SHA-512 _k = [ [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] ]; // initial hash states _states = {}; _states['SHA-512'] = [ [0x6a09e667, 0xf3bcc908], [0xbb67ae85, 0x84caa73b], [0x3c6ef372, 0xfe94f82b], [0xa54ff53a, 0x5f1d36f1], [0x510e527f, 0xade682d1], [0x9b05688c, 0x2b3e6c1f], [0x1f83d9ab, 0xfb41bd6b], [0x5be0cd19, 0x137e2179] ]; _states['SHA-384'] = [ [0xcbbb9d5d, 0xc1059ed8], [0x629a292a, 0x367cd507], [0x9159015a, 0x3070dd17], [0x152fecd8, 0xf70e5939], [0x67332667, 0xffc00b31], [0x8eb44a87, 0x68581511], [0xdb0c2e0d, 0x64f98fa7], [0x47b5481d, 0xbefa4fa4] ]; _states['SHA-512/256'] = [ [0x22312194, 0xFC2BF72C], [0x9F555FA3, 0xC84C64C2], [0x2393B86B, 0x6F53B151], [0x96387719, 0x5940EABD], [0x96283EE2, 0xA88EFFE3], [0xBE5E1E25, 0x53863992], [0x2B0199FC, 0x2C85B8AA], [0x0EB72DDC, 0x81C52CA2] ]; _states['SHA-512/224'] = [ [0x8C3D37C8, 0x19544DA2], [0x73E19966, 0x89DCD4D6], [0x1DFAB7AE, 0x32FF9C82], [0x679DD514, 0x582F9FCF], [0x0F6D2B69, 0x7BD44DA8], [0x77E36F73, 0x04C48942], [0x3F9D85A8, 0x6A1D36C8], [0x1112E6AD, 0x91D692A1] ]; // now initialized _initialized = true; } /** * Updates a SHA-512 state with the given byte buffer. * * @param s the SHA-512 state to update. * @param w the array to use to store words. * @param bytes the byte buffer to update with. */ function _update(s, w, bytes) { // consume 512 bit (128 byte) chunks var t1_hi, t1_lo; var t2_hi, t2_lo; var s0_hi, s0_lo; var s1_hi, s1_lo; var ch_hi, ch_lo; var maj_hi, maj_lo; var a_hi, a_lo; var b_hi, b_lo; var c_hi, c_lo; var d_hi, d_lo; var e_hi, e_lo; var f_hi, f_lo; var g_hi, g_lo; var h_hi, h_lo; var i, hi, lo, w2, w7, w15, w16; var len = bytes.length(); while(len >= 128) { // the w array will be populated with sixteen 64-bit big-endian words // and then extended into 64 64-bit words according to SHA-512 for(i = 0; i < 16; ++i) { w[i][0] = bytes.getInt32() >>> 0; w[i][1] = bytes.getInt32() >>> 0; } for(; i < 80; ++i) { // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) w2 = w[i - 2]; hi = w2[0]; lo = w2[1]; // high bits t1_hi = ( ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) (hi >>> 6)) >>> 0; // SHR 6 // low bits t1_lo = ( ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) w15 = w[i - 15]; hi = w15[0]; lo = w15[1]; // high bits t2_hi = ( ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 (hi >>> 7)) >>> 0; // SHR 7 // low bits t2_lo = ( ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) w7 = w[i - 7]; w16 = w[i - 16]; lo = (t1_lo + w7[1] + t2_lo + w16[1]); w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + ((lo / 0x100000000) >>> 0)) >>> 0; w[i][1] = lo >>> 0; } // initialize hash value for this chunk a_hi = s[0][0]; a_lo = s[0][1]; b_hi = s[1][0]; b_lo = s[1][1]; c_hi = s[2][0]; c_lo = s[2][1]; d_hi = s[3][0]; d_lo = s[3][1]; e_hi = s[4][0]; e_lo = s[4][1]; f_hi = s[5][0]; f_lo = s[5][1]; g_hi = s[6][0]; g_lo = s[6][1]; h_hi = s[7][0]; h_lo = s[7][1]; // round function for(i = 0; i < 80; ++i) { // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) s1_hi = ( ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) s1_lo = ( ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) // Ch(e, f, g) (optimized the same way as SHA-1) ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) s0_hi = ( ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) s0_lo = ( ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) // Maj(a, b, c) (optimized the same way as SHA-1) maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; // main algorithm // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + ((lo / 0x100000000) >>> 0)) >>> 0; t1_lo = lo >>> 0; // t2 = s0 + maj modulo 2^64 (carry lo overflow) lo = s0_lo + maj_lo; t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; t2_lo = lo >>> 0; h_hi = g_hi; h_lo = g_lo; g_hi = f_hi; g_lo = f_lo; f_hi = e_hi; f_lo = e_lo; // e = (d + t1) modulo 2^64 (carry lo overflow) lo = d_lo + t1_lo; e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; e_lo = lo >>> 0; d_hi = c_hi; d_lo = c_lo; c_hi = b_hi; c_lo = b_lo; b_hi = a_hi; b_lo = a_lo; // a = (t1 + t2) modulo 2^64 (carry lo overflow) lo = t1_lo + t2_lo; a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; a_lo = lo >>> 0; } // update hash state (additional modulo 2^64) lo = s[0][1] + a_lo; s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[0][1] = lo >>> 0; lo = s[1][1] + b_lo; s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[1][1] = lo >>> 0; lo = s[2][1] + c_lo; s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[2][1] = lo >>> 0; lo = s[3][1] + d_lo; s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[3][1] = lo >>> 0; lo = s[4][1] + e_lo; s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[4][1] = lo >>> 0; lo = s[5][1] + f_lo; s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[5][1] = lo >>> 0; lo = s[6][1] + g_lo; s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[6][1] = lo >>> 0; lo = s[7][1] + h_lo; s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; s[7][1] = lo >>> 0; len -= 128; } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/forge.js
aws/lti-middleware/node_modules/node-forge/lib/forge.js
/** * Node.js module for Forge. * * @author Dave Longley * * Copyright 2011-2016 Digital Bazaar, Inc. */ module.exports = { // default options options: { usePureJavaScript: false } };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/form.js
aws/lti-middleware/node_modules/node-forge/lib/form.js
/** * Functions for manipulating web forms. * * @author David I. Lehn <[email protected]> * @author Dave Longley * @author Mike Johnson * * Copyright (c) 2011-2014 Digital Bazaar, Inc. All rights reserved. */ var forge = require('./forge'); /* Form API */ var form = module.exports = forge.form = forge.form || {}; (function($) { /** * Regex for parsing a single name property (handles array brackets). */ var _regex = /([^\[]*?)\[(.*?)\]/g; /** * Parses a single name property into an array with the name and any * array indices. * * @param name the name to parse. * * @return the array of the name and its array indices in order. */ var _parseName = function(name) { var rval = []; var matches; while(!!(matches = _regex.exec(name))) { if(matches[1].length > 0) { rval.push(matches[1]); } if(matches.length >= 2) { rval.push(matches[2]); } } if(rval.length === 0) { rval.push(name); } return rval; }; /** * Adds a field from the given form to the given object. * * @param obj the object. * @param names the field as an array of object property names. * @param value the value of the field. * @param dict a dictionary of names to replace. */ var _addField = function(obj, names, value, dict) { // combine array names that fall within square brackets var tmp = []; for(var i = 0; i < names.length; ++i) { // check name for starting square bracket but no ending one var name = names[i]; if(name.indexOf('[') !== -1 && name.indexOf(']') === -1 && i < names.length - 1) { do { name += '.' + names[++i]; } while(i < names.length - 1 && names[i].indexOf(']') === -1); } tmp.push(name); } names = tmp; // split out array indexes var tmp = []; $.each(names, function(n, name) { tmp = tmp.concat(_parseName(name)); }); names = tmp; // iterate over object property names until value is set $.each(names, function(n, name) { // do dictionary name replacement if(dict && name.length !== 0 && name in dict) { name = dict[name]; } // blank name indicates appending to an array, set name to // new last index of array if(name.length === 0) { name = obj.length; } // value already exists, append value if(obj[name]) { // last name in the field if(n == names.length - 1) { // more than one value, so convert into an array if(!$.isArray(obj[name])) { obj[name] = [obj[name]]; } obj[name].push(value); } else { // not last name, go deeper into object obj = obj[name]; } } else if(n == names.length - 1) { // new value, last name in the field, set value obj[name] = value; } else { // new value, not last name, go deeper // get next name var next = names[n + 1]; // blank next value indicates array-appending, so create array if(next.length === 0) { obj[name] = []; } else { // if next name is a number create an array, otherwise a map var isNum = ((next - 0) == next && next.length > 0); obj[name] = isNum ? [] : {}; } obj = obj[name]; } }); }; /** * Serializes a form to a JSON object. Object properties will be separated * using the given separator (defaults to '.') and by square brackets. * * @param input the jquery form to serialize. * @param sep the object-property separator (defaults to '.'). * @param dict a dictionary of names to replace (name=replace). * * @return the JSON-serialized form. */ form.serialize = function(input, sep, dict) { var rval = {}; // add all fields in the form to the object sep = sep || '.'; $.each(input.serializeArray(), function() { _addField(rval, this.name.split(sep), this.value || '', dict); }); return rval; }; })(jQuery);
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/md5.js
aws/lti-middleware/node_modules/node-forge/lib/md5.js
/** * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./md'); require('./util'); var md5 = module.exports = forge.md5 = forge.md5 || {}; forge.md.md5 = forge.md.algorithms.md5 = md5; /** * Creates an MD5 message digest object. * * @return a message digest object. */ md5.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // MD5 state contains four 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(16); // message digest object var md = { algorithm: 'md5', blockLength: 64, digestLength: 16, // 56-bit length of message so far (does not including padding) messageLength: 0, // true message length fullMessageLength: null, // size of message length in bytes messageLengthSize: 8 }; /** * Starts the digest. * * @return this digest object. */ md.start = function() { // up to 56-bit message length for convenience md.messageLength = 0; // full message length (set md.messageLength64 for backwards-compatibility) md.fullMessageLength = md.messageLength64 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _state = { h0: 0x67452301, h1: 0xEFCDAB89, h2: 0x98BADCFE, h3: 0x10325476 }; return md; }; // start digest automatically for first time md.start(); /** * Updates the digest with the given message input. The given input can * treated as raw input (no encoding will be applied) or an encoding of * 'utf8' maybe given to encode the input using UTF-8. * * @param msg the message input to update with. * @param encoding the encoding to use (default: 'raw', other: 'utf8'). * * @return this digest object. */ md.update = function(msg, encoding) { if(encoding === 'utf8') { msg = forge.util.encodeUtf8(msg); } // update message length var len = msg.length; md.messageLength += len; len = [(len / 0x100000000) >>> 0, len >>> 0]; for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { md.fullMessageLength[i] += len[1]; len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; len[0] = (len[1] / 0x100000000) >>> 0; } // add bytes to input buffer _input.putBytes(msg); // process bytes _update(_state, _w, _input); // compact input buffer every 2K or if empty if(_input.read > 2048 || _input.length() === 0) { _input.compact(); } return md; }; /** * Produces the digest. * * @return a byte buffer containing the digest value. */ md.digest = function() { /* Note: Here we copy the remaining bytes in the input buffer and add the appropriate MD5 padding. Then we do the final update on a copy of the state so that if the user wants to get intermediate digests they can do so. */ /* Determine the number of bytes that must be added to the message to ensure its length is congruent to 448 mod 512. In other words, the data to be digested must be a multiple of 512 bits (or 128 bytes). This data includes the message, some padding, and the length of the message. Since the length of the message will be encoded as 8 bytes (64 bits), that means that the last segment of the data must have 56 bytes (448 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 448 mod 512 because 512 - 128 = 448. In order to fill up the message length it must be filled with padding that begins with 1 bit followed by all 0 bits. Padding must *always* be present, so if the message length is already congruent to 448 mod 512, then 512 padding bits must be added. */ var finalBlock = forge.util.createBuffer(); finalBlock.putBytes(_input.bytes()); // compute remaining size to be digested (include message length size) var remaining = ( md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize); // add padding for overflow blockSize - overflow // _padding starts with 1 byte with first bit is set (byte value 128), then // there may be up to (blockSize - 1) other pad bytes var overflow = remaining & (md.blockLength - 1); finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); // serialize message length in bits in little-endian order; since length // is stored in bytes we multiply by 8 and add carry var bits, carry = 0; for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { bits = md.fullMessageLength[i] * 8 + carry; carry = (bits / 0x100000000) >>> 0; finalBlock.putInt32Le(bits >>> 0); } var s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32Le(s2.h0); rval.putInt32Le(s2.h1); rval.putInt32Le(s2.h2); rval.putInt32Le(s2.h3); return rval; }; return md; }; // padding, constant tables for calculating md5 var _padding = null; var _g = null; var _r = null; var _k = null; var _initialized = false; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // g values _g = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; // rounds table _r = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; // get the result of abs(sin(i + 1)) as a 32-bit integer _k = new Array(64); for(var i = 0; i < 64; ++i) { _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); } // now initialized _initialized = true; } /** * Updates an MD5 state with the given byte buffer. * * @param s the MD5 state to update. * @param w the array to use to store words. * @param bytes the byte buffer to update with. */ function _update(s, w, bytes) { // consume 512 bit (64 byte) chunks var t, a, b, c, d, f, r, i; var len = bytes.length(); while(len >= 64) { // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; // round 1 for(i = 0; i < 16; ++i) { w[i] = bytes.getInt32Le(); f = d ^ (b & (c ^ d)); t = (a + f + _k[i] + w[i]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // round 2 for(; i < 32; ++i) { f = c ^ (d & (b ^ c)); t = (a + f + _k[i] + w[_g[i]]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // round 3 for(; i < 48; ++i) { f = b ^ c ^ d; t = (a + f + _k[i] + w[_g[i]]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // round 4 for(; i < 64; ++i) { f = c ^ (b | ~d); t = (a + f + _k[i] + w[_g[i]]); r = _r[i]; a = d; d = c; c = b; b += (t << r) | (t >>> (32 - r)); } // update hash state s.h0 = (s.h0 + a) | 0; s.h1 = (s.h1 + b) | 0; s.h2 = (s.h2 + c) | 0; s.h3 = (s.h3 + d) | 0; len -= 64; } }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/rc2.js
aws/lti-middleware/node_modules/node-forge/lib/rc2.js
/** * RC2 implementation. * * @author Stefan Siegl * * Copyright (c) 2012 Stefan Siegl <[email protected]> * * Information on the RC2 cipher is available from RFC #2268, * http://www.ietf.org/rfc/rfc2268.txt */ var forge = require('./forge'); require('./util'); var piTable = [ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad ]; var s = [1, 2, 3, 5]; /** * Rotate a word left by given number of bits. * * Bits that are shifted out on the left are put back in on the right * hand side. * * @param word The word to shift left. * @param bits The number of bits to shift by. * @return The rotated word. */ var rol = function(word, bits) { return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); }; /** * Rotate a word right by given number of bits. * * Bits that are shifted out on the right are put back in on the left * hand side. * * @param word The word to shift right. * @param bits The number of bits to shift by. * @return The rotated word. */ var ror = function(word, bits) { return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); }; /* RC2 API */ module.exports = forge.rc2 = forge.rc2 || {}; /** * Perform RC2 key expansion as per RFC #2268, section 2. * * @param key variable-length user key (between 1 and 128 bytes) * @param effKeyBits number of effective key bits (default: 128) * @return the expanded RC2 key (ByteBuffer of 128 bytes) */ forge.rc2.expandKey = function(key, effKeyBits) { if(typeof key === 'string') { key = forge.util.createBuffer(key); } effKeyBits = effKeyBits || 128; /* introduce variables that match the names used in RFC #2268 */ var L = key; var T = key.length(); var T1 = effKeyBits; var T8 = Math.ceil(T1 / 8); var TM = 0xff >> (T1 & 0x07); var i; for(i = T; i < 128; i++) { L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); } L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); for(i = 127 - T8; i >= 0; i--) { L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); } return L; }; /** * Creates a RC2 cipher object. * * @param key the symmetric key to use (as base for key generation). * @param bits the number of effective key bits. * @param encrypt false for decryption, true for encryption. * * @return the cipher. */ var createCipher = function(key, bits, encrypt) { var _finish = false, _input = null, _output = null, _iv = null; var mixRound, mashRound; var i, j, K = []; /* Expand key and fill into K[] Array */ key = forge.rc2.expandKey(key, bits); for(i = 0; i < 64; i++) { K.push(key.getInt16Le()); } if(encrypt) { /** * Perform one mixing round "in place". * * @param R Array of four words to perform mixing on. */ mixRound = function(R) { for(i = 0; i < 4; i++) { R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); R[i] = rol(R[i], s[i]); j++; } }; /** * Perform one mashing round "in place". * * @param R Array of four words to perform mashing on. */ mashRound = function(R) { for(i = 0; i < 4; i++) { R[i] += K[R[(i + 3) % 4] & 63]; } }; } else { /** * Perform one r-mixing round "in place". * * @param R Array of four words to perform mixing on. */ mixRound = function(R) { for(i = 3; i >= 0; i--) { R[i] = ror(R[i], s[i]); R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); j--; } }; /** * Perform one r-mashing round "in place". * * @param R Array of four words to perform mashing on. */ mashRound = function(R) { for(i = 3; i >= 0; i--) { R[i] -= K[R[(i + 3) % 4] & 63]; } }; } /** * Run the specified cipher execution plan. * * This function takes four words from the input buffer, applies the IV on * it (if requested) and runs the provided execution plan. * * The plan must be put together in form of a array of arrays. Where the * outer one is simply a list of steps to perform and the inner one needs * to have two elements: the first one telling how many rounds to perform, * the second one telling what to do (i.e. the function to call). * * @param {Array} plan The plan to execute. */ var runPlan = function(plan) { var R = []; /* Get data from input buffer and fill the four words into R */ for(i = 0; i < 4; i++) { var val = _input.getInt16Le(); if(_iv !== null) { if(encrypt) { /* We're encrypting, apply the IV first. */ val ^= _iv.getInt16Le(); } else { /* We're decryption, keep cipher text for next block. */ _iv.putInt16Le(val); } } R.push(val & 0xffff); } /* Reset global "j" variable as per spec. */ j = encrypt ? 0 : 63; /* Run execution plan. */ for(var ptr = 0; ptr < plan.length; ptr++) { for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { plan[ptr][1](R); } } /* Write back result to output buffer. */ for(i = 0; i < 4; i++) { if(_iv !== null) { if(encrypt) { /* We're encrypting in CBC-mode, feed back encrypted bytes into IV buffer to carry it forward to next block. */ _iv.putInt16Le(R[i]); } else { R[i] ^= _iv.getInt16Le(); } } _output.putInt16Le(R[i]); } }; /* Create cipher object */ var cipher = null; cipher = { /** * Starts or restarts the encryption or decryption process, whichever * was previously configured. * * To use the cipher in CBC mode, iv may be given either as a string * of bytes, or as a byte buffer. For ECB mode, give null as iv. * * @param iv the initialization vector to use, null for ECB mode. * @param output the output the buffer to write to, null to create one. */ start: function(iv, output) { if(iv) { /* CBC mode */ if(typeof iv === 'string') { iv = forge.util.createBuffer(iv); } } _finish = false; _input = forge.util.createBuffer(); _output = output || new forge.util.createBuffer(); _iv = iv; cipher.output = _output; }, /** * Updates the next block. * * @param input the buffer to read from. */ update: function(input) { if(!_finish) { // not finishing, so fill the input buffer with more input _input.putBuffer(input); } while(_input.length() >= 8) { runPlan([ [ 5, mixRound ], [ 1, mashRound ], [ 6, mixRound ], [ 1, mashRound ], [ 5, mixRound ] ]); } }, /** * Finishes encrypting or decrypting. * * @param pad a padding function to use, null for PKCS#7 padding, * signature(blockSize, buffer, decrypt). * * @return true if successful, false on error. */ finish: function(pad) { var rval = true; if(encrypt) { if(pad) { rval = pad(8, _input, !encrypt); } else { // add PKCS#7 padding to block (each pad byte is the // value of the number of pad bytes) var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); _input.fillWithByte(padding, padding); } } if(rval) { // do final update _finish = true; cipher.update(); } if(!encrypt) { // check for error: input data not a multiple of block size rval = (_input.length() === 0); if(rval) { if(pad) { rval = pad(8, _output, !encrypt); } else { // ensure padding byte count is valid var len = _output.length(); var count = _output.at(len - 1); if(count > len) { rval = false; } else { // trim off padding bytes _output.truncate(count); } } } } return rval; } }; return cipher; }; /** * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the * given symmetric key. The output will be stored in the 'output' member * of the returned cipher. * * The key and iv may be given as a string of bytes or a byte buffer. * The cipher is initialized to use 128 effective key bits. * * @param key the symmetric key to use. * @param iv the initialization vector to use. * @param output the buffer to write to, null to create one. * * @return the cipher. */ forge.rc2.startEncrypting = function(key, iv, output) { var cipher = forge.rc2.createEncryptionCipher(key, 128); cipher.start(iv, output); return cipher; }; /** * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the * given symmetric key. * * The key may be given as a string of bytes or a byte buffer. * * To start encrypting call start() on the cipher with an iv and optional * output buffer. * * @param key the symmetric key to use. * * @return the cipher. */ forge.rc2.createEncryptionCipher = function(key, bits) { return createCipher(key, bits, true); }; /** * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the * given symmetric key. The output will be stored in the 'output' member * of the returned cipher. * * The key and iv may be given as a string of bytes or a byte buffer. * The cipher is initialized to use 128 effective key bits. * * @param key the symmetric key to use. * @param iv the initialization vector to use. * @param output the buffer to write to, null to create one. * * @return the cipher. */ forge.rc2.startDecrypting = function(key, iv, output) { var cipher = forge.rc2.createDecryptionCipher(key, 128); cipher.start(iv, output); return cipher; }; /** * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the * given symmetric key. * * The key may be given as a string of bytes or a byte buffer. * * To start decrypting call start() on the cipher with an iv and optional * output buffer. * * @param key the symmetric key to use. * * @return the cipher. */ forge.rc2.createDecryptionCipher = function(key, bits) { return createCipher(key, bits, false); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/pbe.js
aws/lti-middleware/node_modules/node-forge/lib/pbe.js
/** * Password-based encryption functions. * * @author Dave Longley * @author Stefan Siegl <[email protected]> * * Copyright (c) 2010-2013 Digital Bazaar, Inc. * Copyright (c) 2012 Stefan Siegl <[email protected]> * * An EncryptedPrivateKeyInfo: * * EncryptedPrivateKeyInfo ::= SEQUENCE { * encryptionAlgorithm EncryptionAlgorithmIdentifier, * encryptedData EncryptedData } * * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier * * EncryptedData ::= OCTET STRING */ var forge = require('./forge'); require('./aes'); require('./asn1'); require('./des'); require('./md'); require('./oids'); require('./pbkdf2'); require('./pem'); require('./random'); require('./rc2'); require('./rsa'); require('./util'); if(typeof BigInteger === 'undefined') { var BigInteger = forge.jsbn.BigInteger; } // shortcut for asn.1 API var asn1 = forge.asn1; /* Password-based encryption implementation. */ var pki = forge.pki = forge.pki || {}; module.exports = pki.pbe = forge.pbe = forge.pbe || {}; var oids = pki.oids; // validator for an EncryptedPrivateKeyInfo structure // Note: Currently only works w/algorithm params var encryptedPrivateKeyValidator = { name: 'EncryptedPrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'encryptionOid' }, { name: 'AlgorithmIdentifier.parameters', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'encryptionParams' }] }, { // encryptedData name: 'EncryptedPrivateKeyInfo.encryptedData', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'encryptedData' }] }; // validator for a PBES2Algorithms structure // Note: Currently only works w/PBKDF2 + AES encryption schemes var PBES2AlgorithmsValidator = { name: 'PBES2Algorithms', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'PBES2Algorithms.keyDerivationFunc', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'PBES2Algorithms.keyDerivationFunc.oid', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'kdfOid' }, { name: 'PBES2Algorithms.params', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'PBES2Algorithms.params.salt', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'kdfSalt' }, { name: 'PBES2Algorithms.params.iterationCount', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'kdfIterationCount' }, { name: 'PBES2Algorithms.params.keyLength', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, optional: true, capture: 'keyLength' }, { // prf name: 'PBES2Algorithms.params.prf', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, optional: true, value: [{ name: 'PBES2Algorithms.params.prf.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'prfOid' }] }] }] }, { name: 'PBES2Algorithms.encryptionScheme', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'PBES2Algorithms.encryptionScheme.oid', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'encOid' }, { name: 'PBES2Algorithms.encryptionScheme.iv', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'encIv' }] }] }; var pkcs12PbeParamsValidator = { name: 'pkcs-12PbeParams', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'pkcs-12PbeParams.salt', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'salt' }, { name: 'pkcs-12PbeParams.iterations', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'iterations' }] }; /** * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. * * PBES2Algorithms ALGORITHM-IDENTIFIER ::= * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} * * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} * * PBES2-params ::= SEQUENCE { * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} * } * * PBES2-KDFs ALGORITHM-IDENTIFIER ::= * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } * * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } * * PBKDF2-params ::= SEQUENCE { * salt CHOICE { * specified OCTET STRING, * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} * }, * iterationCount INTEGER (1..MAX), * keyLength INTEGER (1..MAX) OPTIONAL, * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 * } * * @param obj the ASN.1 PrivateKeyInfo object. * @param password the password to encrypt with. * @param options: * algorithm the encryption algorithm to use * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. * count the iteration count to use. * saltSize the salt size to use. * prfAlgorithm the PRF message digest algorithm to use * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') * * @return the ASN.1 EncryptedPrivateKeyInfo. */ pki.encryptPrivateKeyInfo = function(obj, password, options) { // set default options options = options || {}; options.saltSize = options.saltSize || 8; options.count = options.count || 2048; options.algorithm = options.algorithm || 'aes128'; options.prfAlgorithm = options.prfAlgorithm || 'sha1'; // generate PBE params var salt = forge.random.getBytesSync(options.saltSize); var count = options.count; var countBytes = asn1.integerToDer(count); var dkLen; var encryptionAlgorithm; var encryptedData; if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { // do PBES2 var ivLen, encOid, cipherFn; switch(options.algorithm) { case 'aes128': dkLen = 16; ivLen = 16; encOid = oids['aes128-CBC']; cipherFn = forge.aes.createEncryptionCipher; break; case 'aes192': dkLen = 24; ivLen = 16; encOid = oids['aes192-CBC']; cipherFn = forge.aes.createEncryptionCipher; break; case 'aes256': dkLen = 32; ivLen = 16; encOid = oids['aes256-CBC']; cipherFn = forge.aes.createEncryptionCipher; break; case 'des': dkLen = 8; ivLen = 8; encOid = oids['desCBC']; cipherFn = forge.des.createEncryptionCipher; break; default: var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); error.algorithm = options.algorithm; throw error; } // get PRF message digest var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); var md = prfAlgorithmToMessageDigest(prfAlgorithm); // encrypt private key using pbe SHA-1 and AES/DES var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); var iv = forge.random.getBytesSync(ivLen); var cipher = cipherFn(dk); cipher.start(iv); cipher.update(asn1.toDer(obj)); cipher.finish(); encryptedData = cipher.output.getBytes(); // get PBKDF2-params var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); encryptionAlgorithm = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids['pkcs5PBES2']).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // keyDerivationFunc asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()), // PBKDF2-params params ]), // encryptionScheme asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(encOid).getBytes()), // iv asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv) ]) ]) ]); } else if(options.algorithm === '3des') { // Do PKCS12 PBE dkLen = 24; var saltBytes = new forge.util.ByteBuffer(salt); var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); var cipher = forge.des.createEncryptionCipher(dk); cipher.start(iv); cipher.update(asn1.toDer(obj)); cipher.finish(); encryptedData = cipher.output.getBytes(); encryptionAlgorithm = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), // pkcs-12PbeParams asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // salt asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), // iteration count asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, countBytes.getBytes()) ]) ]); } else { var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); error.algorithm = options.algorithm; throw error; } // EncryptedPrivateKeyInfo var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // encryptionAlgorithm encryptionAlgorithm, // encryptedData asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData) ]); return rval; }; /** * Decrypts a ASN.1 PrivateKeyInfo object. * * @param obj the ASN.1 EncryptedPrivateKeyInfo object. * @param password the password to decrypt with. * * @return the ASN.1 PrivateKeyInfo on success, null on failure. */ pki.decryptPrivateKeyInfo = function(obj, password) { var rval = null; // get PBE params var capture = {}; var errors = []; if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { var error = new Error('Cannot read encrypted private key. ' + 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); error.errors = errors; throw error; } // get cipher var oid = asn1.derToOid(capture.encryptionOid); var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); // get encrypted data var encrypted = forge.util.createBuffer(capture.encryptedData); cipher.update(encrypted); if(cipher.finish()) { rval = asn1.fromDer(cipher.output); } return rval; }; /** * Converts a EncryptedPrivateKeyInfo to PEM format. * * @param epki the EncryptedPrivateKeyInfo. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted encrypted private key. */ pki.encryptedPrivateKeyToPem = function(epki, maxline) { // convert to DER, then PEM-encode var msg = { type: 'ENCRYPTED PRIVATE KEY', body: asn1.toDer(epki).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); }; /** * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption * is not performed. * * @param pem the EncryptedPrivateKeyInfo in PEM-format. * * @return the ASN.1 EncryptedPrivateKeyInfo. */ pki.encryptedPrivateKeyFromPem = function(pem) { var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'ENCRYPTED PRIVATE KEY') { var error = new Error('Could not convert encrypted private key from PEM; ' + 'PEM header type is "ENCRYPTED PRIVATE KEY".'); error.headerType = msg.type; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error('Could not convert encrypted private key from PEM; ' + 'PEM is encrypted.'); } // convert DER to ASN.1 object return asn1.fromDer(msg.body); }; /** * Encrypts an RSA private key. By default, the key will be wrapped in * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. * This is the standard, preferred way to encrypt a private key. * * To produce a non-standard PEM-encrypted private key that uses encapsulated * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL * private key encryption), set the 'legacy' option to true. Note: Using this * option will cause the iteration count to be forced to 1. * * Note: The 'des' algorithm is supported, but it is not considered to be * secure because it only uses a single 56-bit key. If possible, it is highly * recommended that a different algorithm be used. * * @param rsaKey the RSA key to encrypt. * @param password the password to use. * @param options: * algorithm: the encryption algorithm to use * ('aes128', 'aes192', 'aes256', '3des', 'des'). * count: the iteration count to use. * saltSize: the salt size to use. * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated * headers (DEK-Info) private key. * * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. */ pki.encryptRsaPrivateKey = function(rsaKey, password, options) { // standard PKCS#8 options = options || {}; if(!options.legacy) { // encrypt PrivateKeyInfo var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); rval = pki.encryptPrivateKeyInfo(rval, password, options); return pki.encryptedPrivateKeyToPem(rval); } // legacy non-PKCS#8 var algorithm; var iv; var dkLen; var cipherFn; switch(options.algorithm) { case 'aes128': algorithm = 'AES-128-CBC'; dkLen = 16; iv = forge.random.getBytesSync(16); cipherFn = forge.aes.createEncryptionCipher; break; case 'aes192': algorithm = 'AES-192-CBC'; dkLen = 24; iv = forge.random.getBytesSync(16); cipherFn = forge.aes.createEncryptionCipher; break; case 'aes256': algorithm = 'AES-256-CBC'; dkLen = 32; iv = forge.random.getBytesSync(16); cipherFn = forge.aes.createEncryptionCipher; break; case '3des': algorithm = 'DES-EDE3-CBC'; dkLen = 24; iv = forge.random.getBytesSync(8); cipherFn = forge.des.createEncryptionCipher; break; case 'des': algorithm = 'DES-CBC'; dkLen = 8; iv = forge.random.getBytesSync(8); cipherFn = forge.des.createEncryptionCipher; break; default: var error = new Error('Could not encrypt RSA private key; unsupported ' + 'encryption algorithm "' + options.algorithm + '".'); error.algorithm = options.algorithm; throw error; } // encrypt private key using OpenSSL legacy key derivation var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); var cipher = cipherFn(dk); cipher.start(iv); cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); cipher.finish(); var msg = { type: 'RSA PRIVATE KEY', procType: { version: '4', type: 'ENCRYPTED' }, dekInfo: { algorithm: algorithm, parameters: forge.util.bytesToHex(iv).toUpperCase() }, body: cipher.output.getBytes() }; return forge.pem.encode(msg); }; /** * Decrypts an RSA private key. * * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. * @param password the password to use. * * @return the RSA key on success, null on failure. */ pki.decryptRsaPrivateKey = function(pem, password) { var rval = null; var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'ENCRYPTED PRIVATE KEY' && msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { var error = new Error('Could not convert private key from PEM; PEM header type ' + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); error.headerType = error; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { var dkLen; var cipherFn; switch(msg.dekInfo.algorithm) { case 'DES-CBC': dkLen = 8; cipherFn = forge.des.createDecryptionCipher; break; case 'DES-EDE3-CBC': dkLen = 24; cipherFn = forge.des.createDecryptionCipher; break; case 'AES-128-CBC': dkLen = 16; cipherFn = forge.aes.createDecryptionCipher; break; case 'AES-192-CBC': dkLen = 24; cipherFn = forge.aes.createDecryptionCipher; break; case 'AES-256-CBC': dkLen = 32; cipherFn = forge.aes.createDecryptionCipher; break; case 'RC2-40-CBC': dkLen = 5; cipherFn = function(key) { return forge.rc2.createDecryptionCipher(key, 40); }; break; case 'RC2-64-CBC': dkLen = 8; cipherFn = function(key) { return forge.rc2.createDecryptionCipher(key, 64); }; break; case 'RC2-128-CBC': dkLen = 16; cipherFn = function(key) { return forge.rc2.createDecryptionCipher(key, 128); }; break; default: var error = new Error('Could not decrypt private key; unsupported ' + 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); error.algorithm = msg.dekInfo.algorithm; throw error; } // use OpenSSL legacy key derivation var iv = forge.util.hexToBytes(msg.dekInfo.parameters); var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); var cipher = cipherFn(dk); cipher.start(iv); cipher.update(forge.util.createBuffer(msg.body)); if(cipher.finish()) { rval = cipher.output.getBytes(); } else { return rval; } } else { rval = msg.body; } if(msg.type === 'ENCRYPTED PRIVATE KEY') { rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); } else { // decryption already performed above rval = asn1.fromDer(rval); } if(rval !== null) { rval = pki.privateKeyFromAsn1(rval); } return rval; }; /** * Derives a PKCS#12 key. * * @param password the password to derive the key material from, null or * undefined for none. * @param salt the salt, as a ByteBuffer, to use. * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). * @param iter the iteration count. * @param n the number of bytes to derive from the password. * @param md the message digest to use, defaults to SHA-1. * * @return a ByteBuffer with the bytes derived from the password. */ pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { var j, l; if(typeof md === 'undefined' || md === null) { if(!('sha1' in forge.md)) { throw new Error('"sha1" hash algorithm unavailable.'); } md = forge.md.sha1.create(); } var u = md.digestLength; var v = md.blockLength; var result = new forge.util.ByteBuffer(); /* Convert password to Unicode byte buffer + trailing 0-byte. */ var passBuf = new forge.util.ByteBuffer(); if(password !== null && password !== undefined) { for(l = 0; l < password.length; l++) { passBuf.putInt16(password.charCodeAt(l)); } passBuf.putInt16(0); } /* Length of salt and password in BYTES. */ var p = passBuf.length(); var s = salt.length(); /* 1. Construct a string, D (the "diversifier"), by concatenating v copies of ID. */ var D = new forge.util.ByteBuffer(); D.fillWithByte(id, v); /* 2. Concatenate copies of the salt together to create a string S of length v * ceil(s / v) bytes (the final copy of the salt may be trunacted to create S). Note that if the salt is the empty string, then so is S. */ var Slen = v * Math.ceil(s / v); var S = new forge.util.ByteBuffer(); for(l = 0; l < Slen; l++) { S.putByte(salt.at(l % s)); } /* 3. Concatenate copies of the password together to create a string P of length v * ceil(p / v) bytes (the final copy of the password may be truncated to create P). Note that if the password is the empty string, then so is P. */ var Plen = v * Math.ceil(p / v); var P = new forge.util.ByteBuffer(); for(l = 0; l < Plen; l++) { P.putByte(passBuf.at(l % p)); } /* 4. Set I=S||P to be the concatenation of S and P. */ var I = S; I.putBuffer(P); /* 5. Set c=ceil(n / u). */ var c = Math.ceil(n / u); /* 6. For i=1, 2, ..., c, do the following: */ for(var i = 1; i <= c; i++) { /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ var buf = new forge.util.ByteBuffer(); buf.putBytes(D.bytes()); buf.putBytes(I.bytes()); for(var round = 0; round < iter; round++) { md.start(); md.update(buf.getBytes()); buf = md.digest(); } /* b) Concatenate copies of Ai to create a string B of length v bytes (the final copy of Ai may be truncated to create B). */ var B = new forge.util.ByteBuffer(); for(l = 0; l < v; l++) { B.putByte(buf.at(l % u)); } /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, where k=ceil(s / v) + ceil(p / v), modify I by setting Ij=(Ij+B+1) mod 2v for each j. */ var k = Math.ceil(s / v) + Math.ceil(p / v); var Inew = new forge.util.ByteBuffer(); for(j = 0; j < k; j++) { var chunk = new forge.util.ByteBuffer(I.getBytes(v)); var x = 0x1ff; for(l = B.length() - 1; l >= 0; l--) { x = x >> 8; x += B.at(l) + chunk.at(l); chunk.setAt(l, x & 0xff); } Inew.putBuffer(chunk); } I = Inew; /* Add Ai to A. */ result.putBuffer(buf); } result.truncate(result.length() - n); return result; }; /** * Get new Forge cipher object instance. * * @param oid the OID (in string notation). * @param params the ASN.1 params object. * @param password the password to decrypt with. * * @return new cipher object instance. */ pki.pbe.getCipher = function(oid, params, password) { switch(oid) { case pki.oids['pkcs5PBES2']: return pki.pbe.getCipherForPBES2(oid, params, password); case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: case pki.oids['pbewithSHAAnd40BitRC2-CBC']: return pki.pbe.getCipherForPKCS12PBE(oid, params, password); default: var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); error.oid = oid; error.supportedOids = [ 'pkcs5PBES2', 'pbeWithSHAAnd3-KeyTripleDES-CBC', 'pbewithSHAAnd40BitRC2-CBC' ]; throw error; } }; /** * Get new Forge cipher object instance according to PBES2 params block. * * The returned cipher instance is already started using the IV * from PBES2 parameter block. * * @param oid the PKCS#5 PBKDF2 OID (in string notation). * @param params the ASN.1 PBES2-params object. * @param password the password to decrypt with. * * @return new cipher object instance. */ pki.pbe.getCipherForPBES2 = function(oid, params, password) { // get PBE params var capture = {}; var errors = []; if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { var error = new Error('Cannot read password-based-encryption algorithm ' + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); error.errors = errors; throw error; } // check oids oid = asn1.derToOid(capture.kdfOid); if(oid !== pki.oids['pkcs5PBKDF2']) { var error = new Error('Cannot read encrypted private key. ' + 'Unsupported key derivation function OID.'); error.oid = oid; error.supportedOids = ['pkcs5PBKDF2']; throw error; } oid = asn1.derToOid(capture.encOid); if(oid !== pki.oids['aes128-CBC'] && oid !== pki.oids['aes192-CBC'] && oid !== pki.oids['aes256-CBC'] && oid !== pki.oids['des-EDE3-CBC'] && oid !== pki.oids['desCBC']) { var error = new Error('Cannot read encrypted private key. ' + 'Unsupported encryption scheme OID.'); error.oid = oid; error.supportedOids = [ 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; throw error; } // set PBE params var salt = capture.kdfSalt; var count = forge.util.createBuffer(capture.kdfIterationCount); count = count.getInt(count.length() << 3); var dkLen; var cipherFn; switch(pki.oids[oid]) { case 'aes128-CBC': dkLen = 16; cipherFn = forge.aes.createDecryptionCipher; break; case 'aes192-CBC': dkLen = 24; cipherFn = forge.aes.createDecryptionCipher; break; case 'aes256-CBC': dkLen = 32; cipherFn = forge.aes.createDecryptionCipher; break; case 'des-EDE3-CBC': dkLen = 24; cipherFn = forge.des.createDecryptionCipher; break; case 'desCBC': dkLen = 8; cipherFn = forge.des.createDecryptionCipher; break; } // get PRF message digest var md = prfOidToMessageDigest(capture.prfOid); // decrypt private key using pbe with chosen PRF and AES/DES var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); var iv = capture.encIv; var cipher = cipherFn(dk); cipher.start(iv); return cipher; }; /** * Get new Forge cipher object instance for PKCS#12 PBE. * * The returned cipher instance is already started using the key & IV * derived from the provided password and PKCS#12 PBE salt. * * @param oid The PKCS#12 PBE OID (in string notation). * @param params The ASN.1 PKCS#12 PBE-params object. * @param password The password to decrypt with. * * @return the new cipher object instance. */ pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { // get PBE params var capture = {}; var errors = []; if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { var error = new Error('Cannot read password-based-encryption algorithm ' + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); error.errors = errors; throw error; } var salt = forge.util.createBuffer(capture.salt); var count = forge.util.createBuffer(capture.iterations); count = count.getInt(count.length() << 3); var dkLen, dIvLen, cipherFn; switch(oid) { case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: dkLen = 24; dIvLen = 8; cipherFn = forge.des.startDecrypting; break; case pki.oids['pbewithSHAAnd40BitRC2-CBC']: dkLen = 5; dIvLen = 8; cipherFn = function(key, iv) { var cipher = forge.rc2.createDecryptionCipher(key, 40); cipher.start(iv, null); return cipher; }; break; default: var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); error.oid = oid; throw error; } // get PRF message digest var md = prfOidToMessageDigest(capture.prfOid); var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); md.start(); var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); return cipherFn(key, iv); }; /** * OpenSSL's legacy key derivation function. * * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html * * @param password the password to derive the key from. * @param salt the salt to use, null for none. * @param dkLen the number of bytes needed for the derived key. * @param [options] the options to use: * [md] an optional message digest object to use. */ pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { if(typeof md === 'undefined' || md === null) { if(!('md5' in forge.md)) { throw new Error('"md5" hash algorithm unavailable.'); } md = forge.md.md5.create(); } if(salt === null) { salt = ''; } var digests = [hash(md, password + salt)]; for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { digests.push(hash(md, digests[i - 1] + password + salt)); } return digests.join('').substr(0, dkLen); }; function hash(md, bytes) { return md.start().update(bytes).digest().getBytes(); } function prfOidToMessageDigest(prfOid) { // get PRF algorithm, default to SHA-1 var prfAlgorithm; if(!prfOid) { prfAlgorithm = 'hmacWithSHA1'; } else { prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; if(!prfAlgorithm) { var error = new Error('Unsupported PRF OID.'); error.oid = prfOid; error.supported = [ 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', 'hmacWithSHA512']; throw error; } } return prfAlgorithmToMessageDigest(prfAlgorithm); } function prfAlgorithmToMessageDigest(prfAlgorithm) { var factory = forge.md; switch(prfAlgorithm) { case 'hmacWithSHA224': factory = forge.md.sha512; case 'hmacWithSHA1': case 'hmacWithSHA256': case 'hmacWithSHA384': case 'hmacWithSHA512': prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); break; default: var error = new Error('Unsupported PRF algorithm.'); error.algorithm = prfAlgorithm; error.supported = [ 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', 'hmacWithSHA512']; throw error; } if(!factory || !(prfAlgorithm in factory)) { throw new Error('Unknown hash algorithm: ' + prfAlgorithm); } return factory[prfAlgorithm].create(); } function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // salt asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), // iteration count asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, countBytes.getBytes()) ]); // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm if(prfAlgorithm !== 'hmacWithSHA1') { params.value.push( // key length asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(dkLen.toString(16))), // AlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ])); } return params; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/tls.js
aws/lti-middleware/node_modules/node-forge/lib/tls.js
/** * A Javascript implementation of Transport Layer Security (TLS). * * @author Dave Longley * * Copyright (c) 2009-2014 Digital Bazaar, Inc. * * The TLS Handshake Protocol involves the following steps: * * - Exchange hello messages to agree on algorithms, exchange random values, * and check for session resumption. * * - Exchange the necessary cryptographic parameters to allow the client and * server to agree on a premaster secret. * * - Exchange certificates and cryptographic information to allow the client * and server to authenticate themselves. * * - Generate a master secret from the premaster secret and exchanged random * values. * * - Provide security parameters to the record layer. * * - Allow the client and server to verify that their peer has calculated the * same security parameters and that the handshake occurred without tampering * by an attacker. * * Up to 4 different messages may be sent during a key exchange. The server * certificate, the server key exchange, the client certificate, and the * client key exchange. * * A typical handshake (from the client's perspective). * * 1. Client sends ClientHello. * 2. Client receives ServerHello. * 3. Client receives optional Certificate. * 4. Client receives optional ServerKeyExchange. * 5. Client receives ServerHelloDone. * 6. Client sends optional Certificate. * 7. Client sends ClientKeyExchange. * 8. Client sends optional CertificateVerify. * 9. Client sends ChangeCipherSpec. * 10. Client sends Finished. * 11. Client receives ChangeCipherSpec. * 12. Client receives Finished. * 13. Client sends/receives application data. * * To reuse an existing session: * * 1. Client sends ClientHello with session ID for reuse. * 2. Client receives ServerHello with same session ID if reusing. * 3. Client receives ChangeCipherSpec message if reusing. * 4. Client receives Finished. * 5. Client sends ChangeCipherSpec. * 6. Client sends Finished. * * Note: Client ignores HelloRequest if in the middle of a handshake. * * Record Layer: * * The record layer fragments information blocks into TLSPlaintext records * carrying data in chunks of 2^14 bytes or less. Client message boundaries are * not preserved in the record layer (i.e., multiple client messages of the * same ContentType MAY be coalesced into a single TLSPlaintext record, or a * single message MAY be fragmented across several records). * * struct { * uint8 major; * uint8 minor; * } ProtocolVersion; * * struct { * ContentType type; * ProtocolVersion version; * uint16 length; * opaque fragment[TLSPlaintext.length]; * } TLSPlaintext; * * type: * The higher-level protocol used to process the enclosed fragment. * * version: * The version of the protocol being employed. TLS Version 1.2 uses version * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that * supports multiple versions of TLS may not know what version will be * employed before it receives the ServerHello. * * length: * The length (in bytes) of the following TLSPlaintext.fragment. The length * MUST NOT exceed 2^14 = 16384 bytes. * * fragment: * The application data. This data is transparent and treated as an * independent block to be dealt with by the higher-level protocol specified * by the type field. * * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or * ChangeCipherSpec content types. Zero-length fragments of Application data * MAY be sent as they are potentially useful as a traffic analysis * countermeasure. * * Note: Data of different TLS record layer content types MAY be interleaved. * Application data is generally of lower precedence for transmission than * other content types. However, records MUST be delivered to the network in * the same order as they are protected by the record layer. Recipients MUST * receive and process interleaved application layer traffic during handshakes * subsequent to the first one on a connection. * * struct { * ContentType type; // same as TLSPlaintext.type * ProtocolVersion version;// same as TLSPlaintext.version * uint16 length; * opaque fragment[TLSCompressed.length]; * } TLSCompressed; * * length: * The length (in bytes) of the following TLSCompressed.fragment. * The length MUST NOT exceed 2^14 + 1024. * * fragment: * The compressed form of TLSPlaintext.fragment. * * Note: A CompressionMethod.null operation is an identity operation; no fields * are altered. In this implementation, since no compression is supported, * uncompressed records are always the same as compressed records. * * Encryption Information: * * The encryption and MAC functions translate a TLSCompressed structure into a * TLSCiphertext. The decryption functions reverse the process. The MAC of the * record also includes a sequence number so that missing, extra, or repeated * messages are detectable. * * struct { * ContentType type; * ProtocolVersion version; * uint16 length; * select (SecurityParameters.cipher_type) { * case stream: GenericStreamCipher; * case block: GenericBlockCipher; * case aead: GenericAEADCipher; * } fragment; * } TLSCiphertext; * * type: * The type field is identical to TLSCompressed.type. * * version: * The version field is identical to TLSCompressed.version. * * length: * The length (in bytes) of the following TLSCiphertext.fragment. * The length MUST NOT exceed 2^14 + 2048. * * fragment: * The encrypted form of TLSCompressed.fragment, with the MAC. * * Note: Only CBC Block Ciphers are supported by this implementation. * * The TLSCompressed.fragment structures are converted to/from block * TLSCiphertext.fragment structures. * * struct { * opaque IV[SecurityParameters.record_iv_length]; * block-ciphered struct { * opaque content[TLSCompressed.length]; * opaque MAC[SecurityParameters.mac_length]; * uint8 padding[GenericBlockCipher.padding_length]; * uint8 padding_length; * }; * } GenericBlockCipher; * * The MAC is generated as described in Section 6.2.3.1. * * IV: * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be * unpredictable. Note that in versions of TLS prior to 1.1, there was no * IV field, and the last ciphertext block of the previous record (the "CBC * residue") was used as the IV. This was changed to prevent the attacks * described in [CBCATT]. For block ciphers, the IV length is of length * SecurityParameters.record_iv_length, which is equal to the * SecurityParameters.block_size. * * padding: * Padding that is added to force the length of the plaintext to be an * integral multiple of the block cipher's block length. The padding MAY be * any length up to 255 bytes, as long as it results in the * TLSCiphertext.length being an integral multiple of the block length. * Lengths longer than necessary might be desirable to frustrate attacks on * a protocol that are based on analysis of the lengths of exchanged * messages. Each uint8 in the padding data vector MUST be filled with the * padding length value. The receiver MUST check this padding and MUST use * the bad_record_mac alert to indicate padding errors. * * padding_length: * The padding length MUST be such that the total size of the * GenericBlockCipher structure is a multiple of the cipher's block length. * Legal values range from zero to 255, inclusive. This length specifies the * length of the padding field exclusive of the padding_length field itself. * * The encrypted data length (TLSCiphertext.length) is one more than the sum of * SecurityParameters.block_length, TLSCompressed.length, * SecurityParameters.mac_length, and padding_length. * * Example: If the block length is 8 bytes, the content length * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the * length before padding is 82 bytes (this does not include the IV. Thus, the * padding length modulo 8 must be equal to 6 in order to make the total length * an even multiple of 8 bytes (the block length). The padding length can be * 6, 14, 22, and so on, through 254. If the padding length were the minimum * necessary, 6, the padding would be 6 bytes, each containing the value 6. * Thus, the last 8 octets of the GenericBlockCipher before block encryption * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. * * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical * that the entire plaintext of the record be known before any ciphertext is * transmitted. Otherwise, it is possible for the attacker to mount the attack * described in [CBCATT]. * * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing * attack on CBC padding based on the time required to compute the MAC. In * order to defend against this attack, implementations MUST ensure that * record processing time is essentially the same whether or not the padding * is correct. In general, the best way to do this is to compute the MAC even * if the padding is incorrect, and only then reject the packet. For instance, * if the pad appears to be incorrect, the implementation might assume a * zero-length pad and then compute the MAC. This leaves a small timing * channel, since MAC performance depends, to some extent, on the size of the * data fragment, but it is not believed to be large enough to be exploitable, * due to the large block size of existing MACs and the small size of the * timing signal. */ var forge = require('./forge'); require('./asn1'); require('./hmac'); require('./md5'); require('./pem'); require('./pki'); require('./random'); require('./sha1'); require('./util'); /** * Generates pseudo random bytes by mixing the result of two hash functions, * MD5 and SHA-1. * * prf_TLS1(secret, label, seed) = * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); * * Each P_hash function functions as follows: * * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + * HMAC_hash(secret, A(2) + seed) + * HMAC_hash(secret, A(3) + seed) + ... * A() is defined as: * A(0) = seed * A(i) = HMAC_hash(secret, A(i-1)) * * The '+' operator denotes concatenation. * * As many iterations A(N) as are needed are performed to generate enough * pseudo random byte output. If an iteration creates more data than is * necessary, then it is truncated. * * Therefore: * A(1) = HMAC_hash(secret, A(0)) * = HMAC_hash(secret, seed) * A(2) = HMAC_hash(secret, A(1)) * = HMAC_hash(secret, HMAC_hash(secret, seed)) * * Therefore: * P_hash(secret, seed) = * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + * ... * * Therefore: * P_hash(secret, seed) = * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + * ... * * @param secret the secret to use. * @param label the label to use. * @param seed the seed value to use. * @param length the number of bytes to generate. * * @return the pseudo random bytes in a byte buffer. */ var prf_TLS1 = function(secret, label, seed, length) { var rval = forge.util.createBuffer(); /* For TLS 1.0, the secret is split in half, into two secrets of equal length. If the secret has an odd length then the last byte of the first half will be the same as the first byte of the second. The length of the two secrets is half of the secret rounded up. */ var idx = (secret.length >> 1); var slen = idx + (secret.length & 1); var s1 = secret.substr(0, slen); var s2 = secret.substr(idx, slen); var ai = forge.util.createBuffer(); var hmac = forge.hmac.create(); seed = label + seed; // determine the number of iterations that must be performed to generate // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 var md5itr = Math.ceil(length / 16); var sha1itr = Math.ceil(length / 20); // do md5 iterations hmac.start('MD5', s1); var md5bytes = forge.util.createBuffer(); ai.putBytes(seed); for(var i = 0; i < md5itr; ++i) { // HMAC_hash(secret, A(i-1)) hmac.start(null, null); hmac.update(ai.getBytes()); ai.putBuffer(hmac.digest()); // HMAC_hash(secret, A(i) + seed) hmac.start(null, null); hmac.update(ai.bytes() + seed); md5bytes.putBuffer(hmac.digest()); } // do sha1 iterations hmac.start('SHA1', s2); var sha1bytes = forge.util.createBuffer(); ai.clear(); ai.putBytes(seed); for(var i = 0; i < sha1itr; ++i) { // HMAC_hash(secret, A(i-1)) hmac.start(null, null); hmac.update(ai.getBytes()); ai.putBuffer(hmac.digest()); // HMAC_hash(secret, A(i) + seed) hmac.start(null, null); hmac.update(ai.bytes() + seed); sha1bytes.putBuffer(hmac.digest()); } // XOR the md5 bytes with the sha1 bytes rval.putBytes(forge.util.xorBytes( md5bytes.getBytes(), sha1bytes.getBytes(), length)); return rval; }; /** * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2. * * @param secret the secret to use. * @param label the label to use. * @param seed the seed value to use. * @param length the number of bytes to generate. * * @return the pseudo random bytes in a byte buffer. */ var prf_sha256 = function(secret, label, seed, length) { // FIXME: implement me for TLS 1.2 }; /** * Gets a MAC for a record using the SHA-1 hash algorithm. * * @param key the mac key. * @param state the sequence number (array of two 32-bit integers). * @param record the record. * * @return the sha-1 hash (20 bytes) for the given record. */ var hmac_sha1 = function(key, seqNum, record) { /* MAC is computed like so: HMAC_hash( key, seqNum + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length + TLSCompressed.fragment) */ var hmac = forge.hmac.create(); hmac.start('SHA1', key); var b = forge.util.createBuffer(); b.putInt32(seqNum[0]); b.putInt32(seqNum[1]); b.putByte(record.type); b.putByte(record.version.major); b.putByte(record.version.minor); b.putInt16(record.length); b.putBytes(record.fragment.bytes()); hmac.update(b.getBytes()); return hmac.digest().getBytes(); }; /** * Compresses the TLSPlaintext record into a TLSCompressed record using the * deflate algorithm. * * @param c the TLS connection. * @param record the TLSPlaintext record to compress. * @param s the ConnectionState to use. * * @return true on success, false on failure. */ var deflate = function(c, record, s) { var rval = false; try { var bytes = c.deflate(record.fragment.getBytes()); record.fragment = forge.util.createBuffer(bytes); record.length = bytes.length; rval = true; } catch(ex) { // deflate error, fail out } return rval; }; /** * Decompresses the TLSCompressed record into a TLSPlaintext record using the * deflate algorithm. * * @param c the TLS connection. * @param record the TLSCompressed record to decompress. * @param s the ConnectionState to use. * * @return true on success, false on failure. */ var inflate = function(c, record, s) { var rval = false; try { var bytes = c.inflate(record.fragment.getBytes()); record.fragment = forge.util.createBuffer(bytes); record.length = bytes.length; rval = true; } catch(ex) { // inflate error, fail out } return rval; }; /** * Reads a TLS variable-length vector from a byte buffer. * * Variable-length vectors are defined by specifying a subrange of legal * lengths, inclusively, using the notation <floor..ceiling>. When these are * encoded, the actual length precedes the vector's contents in the byte * stream. The length will be in the form of a number consuming as many bytes * as required to hold the vector's specified maximum (ceiling) length. A * variable-length vector with an actual length field of zero is referred to * as an empty vector. * * @param b the byte buffer. * @param lenBytes the number of bytes required to store the length. * * @return the resulting byte buffer. */ var readVector = function(b, lenBytes) { var len = 0; switch(lenBytes) { case 1: len = b.getByte(); break; case 2: len = b.getInt16(); break; case 3: len = b.getInt24(); break; case 4: len = b.getInt32(); break; } // read vector bytes into a new buffer return forge.util.createBuffer(b.getBytes(len)); }; /** * Writes a TLS variable-length vector to a byte buffer. * * @param b the byte buffer. * @param lenBytes the number of bytes required to store the length. * @param v the byte buffer vector. */ var writeVector = function(b, lenBytes, v) { // encode length at the start of the vector, where the number of bytes for // the length is the maximum number of bytes it would take to encode the // vector's ceiling b.putInt(v.length(), lenBytes << 3); b.putBuffer(v); }; /** * The tls implementation. */ var tls = {}; /** * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time * of this implementation so TLS 1.0 was implemented instead. */ tls.Versions = { TLS_1_0: {major: 3, minor: 1}, TLS_1_1: {major: 3, minor: 2}, TLS_1_2: {major: 3, minor: 3} }; tls.SupportedVersions = [ tls.Versions.TLS_1_1, tls.Versions.TLS_1_0 ]; tls.Version = tls.SupportedVersions[0]; /** * Maximum fragment size. True maximum is 16384, but we fragment before that * to allow for unusual small increases during compression. */ tls.MaxFragment = 16384 - 1024; /** * Whether this entity is considered the "client" or "server". * enum { server, client } ConnectionEnd; */ tls.ConnectionEnd = { server: 0, client: 1 }; /** * Pseudo-random function algorithm used to generate keys from the master * secret. * enum { tls_prf_sha256 } PRFAlgorithm; */ tls.PRFAlgorithm = { tls_prf_sha256: 0 }; /** * Bulk encryption algorithms. * enum { null, rc4, des3, aes } BulkCipherAlgorithm; */ tls.BulkCipherAlgorithm = { none: null, rc4: 0, des3: 1, aes: 2 }; /** * Cipher types. * enum { stream, block, aead } CipherType; */ tls.CipherType = { stream: 0, block: 1, aead: 2 }; /** * MAC (Message Authentication Code) algorithms. * enum { null, hmac_md5, hmac_sha1, hmac_sha256, * hmac_sha384, hmac_sha512} MACAlgorithm; */ tls.MACAlgorithm = { none: null, hmac_md5: 0, hmac_sha1: 1, hmac_sha256: 2, hmac_sha384: 3, hmac_sha512: 4 }; /** * Compression algorithms. * enum { null(0), deflate(1), (255) } CompressionMethod; */ tls.CompressionMethod = { none: 0, deflate: 1 }; /** * TLS record content types. * enum { * change_cipher_spec(20), alert(21), handshake(22), * application_data(23), (255) * } ContentType; */ tls.ContentType = { change_cipher_spec: 20, alert: 21, handshake: 22, application_data: 23, heartbeat: 24 }; /** * TLS handshake types. * enum { * hello_request(0), client_hello(1), server_hello(2), * certificate(11), server_key_exchange (12), * certificate_request(13), server_hello_done(14), * certificate_verify(15), client_key_exchange(16), * finished(20), (255) * } HandshakeType; */ tls.HandshakeType = { hello_request: 0, client_hello: 1, server_hello: 2, certificate: 11, server_key_exchange: 12, certificate_request: 13, server_hello_done: 14, certificate_verify: 15, client_key_exchange: 16, finished: 20 }; /** * TLS Alert Protocol. * * enum { warning(1), fatal(2), (255) } AlertLevel; * * enum { * close_notify(0), * unexpected_message(10), * bad_record_mac(20), * decryption_failed(21), * record_overflow(22), * decompression_failure(30), * handshake_failure(40), * bad_certificate(42), * unsupported_certificate(43), * certificate_revoked(44), * certificate_expired(45), * certificate_unknown(46), * illegal_parameter(47), * unknown_ca(48), * access_denied(49), * decode_error(50), * decrypt_error(51), * export_restriction(60), * protocol_version(70), * insufficient_security(71), * internal_error(80), * user_canceled(90), * no_renegotiation(100), * (255) * } AlertDescription; * * struct { * AlertLevel level; * AlertDescription description; * } Alert; */ tls.Alert = {}; tls.Alert.Level = { warning: 1, fatal: 2 }; tls.Alert.Description = { close_notify: 0, unexpected_message: 10, bad_record_mac: 20, decryption_failed: 21, record_overflow: 22, decompression_failure: 30, handshake_failure: 40, bad_certificate: 42, unsupported_certificate: 43, certificate_revoked: 44, certificate_expired: 45, certificate_unknown: 46, illegal_parameter: 47, unknown_ca: 48, access_denied: 49, decode_error: 50, decrypt_error: 51, export_restriction: 60, protocol_version: 70, insufficient_security: 71, internal_error: 80, user_canceled: 90, no_renegotiation: 100 }; /** * TLS Heartbeat Message types. * enum { * heartbeat_request(1), * heartbeat_response(2), * (255) * } HeartbeatMessageType; */ tls.HeartbeatMessageType = { heartbeat_request: 1, heartbeat_response: 2 }; /** * Supported cipher suites. */ tls.CipherSuites = {}; /** * Gets a supported cipher suite from its 2 byte ID. * * @param twoBytes two bytes in a string. * * @return the matching supported cipher suite or null. */ tls.getCipherSuite = function(twoBytes) { var rval = null; for(var key in tls.CipherSuites) { var cs = tls.CipherSuites[key]; if(cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { rval = cs; break; } } return rval; }; /** * Called when an unexpected record is encountered. * * @param c the connection. * @param record the record. */ tls.handleUnexpected = function(c, record) { // if connection is client and closed, ignore unexpected messages var ignore = (!c.open && c.entity === tls.ConnectionEnd.client); if(!ignore) { c.error(c, { message: 'Unexpected message. Received TLS record out of order.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.unexpected_message } }); } }; /** * Called when a client receives a HelloRequest record. * * @param c the connection. * @param record the record. * @param length the length of the handshake message. */ tls.handleHelloRequest = function(c, record, length) { // ignore renegotiation requests from the server during a handshake, but // if handshaking, send a warning alert that renegotation is denied if(!c.handshaking && c.handshakes > 0) { // send alert warning tls.queue(c, tls.createAlert(c, { level: tls.Alert.Level.warning, description: tls.Alert.Description.no_renegotiation })); tls.flush(c); } // continue c.process(); }; /** * Parses a hello message from a ClientHello or ServerHello record. * * @param record the record to parse. * * @return the parsed message. */ tls.parseHelloMessage = function(c, record, length) { var msg = null; var client = (c.entity === tls.ConnectionEnd.client); // minimum of 38 bytes in message if(length < 38) { c.error(c, { message: client ? 'Invalid ServerHello message. Message too short.' : 'Invalid ClientHello message. Message too short.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.illegal_parameter } }); } else { // use 'remaining' to calculate # of remaining bytes in the message var b = record.fragment; var remaining = b.length(); msg = { version: { major: b.getByte(), minor: b.getByte() }, random: forge.util.createBuffer(b.getBytes(32)), session_id: readVector(b, 1), extensions: [] }; if(client) { msg.cipher_suite = b.getBytes(2); msg.compression_method = b.getByte(); } else { msg.cipher_suites = readVector(b, 2); msg.compression_methods = readVector(b, 1); } // read extensions if there are any bytes left in the message remaining = length - (remaining - b.length()); if(remaining > 0) { // parse extensions var exts = readVector(b, 2); while(exts.length() > 0) { msg.extensions.push({ type: [exts.getByte(), exts.getByte()], data: readVector(exts, 2) }); } // TODO: make extension support modular if(!client) { for(var i = 0; i < msg.extensions.length; ++i) { var ext = msg.extensions[i]; // support SNI extension if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { // get server name list var snl = readVector(ext.data, 2); while(snl.length() > 0) { // read server name type var snType = snl.getByte(); // only HostName type (0x00) is known, break out if // another type is detected if(snType !== 0x00) { break; } // add host name to server name list c.session.extensions.server_name.serverNameList.push( readVector(snl, 2).getBytes()); } } } } } // version already set, do not allow version change if(c.session.version) { if(msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { return c.error(c, { message: 'TLS version change is disallowed during renegotiation.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.protocol_version } }); } } // get the chosen (ServerHello) cipher suite if(client) { // FIXME: should be checking configured acceptable cipher suites c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); } else { // get a supported preferred (ClientHello) cipher suite // choose the first supported cipher suite var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); while(tmp.length() > 0) { // FIXME: should be checking configured acceptable suites // cipher suites take up 2 bytes c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); if(c.session.cipherSuite !== null) { break; } } } // cipher suite not supported if(c.session.cipherSuite === null) { return c.error(c, { message: 'No cipher suites in common.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.handshake_failure }, cipherSuite: forge.util.bytesToHex(msg.cipher_suite) }); } // TODO: handle compression methods if(client) { c.session.compressionMethod = msg.compression_method; } else { // no compression c.session.compressionMethod = tls.CompressionMethod.none; } } return msg; }; /** * Creates security parameters for the given connection based on the given * hello message. * * @param c the TLS connection. * @param msg the hello message. */ tls.createSecurityParameters = function(c, msg) { /* Note: security params are from TLS 1.2, some values like prf_algorithm are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is used. */ // TODO: handle other options from server when more supported // get client and server randoms var client = (c.entity === tls.ConnectionEnd.client); var msgRandom = msg.random.bytes(); var cRandom = client ? c.session.sp.client_random : msgRandom; var sRandom = client ? msgRandom : tls.createRandom().getBytes(); // create new security parameters c.session.sp = { entity: c.entity, prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, bulk_cipher_algorithm: null, cipher_type: null, enc_key_length: null, block_length: null, fixed_iv_length: null, record_iv_length: null, mac_algorithm: null, mac_length: null, mac_key_length: null, compression_algorithm: c.session.compressionMethod, pre_master_secret: null, master_secret: null, client_random: cRandom, server_random: sRandom }; }; /** * Called when a client receives a ServerHello record. * * When a ServerHello message will be sent: * The server will send this message in response to a client hello message * when it was able to find an acceptable set of algorithms. If it cannot * find such a match, it will respond with a handshake failure alert. * * uint24 length; * struct { * ProtocolVersion server_version; * Random random; * SessionID session_id; * CipherSuite cipher_suite; * CompressionMethod compression_method; * select(extensions_present) { * case false: * struct {}; * case true: * Extension extensions<0..2^16-1>; * }; * } ServerHello; * * @param c the connection. * @param record the record. * @param length the length of the handshake message. */ tls.handleServerHello = function(c, record, length) { var msg = tls.parseHelloMessage(c, record, length); if(c.fail) { return; } // ensure server version is compatible if(msg.version.minor <= c.version.minor) { c.version.minor = msg.version.minor; } else { return c.error(c, { message: 'Incompatible TLS version.', send: true, alert: { level: tls.Alert.Level.fatal, description: tls.Alert.Description.protocol_version } }); } // indicate session version has been set c.session.version = c.version; // get the session ID from the message var sessionId = msg.session_id.bytes(); // if the session ID is not blank and matches the cached one, resume // the session if(sessionId.length > 0 && sessionId === c.session.id) { // resuming session, expect a ChangeCipherSpec next c.expect = SCC; c.session.resuming = true; // get new server random c.session.sp.server_random = msg.random.bytes(); } else { // not resuming, expect a server Certificate message next c.expect = SCE; c.session.resuming = false; // create new security parameters tls.createSecurityParameters(c, msg); } // set new session ID c.session.id = sessionId; // continue c.process(); }; /** * Called when a server receives a ClientHello record. * * When a ClientHello message will be sent: * When a client first connects to a server it is required to send the * client hello as its first message. The client can also send a client * hello in response to a hello request or on its own initiative in order * to renegotiate the security parameters in an existing connection. * * @param c the connection. * @param record the record. * @param length the length of the handshake message. */ tls.handleClientHello = function(c, record, length) { var msg = tls.parseHelloMessage(c, record, length); if(c.fail) { return; } // get the session ID from the message var sessionId = msg.session_id.bytes(); // see if the given session ID is in the cache var session = null; if(c.sessionCache) { session = c.sessionCache.getSession(sessionId); if(session === null) { // session ID not found sessionId = ''; } else if(session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { // if session version is incompatible with client version, do not resume session = null; sessionId = ''; } } // no session found to resume, generate a new session ID if(sessionId.length === 0) { sessionId = forge.random.getBytes(32); } // update session c.session.id = sessionId; c.session.clientHelloVersion = msg.version; c.session.sp = {}; if(session) { // use version and security parameters from resumed session c.version = c.session.version = session.version; c.session.sp = session.sp; } else { // use highest compatible minor version var version; for(var i = 1; i < tls.SupportedVersions.length; ++i) { version = tls.SupportedVersions[i]; if(version.minor <= msg.version.minor) { break; } } c.version = {major: version.major, minor: version.minor}; c.session.version = c.version; } // if a session is set, resume it
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/index.js
aws/lti-middleware/node_modules/node-forge/lib/index.js
/** * Node.js module for Forge. * * @author Dave Longley * * Copyright 2011-2016 Digital Bazaar, Inc. */ module.exports = require('./forge'); require('./aes'); require('./aesCipherSuites'); require('./asn1'); require('./cipher'); require('./des'); require('./ed25519'); require('./hmac'); require('./kem'); require('./log'); require('./md.all'); require('./mgf1'); require('./pbkdf2'); require('./pem'); require('./pkcs1'); require('./pkcs12'); require('./pkcs7'); require('./pki'); require('./prime'); require('./prng'); require('./pss'); require('./random'); require('./rc2'); require('./ssh'); require('./tls'); require('./util');
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/pss.js
aws/lti-middleware/node_modules/node-forge/lib/pss.js
/** * Javascript implementation of PKCS#1 PSS signature padding. * * @author Stefan Siegl * * Copyright (c) 2012 Stefan Siegl <[email protected]> */ var forge = require('./forge'); require('./random'); require('./util'); // shortcut for PSS API var pss = module.exports = forge.pss = forge.pss || {}; /** * Creates a PSS signature scheme object. * * There are several ways to provide a salt for encoding: * * 1. Specify the saltLength only and the built-in PRNG will generate it. * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that * will be used. * 3. Specify the salt itself as a forge.util.ByteBuffer. * * @param options the options to use: * md the message digest object to use, a forge md instance. * mgf the mask generation function to use, a forge mgf instance. * [saltLength] the length of the salt in octets. * [prng] the pseudo-random number generator to use to produce a salt. * [salt] the salt to use when encoding. * * @return a signature scheme object. */ pss.create = function(options) { // backwards compatibility w/legacy args: hash, mgf, sLen if(arguments.length === 3) { options = { md: arguments[0], mgf: arguments[1], saltLength: arguments[2] }; } var hash = options.md; var mgf = options.mgf; var hLen = hash.digestLength; var salt_ = options.salt || null; if(typeof salt_ === 'string') { // assume binary-encoded string salt_ = forge.util.createBuffer(salt_); } var sLen; if('saltLength' in options) { sLen = options.saltLength; } else if(salt_ !== null) { sLen = salt_.length(); } else { throw new Error('Salt length not specified or specific salt not given.'); } if(salt_ !== null && salt_.length() !== sLen) { throw new Error('Given salt length does not match length of given salt.'); } var prng = options.prng || forge.random; var pssobj = {}; /** * Encodes a PSS signature. * * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. * * @param md the message digest object with the hash to sign. * @param modsBits the length of the RSA modulus in bits. * * @return the encoded message as a binary-encoded string of length * ceil((modBits - 1) / 8). */ pssobj.encode = function(md, modBits) { var i; var emBits = modBits - 1; var emLen = Math.ceil(emBits / 8); /* 2. Let mHash = Hash(M), an octet string of length hLen. */ var mHash = md.digest().getBytes(); /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ if(emLen < hLen + sLen + 2) { throw new Error('Message is too long to encrypt.'); } /* 4. Generate a random octet string salt of length sLen; if sLen = 0, * then salt is the empty string. */ var salt; if(salt_ === null) { salt = prng.getBytesSync(sLen); } else { salt = salt_.bytes(); } /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ var m_ = new forge.util.ByteBuffer(); m_.fillWithByte(0, 8); m_.putBytes(mHash); m_.putBytes(salt); /* 6. Let H = Hash(M'), an octet string of length hLen. */ hash.start(); hash.update(m_.getBytes()); var h = hash.digest().getBytes(); /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 * zero octets. The length of PS may be 0. */ var ps = new forge.util.ByteBuffer(); ps.fillWithByte(0, emLen - sLen - hLen - 2); /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length * emLen - hLen - 1. */ ps.putByte(0x01); ps.putBytes(salt); var db = ps.getBytes(); /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ var maskLen = emLen - hLen - 1; var dbMask = mgf.generate(h, maskLen); /* 10. Let maskedDB = DB \xor dbMask. */ var maskedDB = ''; for(i = 0; i < maskLen; i++) { maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); } /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in * maskedDB to zero. */ var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); /* 12. Let EM = maskedDB || H || 0xbc. * 13. Output EM. */ return maskedDB + h + String.fromCharCode(0xbc); }; /** * Verifies a PSS signature. * * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. * * @param mHash the message digest hash, as a binary-encoded string, to * compare against the signature. * @param em the encoded message, as a binary-encoded string * (RSA decryption result). * @param modsBits the length of the RSA modulus in bits. * * @return true if the signature was verified, false if not. */ pssobj.verify = function(mHash, em, modBits) { var i; var emBits = modBits - 1; var emLen = Math.ceil(emBits / 8); /* c. Convert the message representative m to an encoded message EM * of length emLen = ceil((modBits - 1) / 8) octets, where modBits * is the length in bits of the RSA modulus n */ em = em.substr(-emLen); /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ if(emLen < hLen + sLen + 2) { throw new Error('Inconsistent parameters to PSS signature verification.'); } /* 4. If the rightmost octet of EM does not have hexadecimal value * 0xbc, output "inconsistent" and stop. */ if(em.charCodeAt(emLen - 1) !== 0xbc) { throw new Error('Encoded message does not end in 0xBC.'); } /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and * let H be the next hLen octets. */ var maskLen = emLen - hLen - 1; var maskedDB = em.substr(0, maskLen); var h = em.substr(maskLen, hLen); /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in * maskedDB are not all equal to zero, output "inconsistent" and stop. */ var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; if((maskedDB.charCodeAt(0) & mask) !== 0) { throw new Error('Bits beyond keysize not zero as expected.'); } /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ var dbMask = mgf.generate(h, maskLen); /* 8. Let DB = maskedDB \xor dbMask. */ var db = ''; for(i = 0; i < maskLen; i++) { db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); } /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet * in DB to zero. */ db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero * or if the octet at position emLen - hLen - sLen - 1 (the leftmost * position is "position 1") does not have hexadecimal value 0x01, * output "inconsistent" and stop. */ var checkLen = emLen - hLen - sLen - 2; for(i = 0; i < checkLen; i++) { if(db.charCodeAt(i) !== 0x00) { throw new Error('Leftmost octets not zero as expected'); } } if(db.charCodeAt(checkLen) !== 0x01) { throw new Error('Inconsistent PSS signature, 0x01 marker not found'); } /* 11. Let salt be the last sLen octets of DB. */ var salt = db.substr(-sLen); /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ var m_ = new forge.util.ByteBuffer(); m_.fillWithByte(0, 8); m_.putBytes(mHash); m_.putBytes(salt); /* 13. Let H' = Hash(M'), an octet string of length hLen. */ hash.start(); hash.update(m_.getBytes()); var h_ = hash.digest().getBytes(); /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ return h === h_; }; return pssobj; };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/rsa.js
aws/lti-middleware/node_modules/node-forge/lib/rsa.js
/** * Javascript implementation of basic RSA algorithms. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. * * The only algorithm currently supported for PKI is RSA. * * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier * and a subjectPublicKey of type bit string. * * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters * for the algorithm, if any. In the case of RSA, there aren't any. * * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING * } * * AlgorithmIdentifer ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * For an RSA public key, the subjectPublicKey is: * * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * * PrivateKeyInfo ::= SEQUENCE { * version Version, * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, * privateKey PrivateKey, * attributes [0] IMPLICIT Attributes OPTIONAL * } * * Version ::= INTEGER * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier * PrivateKey ::= OCTET STRING * Attributes ::= SET OF Attribute * * An RSA private key as the following structure: * * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER -- (inverse of q) mod p * } * * Version ::= INTEGER * * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 */ var forge = require('./forge'); require('./asn1'); require('./jsbn'); require('./oids'); require('./pkcs1'); require('./prime'); require('./random'); require('./util'); if(typeof BigInteger === 'undefined') { var BigInteger = forge.jsbn.BigInteger; } var _crypto = forge.util.isNodejs ? require('crypto') : null; // shortcut for asn.1 API var asn1 = forge.asn1; // shortcut for util API var util = forge.util; /* * RSA encryption and decryption, see RFC 2313. */ forge.pki = forge.pki || {}; module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; var pki = forge.pki; // for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; // validator for a PrivateKeyInfo structure var privateKeyValidator = { // PrivateKeyInfo name: 'PrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // Version (INTEGER) name: 'PrivateKeyInfo.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyVersion' }, { // privateKeyAlgorithm name: 'PrivateKeyInfo.privateKeyAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'privateKeyOid' }] }, { // PrivateKey name: 'PrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'privateKey' }] }; // validator for an RSA private key var rsaPrivateKeyValidator = { // RSAPrivateKey name: 'RSAPrivateKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // Version (INTEGER) name: 'RSAPrivateKey.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyVersion' }, { // modulus (n) name: 'RSAPrivateKey.modulus', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyModulus' }, { // publicExponent (e) name: 'RSAPrivateKey.publicExponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPublicExponent' }, { // privateExponent (d) name: 'RSAPrivateKey.privateExponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrivateExponent' }, { // prime1 (p) name: 'RSAPrivateKey.prime1', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrime1' }, { // prime2 (q) name: 'RSAPrivateKey.prime2', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrime2' }, { // exponent1 (d mod (p-1)) name: 'RSAPrivateKey.exponent1', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyExponent1' }, { // exponent2 (d mod (q-1)) name: 'RSAPrivateKey.exponent2', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyExponent2' }, { // coefficient ((inverse of q) mod p) name: 'RSAPrivateKey.coefficient', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyCoefficient' }] }; // validator for an RSA public key var rsaPublicKeyValidator = { // RSAPublicKey name: 'RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // modulus (n) name: 'RSAPublicKey.modulus', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'publicKeyModulus' }, { // publicExponent (e) name: 'RSAPublicKey.exponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'publicKeyExponent' }] }; // validator for an SubjectPublicKeyInfo structure // Note: Currently only works with an RSA public key var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { name: 'SubjectPublicKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'subjectPublicKeyInfo', value: [{ name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'publicKeyOid' }] }, { // subjectPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, value: [{ // RSAPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, optional: true, captureAsn1: 'rsaPublicKey' }] }] }; // validator for a DigestInfo structure var digestInfoValidator = { name: 'DigestInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'DigestInfo.DigestAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'algorithmIdentifier' }, { // NULL paramters name: 'DigestInfo.DigestAlgorithm.parameters', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.NULL, // captured only to check existence for md2 and md5 capture: 'parameters', optional: true, constructed: false }] }, { // digest name: 'DigestInfo.digest', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'digest' }] }; /** * Wrap digest in DigestInfo object. * * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * @param md the message digest object with the hash to sign. * * @return the encoded message (ready for RSA encrytion) */ var emsaPkcs1v15encode = function(md) { // get the oid for the algorithm var oid; if(md.algorithm in pki.oids) { oid = pki.oids[md.algorithm]; } else { var error = new Error('Unknown message digest algorithm.'); error.algorithm = md.algorithm; throw error; } var oidBytes = asn1.oidToDer(oid).getBytes(); // create the digest info var digestInfo = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); var digestAlgorithm = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); var digest = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, md.digest().getBytes()); digestInfo.value.push(digestAlgorithm); digestInfo.value.push(digest); // encode digest info return asn1.toDer(digestInfo).getBytes(); }; /** * Performs x^c mod n (RSA encryption or decryption operation). * * @param x the number to raise and mod. * @param key the key to use. * @param pub true if the key is public, false if private. * * @return the result of x^c mod n. */ var _modPow = function(x, key, pub) { if(pub) { return x.modPow(key.e, key.n); } if(!key.p || !key.q) { // allow calculation without CRT params (slow) return x.modPow(key.d, key.n); } // pre-compute dP, dQ, and qInv if necessary if(!key.dP) { key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); } if(!key.dQ) { key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); } if(!key.qInv) { key.qInv = key.q.modInverse(key.p); } /* Chinese remainder theorem (CRT) states: Suppose n1, n2, ..., nk are positive integers which are pairwise coprime (n1 and n2 have no common factors other than 1). For any integers x1, x2, ..., xk there exists an integer x solving the system of simultaneous congruences (where ~= means modularly congruent so a ~= b mod n means a mod n = b mod n): x ~= x1 mod n1 x ~= x2 mod n2 ... x ~= xk mod nk This system of congruences has a single simultaneous solution x between 0 and n - 1. Furthermore, each xk solution and x itself is congruent modulo the product n = n1*n2*...*nk. So x1 mod n = x2 mod n = xk mod n = x mod n. The single simultaneous solution x can be solved with the following equation: x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. Where x is less than n, xi = x mod ni. For RSA we are only concerned with k = 2. The modulus n = pq, where p and q are coprime. The RSA decryption algorithm is: y = x^d mod n Given the above: x1 = x^d mod p r1 = n/p = q s1 = q^-1 mod p x2 = x^d mod q r2 = n/q = p s2 = p^-1 mod q So y = (x1r1s1 + x2r2s2) mod n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n According to Fermat's Little Theorem, if the modulus P is prime, for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. Since A is not divisible by P it follows that if: N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort to calculate). In order to calculate x^d mod p more quickly the exponent d mod (p - 1) is stored in the RSA private key (the same is done for x^d mod q). These values are referred to as dP and dQ respectively. Therefore we now have: y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n Since we'll be reducing x^dP by modulo p (same for q) we can also reduce x by p (and q respectively) before hand. Therefore, let xp = ((x mod p)^dP mod p), and xq = ((x mod q)^dQ mod q), yielding: y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n This can be further reduced to a simple algorithm that only requires 1 inverse (the q inverse is used) to be used and stored. The algorithm is called Garner's algorithm. If qInv is the inverse of q, we simply calculate: y = (qInv*(xp - xq) mod p) * q + xq However, there are two further complications. First, we need to ensure that xp > xq to prevent signed BigIntegers from being used so we add p until this is true (since we will be mod'ing with p anyway). Then, there is a known timing attack on algorithms using the CRT. To mitigate this risk, "cryptographic blinding" should be used. This requires simply generating a random number r between 0 and n-1 and its inverse and multiplying x by r^e before calculating y and then multiplying y by r^-1 afterwards. Note that r must be coprime with n (gcd(r, n) === 1) in order to have an inverse. */ // cryptographic blinding var r; do { r = new BigInteger( forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), 16); } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); // calculate xp and xq var xp = x.mod(key.p).modPow(key.dP, key.p); var xq = x.mod(key.q).modPow(key.dQ, key.q); // xp must be larger than xq to avoid signed bit usage while(xp.compareTo(xq) < 0) { xp = xp.add(key.p); } // do last step var y = xp.subtract(xq) .multiply(key.qInv).mod(key.p) .multiply(key.q).add(xq); // remove effect of random for cryptographic blinding y = y.multiply(r.modInverse(key.n)).mod(key.n); return y; }; /** * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or * 'encrypt' on a public key object instead. * * Performs RSA encryption. * * The parameter bt controls whether to put padding bytes before the * message passed in. Set bt to either true or false to disable padding * completely (in order to handle e.g. EMSA-PSS encoding seperately before), * signaling whether the encryption operation is a public key operation * (i.e. encrypting data) or not, i.e. private key operation (data signing). * * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 * (for signing) or 0x02 (for encryption). The key operation mode (private * or public) is derived from this flag in that case). * * @param m the message to encrypt as a byte string. * @param key the RSA key to use. * @param bt for PKCS#1 v1.5 padding, the block type to use * (0x01 for private key, 0x02 for public), * to disable padding: true = public key, false = private key. * * @return the encrypted bytes as a string. */ pki.rsa.encrypt = function(m, key, bt) { var pub = bt; var eb; // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); if(bt !== false && bt !== true) { // legacy, default to PKCS#1 v1.5 padding pub = (bt === 0x02); eb = _encodePkcs1_v1_5(m, key, bt); } else { eb = forge.util.createBuffer(); eb.putBytes(m); } // load encryption block as big integer 'x' // FIXME: hex conversion inefficient, get BigInteger w/byte strings var x = new BigInteger(eb.toHex(), 16); // do RSA encryption var y = _modPow(x, key, pub); // convert y into the encrypted data byte string, if y is shorter in // bytes than k, then prepend zero bytes to fill up ed // FIXME: hex conversion inefficient, get BigInteger w/byte strings var yhex = y.toString(16); var ed = forge.util.createBuffer(); var zeros = k - Math.ceil(yhex.length / 2); while(zeros > 0) { ed.putByte(0x00); --zeros; } ed.putBytes(forge.util.hexToBytes(yhex)); return ed.getBytes(); }; /** * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or * 'verify' on a public key object instead. * * Performs RSA decryption. * * The parameter ml controls whether to apply PKCS#1 v1.5 padding * or not. Set ml = false to disable padding removal completely * (in order to handle e.g. EMSA-PSS later on) and simply pass back * the RSA encryption block. * * @param ed the encrypted data to decrypt in as a byte string. * @param key the RSA key to use. * @param pub true for a public key operation, false for private. * @param ml the message length, if known, false to disable padding. * * @return the decrypted message as a byte string. */ pki.rsa.decrypt = function(ed, key, pub, ml) { // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); // error if the length of the encrypted data ED is not k if(ed.length !== k) { var error = new Error('Encrypted message length is invalid.'); error.length = ed.length; error.expected = k; throw error; } // convert encrypted data into a big integer // FIXME: hex conversion inefficient, get BigInteger w/byte strings var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); // y must be less than the modulus or it wasn't the result of // a previous mod operation (encryption) using that modulus if(y.compareTo(key.n) >= 0) { throw new Error('Encrypted message is invalid.'); } // do RSA decryption var x = _modPow(y, key, pub); // create the encryption block, if x is shorter in bytes than k, then // prepend zero bytes to fill up eb // FIXME: hex conversion inefficient, get BigInteger w/byte strings var xhex = x.toString(16); var eb = forge.util.createBuffer(); var zeros = k - Math.ceil(xhex.length / 2); while(zeros > 0) { eb.putByte(0x00); --zeros; } eb.putBytes(forge.util.hexToBytes(xhex)); if(ml !== false) { // legacy, default to PKCS#1 v1.5 padding return _decodePkcs1_v1_5(eb.getBytes(), key, pub); } // return message return eb.getBytes(); }; /** * Creates an RSA key-pair generation state object. It is used to allow * key-generation to be performed in steps. It also allows for a UI to * display progress updates. * * @param bits the size for the private key in bits, defaults to 2048. * @param e the public exponent to use, defaults to 65537 (0x10001). * @param [options] the options to use. * prng a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". * algorithm the algorithm to use (default: 'PRIMEINC'). * * @return the state object to use to generate the key-pair. */ pki.rsa.createKeyPairGenerationState = function(bits, e, options) { // TODO: migrate step-based prime generation code to forge.prime // set default bits if(typeof(bits) === 'string') { bits = parseInt(bits, 10); } bits = bits || 2048; // create prng with api that matches BigInteger secure random options = options || {}; var prng = options.prng || forge.random; var rng = { // x is an array to fill with bytes nextBytes: function(x) { var b = prng.getBytesSync(x.length); for(var i = 0; i < x.length; ++i) { x[i] = b.charCodeAt(i); } } }; var algorithm = options.algorithm || 'PRIMEINC'; // create PRIMEINC algorithm state var rval; if(algorithm === 'PRIMEINC') { rval = { algorithm: algorithm, state: 0, bits: bits, rng: rng, eInt: e || 65537, e: new BigInteger(null), p: null, q: null, qBits: bits >> 1, pBits: bits - (bits >> 1), pqState: 0, num: null, keys: null }; rval.e.fromInt(rval.eInt); } else { throw new Error('Invalid key generation algorithm: ' + algorithm); } return rval; }; /** * Attempts to runs the key-generation algorithm for at most n seconds * (approximately) using the given state. When key-generation has completed, * the keys will be stored in state.keys. * * To use this function to update a UI while generating a key or to prevent * causing browser lockups/warnings, set "n" to a value other than 0. A * simple pattern for generating a key and showing a progress indicator is: * * var state = pki.rsa.createKeyPairGenerationState(2048); * var step = function() { * // step key-generation, run algorithm for 100 ms, repeat * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { * setTimeout(step, 1); * } else { * // key-generation complete * // TODO: turn off progress indicator here * // TODO: use the generated key-pair in "state.keys" * } * }; * // TODO: turn on progress indicator here * setTimeout(step, 0); * * @param state the state to use. * @param n the maximum number of milliseconds to run the algorithm for, 0 * to run the algorithm to completion. * * @return true if the key-generation completed, false if not. */ pki.rsa.stepKeyPairGenerationState = function(state, n) { // set default algorithm if not set if(!('algorithm' in state)) { state.algorithm = 'PRIMEINC'; } // TODO: migrate step-based prime generation code to forge.prime // TODO: abstract as PRIMEINC algorithm // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) // with some minor optimizations and designed to run in steps // local state vars var THIRTY = new BigInteger(null); THIRTY.fromInt(30); var deltaIdx = 0; var op_or = function(x, y) {return x | y;}; // keep stepping until time limit is reached or done var t1 = +new Date(); var t2; var total = 0; while(state.keys === null && (n <= 0 || total < n)) { // generate p or q if(state.state === 0) { /* Note: All primes are of the form: 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i When we generate a random number, we always align it at 30k + 1. Each time the number is determined not to be prime we add to get to the next 'i', eg: if the number was at 30k + 1 we add 6. */ var bits = (state.p === null) ? state.pBits : state.qBits; var bits1 = bits - 1; // get a random number if(state.pqState === 0) { state.num = new BigInteger(bits, state.rng); // force MSB set if(!state.num.testBit(bits1)) { state.num.bitwiseTo( BigInteger.ONE.shiftLeft(bits1), op_or, state.num); } // align number on 30k+1 boundary state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); deltaIdx = 0; ++state.pqState; } else if(state.pqState === 1) { // try to make the number a prime if(state.num.bitLength() > bits) { // overflow, try again state.pqState = 0; // do primality test } else if(state.num.isProbablePrime( _getMillerRabinTests(state.num.bitLength()))) { ++state.pqState; } else { // get next potential prime state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); } } else if(state.pqState === 2) { // ensure number is coprime with e state.pqState = (state.num.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) === 0) ? 3 : 0; } else if(state.pqState === 3) { // store p or q state.pqState = 0; if(state.p === null) { state.p = state.num; } else { state.q = state.num; } // advance state if both p and q are ready if(state.p !== null && state.q !== null) { ++state.state; } state.num = null; } } else if(state.state === 1) { // ensure p is larger than q (swap them if not) if(state.p.compareTo(state.q) < 0) { state.num = state.p; state.p = state.q; state.q = state.num; } ++state.state; } else if(state.state === 2) { // compute phi: (p - 1)(q - 1) (Euler's totient function) state.p1 = state.p.subtract(BigInteger.ONE); state.q1 = state.q.subtract(BigInteger.ONE); state.phi = state.p1.multiply(state.q1); ++state.state; } else if(state.state === 3) { // ensure e and phi are coprime if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { // phi and e are coprime, advance ++state.state; } else { // phi and e aren't coprime, so generate a new p and q state.p = null; state.q = null; state.state = 0; } } else if(state.state === 4) { // create n, ensure n is has the right number of bits state.n = state.p.multiply(state.q); // ensure n is right number of bits if(state.n.bitLength() === state.bits) { // success, advance ++state.state; } else { // failed, get new q state.q = null; state.state = 0; } } else if(state.state === 5) { // set keys var d = state.e.modInverse(state.phi); state.keys = { privateKey: pki.rsa.setPrivateKey( state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), publicKey: pki.rsa.setPublicKey(state.n, state.e) }; } // update timing t2 = +new Date(); total += t2 - t1; t1 = t2; } return state.keys !== null; }; /** * Generates an RSA public-private key pair in a single call. * * To generate a key-pair in steps (to allow for progress updates and to * prevent blocking or warnings in slow browsers) then use the key-pair * generation state functions. * * To generate a key-pair asynchronously (either through web-workers, if * available, or by breaking up the work on the main thread), pass a * callback function. * * @param [bits] the size for the private key in bits, defaults to 2048. * @param [e] the public exponent to use, defaults to 65537. * @param [options] options for key-pair generation, if given then 'bits' * and 'e' must *not* be given: * bits the size for the private key in bits, (default: 2048). * e the public exponent to use, (default: 65537 (0x10001)). * workerScript the worker script URL. * workers the number of web workers (if supported) to use, * (default: 2). * workLoad the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * prng a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". Disables use of native APIs. * algorithm the algorithm to use (default: 'PRIMEINC'). * @param [callback(err, keypair)] called once the operation completes. * * @return an object with privateKey and publicKey properties. */ pki.rsa.generateKeyPair = function(bits, e, options, callback) { // (bits), (options), (callback) if(arguments.length === 1) { if(typeof bits === 'object') { options = bits; bits = undefined; } else if(typeof bits === 'function') { callback = bits; bits = undefined; } } else if(arguments.length === 2) { // (bits, e), (bits, options), (bits, callback), (options, callback) if(typeof bits === 'number') { if(typeof e === 'function') { callback = e; e = undefined; } else if(typeof e !== 'number') { options = e; e = undefined; } } else { options = bits; callback = e; bits = undefined; e = undefined; } } else if(arguments.length === 3) { // (bits, e, options), (bits, e, callback), (bits, options, callback) if(typeof e === 'number') { if(typeof options === 'function') { callback = options; options = undefined; } } else { callback = options; options = e; e = undefined; } } options = options || {}; if(bits === undefined) { bits = options.bits || 2048; } if(e === undefined) { e = options.e || 0x10001; } // use native code if permitted, available, and parameters are acceptable if(!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { if(callback) { // try native async if(_detectNodeCrypto('generateKeyPair')) { return _crypto.generateKeyPair('rsa', { modulusLength: bits, publicExponent: e, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, function(err, pub, priv) { if(err) { return callback(err); } callback(null, { privateKey: pki.privateKeyFromPem(priv), publicKey: pki.publicKeyFromPem(pub) }); }); } if(_detectSubtleCrypto('generateKey') && _detectSubtleCrypto('exportKey')) { // use standard native generateKey return util.globalScope.crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: bits, publicExponent: _intToUint8Array(e), hash: {name: 'SHA-256'} }, true /* key can be exported*/, ['sign', 'verify']) .then(function(pair) { return util.globalScope.crypto.subtle.exportKey( 'pkcs8', pair.privateKey); // avoiding catch(function(err) {...}) to support IE <= 8 }).then(undefined, function(err) { callback(err); }).then(function(pkcs8) { if(pkcs8) { var privateKey = pki.privateKeyFromAsn1( asn1.fromDer(forge.util.createBuffer(pkcs8))); callback(null, { privateKey: privateKey, publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) }); } }); } if(_detectSubtleMsCrypto('generateKey') && _detectSubtleMsCrypto('exportKey')) { var genOp = util.globalScope.msCrypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: bits, publicExponent: _intToUint8Array(e), hash: {name: 'SHA-256'} }, true /* key can be exported*/, ['sign', 'verify']); genOp.oncomplete = function(e) { var pair = e.target.result; var exportOp = util.globalScope.msCrypto.subtle.exportKey( 'pkcs8', pair.privateKey); exportOp.oncomplete = function(e) { var pkcs8 = e.target.result; var privateKey = pki.privateKeyFromAsn1( asn1.fromDer(forge.util.createBuffer(pkcs8))); callback(null, { privateKey: privateKey, publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) }); }; exportOp.onerror = function(err) { callback(err); }; }; genOp.onerror = function(err) { callback(err); }; return; } } else { // try native sync if(_detectNodeCrypto('generateKeyPairSync')) { var keypair = _crypto.generateKeyPairSync('rsa', { modulusLength: bits, publicExponent: e, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); return { privateKey: pki.privateKeyFromPem(keypair.privateKey), publicKey: pki.publicKeyFromPem(keypair.publicKey) }; } } } // use JavaScript implementation var state = pki.rsa.createKeyPairGenerationState(bits, e, options); if(!callback) { pki.rsa.stepKeyPairGenerationState(state, 0); return state.keys; } _generateKeyPair(state, options, callback); }; /** * Sets an RSA public key from BigIntegers modulus and exponent. * * @param n the modulus. * @param e the exponent. * * @return the public key. */ pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { var key = { n: n, e: e }; /** * Encrypts the given data with this public key. Newer applications * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for * legacy applications. * * @param data the byte string to encrypt.
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/md.js
aws/lti-middleware/node_modules/node-forge/lib/md.js
/** * Node.js module for Forge message digests. * * @author Dave Longley * * Copyright 2011-2017 Digital Bazaar, Inc. */ var forge = require('./forge'); module.exports = forge.md = forge.md || {}; forge.md.algorithms = forge.md.algorithms || {};
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/jsbn.js
aws/lti-middleware/node_modules/node-forge/lib/jsbn.js
// Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. /* Licensing (LICENSE) ------------------- This software is covered under the following copyright: */ /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ /* Address all questions regarding this license to: Tom Wu [email protected] */ var forge = require('./forge'); module.exports = forge.jsbn = forge.jsbn || {}; // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { this.data = []; if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } forge.jsbn.BigInteger = BigInteger; // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this.data[i++]+w.data[j]+c; c = Math.floor(v/0x4000000); w.data[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this.data[i]&0x7fff; var h = this.data[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.data[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this.data[i]&0x3fff; var h = this.data[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; c = (l>>28)+(m>>14)+xh*h; w.data[j++] = l&0xfffffff; } return c; } // node.js (no browser) if(typeof(navigator) === 'undefined') { BigInteger.prototype.am = am3; dbits = 28; } else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this.data[0] = x; else if(x < -1) this.data[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this.data[this.t++] = x; else if(sh+k > this.DB) { this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this.data[this.t++] = (x>>(this.DB-sh)); } else this.data[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this.data[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = "", i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this.data[i]&((1<<p)-1))<<(k-p); d |= this.data[--i]>>(p+=this.DB-k); } else { d = (this.data[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; for(i = n-1; i >= 0; --i) r.data[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r.data[i+ds+1] = (this.data[i]>>cbs)|c; c = (this.data[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r.data[i] = 0; r.data[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r.data[0] = this.data[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r.data[i-ds-1] |= (this.data[i]&bm)<<cbs; r.data[i-ds] = this.data[i]>>bs; } if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this.data[i]-a.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r.data[i++] = this.DV+c; else if(c > 0) r.data[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r.data[i] = 0; for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r.data[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x.data[i],r,2*i,0,1); if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r.data[i+x.t] -= x.DV; r.data[i+x.t+1] = 1; } } if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y.data[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y.data[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r.data[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y.data[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r.data[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this.data[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x.data[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x.data[i]*mp mod DV var j = x.data[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1<<i)) > 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // jsbn2 lib //Copyright (c) 2005-2009 Tom Wu //All Rights Reserved. //See "LICENSE" for details (See jsbn.js for LICENSE). //Extended JavaScript BN functions, required for RSA private ops. //Version 1.1: new BigInteger("0", 10) returns "proper" zero //(public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } //(public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this.data[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this.data[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this.data[1]&((1<<(32-this.DB))-1))<<this.DB)|this.data[0]; } //(public) return value as byte function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; } //(public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } //(protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } //(public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; else return 1; } //(protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } //(protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } //(protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; this.fromString(x,256); } } //(public) convert to bigendian byte array function bnToByteArray() { var i = this.t, r = new Array(); r[0] = this.s; var p = this.DB-(i*this.DB)%8, d, k = 0; if(i-- > 0) { if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this.data[i]&((1<<p)-1))<<(8-p); d |= this.data[--i]>>(p+=this.DB-8); } else { d = (this.data[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } //(protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } //(public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } //(public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } //(public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } //(public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } //(public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; r.t = this.t; r.s = ~this.s; return r; } //(public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } //(public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } //return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } //(public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); if(this.s < 0) return this.t*this.DB; return -1; } //return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } //(public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); return r; } //(public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this.data[j]&(1<<(n%this.DB)))!=0); } //(protected) this op (1<<n) function bnpChangeBit(n,op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r,op,r); return r; } //(public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n,op_or); } //(public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n,op_andnot); } //(public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n,op_xor); } //(protected) r = this + a function bnpAddTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this.data[i]+a.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a.data[i]; r.data[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r.data[i++] = c; else if(c < -1) r.data[i++] = this.DV+c; r.t = i; r.clamp(); } //(public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } //(public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } //(public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } //(public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } //(public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } //(public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } //(protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this.data[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } //(protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this.data[this.t++] = 0; this.data[w] += n; while(this.data[w] >= this.DV) { this.data[w] -= this.DV; if(++w >= this.t) this.data[this.t++] = 0; ++this.data[w]; } } //A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; //(public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } //(protected) r = lower n words of "this * a", a.t <= n //"this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r.data[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); r.clamp(); } //(protected) r = "this * a" without lower n words, n > 0 //"this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r.data[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } //Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } //x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } //r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } //r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; //(public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1; g[1] = z.convert(this); if(k > 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e.data[j])-1; while(j >= 0) { if(i >= k1) w = (e.data[j]>>(i-k1))&km; else { w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e.data[j]&(1<<i)) == 0) { z.sqrTo(r,r2); t = r; r = r2; r2 = t; if(--i < 0) { i = this.DB-1; --j; } } } return z.revert(r); } //(public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } //(protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this.data[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; return r; } //(public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; //(public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x.data[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } //(protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); var prng = bnGetPrng(); var a; for(var i = 0; i < t; ++i) { // select witness 'a' at random from between 1 and n1 do { a = new BigInteger(this.bitLength(), prng); } while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // get pseudo random number generator function bnGetPrng() { // create prng with api that matches BigInteger secure random return {
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/pki.js
aws/lti-middleware/node_modules/node-forge/lib/pki.js
/** * Javascript implementation of a basic Public Key Infrastructure, including * support for RSA public and private keys. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./asn1'); require('./oids'); require('./pbe'); require('./pem'); require('./pbkdf2'); require('./pkcs12'); require('./pss'); require('./rsa'); require('./util'); require('./x509'); // shortcut for asn.1 API var asn1 = forge.asn1; /* Public Key Infrastructure (PKI) implementation. */ var pki = module.exports = forge.pki = forge.pki || {}; /** * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. * * Converts PEM-formatted data to DER. * * @param pem the PEM-formatted data. * * @return the DER-formatted data. */ pki.pemToDer = function(pem) { var msg = forge.pem.decode(pem)[0]; if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error('Could not convert PEM to DER; PEM is encrypted.'); } return forge.util.createBuffer(msg.body); }; /** * Converts an RSA private key from PEM format. * * @param pem the PEM-formatted private key. * * @return the private key. */ pki.privateKeyFromPem = function(pem) { var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { var error = new Error('Could not convert private key from PEM; PEM ' + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); error.headerType = msg.type; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error('Could not convert private key from PEM; PEM is encrypted.'); } // convert DER to ASN.1 object var obj = asn1.fromDer(msg.body); return pki.privateKeyFromAsn1(obj); }; /** * Converts an RSA private key to PEM format. * * @param key the private key. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted private key. */ pki.privateKeyToPem = function(key, maxline) { // convert to ASN.1, then DER, then PEM-encode var msg = { type: 'RSA PRIVATE KEY', body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); }; /** * Converts a PrivateKeyInfo to PEM format. * * @param pki the PrivateKeyInfo. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted private key. */ pki.privateKeyInfoToPem = function(pki, maxline) { // convert to DER, then PEM-encode var msg = { type: 'PRIVATE KEY', body: asn1.toDer(pki).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/prime.js
aws/lti-middleware/node_modules/node-forge/lib/prime.js
/** * Prime number generation API. * * @author Dave Longley * * Copyright (c) 2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); require('./jsbn'); require('./random'); (function() { // forge.prime already defined if(forge.prime) { module.exports = forge.prime; return; } /* PRIME API */ var prime = module.exports = forge.prime = forge.prime || {}; var BigInteger = forge.jsbn.BigInteger; // primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; var THIRTY = new BigInteger(null); THIRTY.fromInt(30); var op_or = function(x, y) {return x|y;}; /** * Generates a random probable prime with the given number of bits. * * Alternative algorithms can be specified by name as a string or as an * object with custom options like so: * * { * name: 'PRIMEINC', * options: { * maxBlockTime: <the maximum amount of time to block the main * thread before allowing I/O other JS to run>, * millerRabinTests: <the number of miller-rabin tests to run>, * workerScript: <the worker script URL>, * workers: <the number of web workers (if supported) to use, * -1 to use estimated cores minus one>. * workLoad: the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * } * } * * @param bits the number of bits for the prime number. * @param options the options to use. * [algorithm] the algorithm to use (default: 'PRIMEINC'). * [prng] a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". * * @return callback(err, num) called once the operation completes. */ prime.generateProbablePrime = function(bits, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; // default to PRIMEINC algorithm var algorithm = options.algorithm || 'PRIMEINC'; if(typeof algorithm === 'string') { algorithm = {name: algorithm}; } algorithm.options = algorithm.options || {}; // create prng with api that matches BigInteger secure random var prng = options.prng || forge.random; var rng = { // x is an array to fill with bytes nextBytes: function(x) { var b = prng.getBytesSync(x.length); for(var i = 0; i < x.length; ++i) { x[i] = b.charCodeAt(i); } } }; if(algorithm.name === 'PRIMEINC') { return primeincFindPrime(bits, rng, algorithm.options, callback); } throw new Error('Invalid prime generation algorithm: ' + algorithm.name); }; function primeincFindPrime(bits, rng, options, callback) { if('workers' in options) { return primeincFindPrimeWithWorkers(bits, rng, options, callback); } return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); } function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { // initialize random number var num = generateRandom(bits, rng); /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The number we are given is always aligned at 30k + 1. Each time the number is determined not to be prime we add to get to the next 'i', eg: if the number was at 30k + 1 we add 6. */ var deltaIdx = 0; // get required number of MR tests var mrTests = getMillerRabinTests(num.bitLength()); if('millerRabinTests' in options) { mrTests = options.millerRabinTests; } // find prime nearest to 'num' for maxBlockTime ms // 10 ms gives 5ms of leeway for other calculations before dropping // below 60fps (1000/60 == 16.67), but in reality, the number will // likely be higher due to an 'atomic' big int modPow var maxBlockTime = 10; if('maxBlockTime' in options) { maxBlockTime = options.maxBlockTime; } _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); } function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { var start = +new Date(); do { // overflow, regenerate random number if(num.bitLength() > bits) { num = generateRandom(bits, rng); } // do primality test if(num.isProbablePrime(mrTests)) { return callback(null, num); } // get next potential prime num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); // keep trying later forge.util.setImmediate(function() { _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); }); } // NOTE: This algorithm is indeterminate in nature because workers // run in parallel looking at different segments of numbers. Even if this // algorithm is run twice with the same input from a predictable RNG, it // may produce different outputs. function primeincFindPrimeWithWorkers(bits, rng, options, callback) { // web workers unavailable if(typeof Worker === 'undefined') { return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); } // initialize random number var num = generateRandom(bits, rng); // use web workers to generate keys var numWorkers = options.workers; var workLoad = options.workLoad || 100; var range = workLoad * 30 / 8; var workerScript = options.workerScript || 'forge/prime.worker.js'; if(numWorkers === -1) { return forge.util.estimateCores(function(err, cores) { if(err) { // default to 2 cores = 2; } numWorkers = cores - 1; generate(); }); } generate(); function generate() { // require at least 1 worker numWorkers = Math.max(1, numWorkers); // TODO: consider optimizing by starting workers outside getPrime() ... // note that in order to clean up they will have to be made internally // asynchronous which may actually be slower // start workers immediately var workers = []; for(var i = 0; i < numWorkers; ++i) { // FIXME: fix path or use blob URLs workers[i] = new Worker(workerScript); } var running = numWorkers; // listen for requests from workers and assign ranges to find prime for(var i = 0; i < numWorkers; ++i) { workers[i].addEventListener('message', workerMessage); } /* Note: The distribution of random numbers is unknown. Therefore, each web worker is continuously allocated a range of numbers to check for a random number until one is found. Every 30 numbers will be checked just 8 times, because prime numbers have the form: 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) Therefore, if we want a web worker to run N checks before asking for a new range of numbers, each range must contain N*30/8 numbers. For 100 checks (workLoad), this is a range of 375. */ var found = false; function workerMessage(e) { // ignore message, prime already found if(found) { return; } --running; var data = e.data; if(data.found) { // terminate all workers for(var i = 0; i < workers.length; ++i) { workers[i].terminate(); } found = true; return callback(null, new BigInteger(data.prime, 16)); } // overflow, regenerate random number if(num.bitLength() > bits) { num = generateRandom(bits, rng); } // assign new range to check var hex = num.toString(16); // start prime search e.target.postMessage({ hex: hex, workLoad: workLoad }); num.dAddOffset(range, 0); } } } /** * Generates a random number using the given number of bits and RNG. * * @param bits the number of bits for the number. * @param rng the random number generator to use. * * @return the random number. */ function generateRandom(bits, rng) { var num = new BigInteger(bits, rng); // force MSB set var bits1 = bits - 1; if(!num.testBit(bits1)) { num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); } // align number on 30k+1 boundary num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); return num; } /** * Returns the required number of Miller-Rabin tests to generate a * prime with an error probability of (1/2)^80. * * See Handbook of Applied Cryptography Chapter 4, Table 4.4. * * @param bits the bit size. * * @return the required number of iterations. */ function getMillerRabinTests(bits) { if(bits <= 100) return 27; if(bits <= 150) return 18; if(bits <= 200) return 15; if(bits <= 250) return 12; if(bits <= 300) return 9; if(bits <= 350) return 8; if(bits <= 400) return 7; if(bits <= 500) return 6; if(bits <= 600) return 5; if(bits <= 800) return 4; if(bits <= 1250) return 3; return 2; } })();
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/http.js
aws/lti-middleware/node_modules/node-forge/lib/http.js
/** * HTTP client-side implementation that uses forge.net sockets. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. All rights reserved. */ var forge = require('./forge'); require('./tls'); require('./util'); // define http namespace var http = module.exports = forge.http = forge.http || {}; // logging category var cat = 'forge.http'; // normalizes an http header field name var _normalize = function(name) { return name.toLowerCase().replace(/(^.)|(-.)/g, function(a) {return a.toUpperCase();}); }; /** * Gets the local storage ID for the given client. * * @param client the client to get the local storage ID for. * * @return the local storage ID to use. */ var _getStorageId = function(client) { // TODO: include browser in ID to avoid sharing cookies between // browsers (if this is undesirable) // navigator.userAgent return 'forge.http.' + client.url.protocol.slice(0, -1) + '.' + client.url.hostname + '.' + client.url.port; }; /** * Loads persistent cookies from disk for the given client. * * @param client the client. */ var _loadCookies = function(client) { if(client.persistCookies) { try { var cookies = forge.util.getItem( client.socketPool.flashApi, _getStorageId(client), 'cookies'); client.cookies = cookies || {}; } catch(ex) { // no flash storage available, just silently fail // TODO: i assume we want this logged somewhere or // should it actually generate an error //forge.log.error(cat, ex); } } }; /** * Saves persistent cookies on disk for the given client. * * @param client the client. */ var _saveCookies = function(client) { if(client.persistCookies) { try { forge.util.setItem( client.socketPool.flashApi, _getStorageId(client), 'cookies', client.cookies); } catch(ex) { // no flash storage available, just silently fail // TODO: i assume we want this logged somewhere or // should it actually generate an error //forge.log.error(cat, ex); } } // FIXME: remove me _loadCookies(client); }; /** * Clears persistent cookies on disk for the given client. * * @param client the client. */ var _clearCookies = function(client) { if(client.persistCookies) { try { // only thing stored is 'cookies', so clear whole storage forge.util.clearItems( client.socketPool.flashApi, _getStorageId(client)); } catch(ex) { // no flash storage available, just silently fail // TODO: i assume we want this logged somewhere or // should it actually generate an error //forge.log.error(cat, ex); } } }; /** * Connects and sends a request. * * @param client the http client. * @param socket the socket to use. */ var _doRequest = function(client, socket) { if(socket.isConnected()) { // already connected socket.options.request.connectTime = +new Date(); socket.connected({ type: 'connect', id: socket.id }); } else { // connect socket.options.request.connectTime = +new Date(); socket.connect({ host: client.url.hostname, port: client.url.port, policyPort: client.policyPort, policyUrl: client.policyUrl }); } }; /** * Handles the next request or marks a socket as idle. * * @param client the http client. * @param socket the socket. */ var _handleNextRequest = function(client, socket) { // clear buffer socket.buffer.clear(); // get pending request var pending = null; while(pending === null && client.requests.length > 0) { pending = client.requests.shift(); if(pending.request.aborted) { pending = null; } } // mark socket idle if no pending requests if(pending === null) { if(socket.options !== null) { socket.options = null; } client.idle.push(socket); } else { // handle pending request, allow 1 retry socket.retries = 1; socket.options = pending; _doRequest(client, socket); } }; /** * Sets up a socket for use with an http client. * * @param client the parent http client. * @param socket the socket to set up. * @param tlsOptions if the socket must use TLS, the TLS options. */ var _initSocket = function(client, socket, tlsOptions) { // no socket options yet socket.options = null; // set up handlers socket.connected = function(e) { // socket primed by caching TLS session, handle next request if(socket.options === null) { _handleNextRequest(client, socket); } else { // socket in use var request = socket.options.request; request.connectTime = +new Date() - request.connectTime; e.socket = socket; socket.options.connected(e); if(request.aborted) { socket.close(); } else { var out = request.toString(); if(request.body) { out += request.body; } request.time = +new Date(); socket.send(out); request.time = +new Date() - request.time; socket.options.response.time = +new Date(); socket.sending = true; } } }; socket.closed = function(e) { if(socket.sending) { socket.sending = false; if(socket.retries > 0) { --socket.retries; _doRequest(client, socket); } else { // error, closed during send socket.error({ id: socket.id, type: 'ioError', message: 'Connection closed during send. Broken pipe.', bytesAvailable: 0 }); } } else { // handle unspecified content-length transfer var response = socket.options.response; if(response.readBodyUntilClose) { response.time = +new Date() - response.time; response.bodyReceived = true; socket.options.bodyReady({ request: socket.options.request, response: response, socket: socket }); } socket.options.closed(e); _handleNextRequest(client, socket); } }; socket.data = function(e) { socket.sending = false; var request = socket.options.request; if(request.aborted) { socket.close(); } else { // receive all bytes available var response = socket.options.response; var bytes = socket.receive(e.bytesAvailable); if(bytes !== null) { // receive header and then body socket.buffer.putBytes(bytes); if(!response.headerReceived) { response.readHeader(socket.buffer); if(response.headerReceived) { socket.options.headerReady({ request: socket.options.request, response: response, socket: socket }); } } if(response.headerReceived && !response.bodyReceived) { response.readBody(socket.buffer); } if(response.bodyReceived) { socket.options.bodyReady({ request: socket.options.request, response: response, socket: socket }); // close connection if requested or by default on http/1.0 var value = response.getField('Connection') || ''; if(value.indexOf('close') != -1 || (response.version === 'HTTP/1.0' && response.getField('Keep-Alive') === null)) { socket.close(); } else { _handleNextRequest(client, socket); } } } } }; socket.error = function(e) { // do error callback, include request socket.options.error({ type: e.type, message: e.message, request: socket.options.request, response: socket.options.response, socket: socket }); socket.close(); }; // wrap socket for TLS if(tlsOptions) { socket = forge.tls.wrapSocket({ sessionId: null, sessionCache: {}, caStore: tlsOptions.caStore, cipherSuites: tlsOptions.cipherSuites, socket: socket, virtualHost: tlsOptions.virtualHost, verify: tlsOptions.verify, getCertificate: tlsOptions.getCertificate, getPrivateKey: tlsOptions.getPrivateKey, getSignature: tlsOptions.getSignature, deflate: tlsOptions.deflate || null, inflate: tlsOptions.inflate || null }); socket.options = null; socket.buffer = forge.util.createBuffer(); client.sockets.push(socket); if(tlsOptions.prime) { // prime socket by connecting and caching TLS session, will do // next request from there socket.connect({ host: client.url.hostname, port: client.url.port, policyPort: client.policyPort, policyUrl: client.policyUrl }); } else { // do not prime socket, just add as idle client.idle.push(socket); } } else { // no need to prime non-TLS sockets socket.buffer = forge.util.createBuffer(); client.sockets.push(socket); client.idle.push(socket); } }; /** * Checks to see if the given cookie has expired. If the cookie's max-age * plus its created time is less than the time now, it has expired, unless * its max-age is set to -1 which indicates it will never expire. * * @param cookie the cookie to check. * * @return true if it has expired, false if not. */ var _hasCookieExpired = function(cookie) { var rval = false; if(cookie.maxAge !== -1) { var now = _getUtcTime(new Date()); var expires = cookie.created + cookie.maxAge; if(expires <= now) { rval = true; } } return rval; }; /** * Adds cookies in the given client to the given request. * * @param client the client. * @param request the request. */ var _writeCookies = function(client, request) { var expired = []; var url = client.url; var cookies = client.cookies; for(var name in cookies) { // get cookie paths var paths = cookies[name]; for(var p in paths) { var cookie = paths[p]; if(_hasCookieExpired(cookie)) { // store for clean up expired.push(cookie); } else if(request.path.indexOf(cookie.path) === 0) { // path or path's ancestor must match cookie.path request.addCookie(cookie); } } } // clean up expired cookies for(var i = 0; i < expired.length; ++i) { var cookie = expired[i]; client.removeCookie(cookie.name, cookie.path); } }; /** * Gets cookies from the given response and adds the to the given client. * * @param client the client. * @param response the response. */ var _readCookies = function(client, response) { var cookies = response.getCookies(); for(var i = 0; i < cookies.length; ++i) { try { client.setCookie(cookies[i]); } catch(ex) { // ignore failure to add other-domain, etc. cookies } } }; /** * Creates an http client that uses forge.net sockets as a backend and * forge.tls for security. * * @param options: * url: the url to connect to (scheme://host:port). * socketPool: the flash socket pool to use. * policyPort: the flash policy port to use (if other than the * socket pool default), use 0 for flash default. * policyUrl: the flash policy file URL to use (if provided will * be used instead of a policy port). * connections: number of connections to use to handle requests. * caCerts: an array of certificates to trust for TLS, certs may * be PEM-formatted or cert objects produced via forge.pki. * cipherSuites: an optional array of cipher suites to use, * see forge.tls.CipherSuites. * virtualHost: the virtual server name to use in a TLS SNI * extension, if not provided the url host will be used. * verify: a custom TLS certificate verify callback to use. * getCertificate: an optional callback used to get a client-side * certificate (see forge.tls for details). * getPrivateKey: an optional callback used to get a client-side * private key (see forge.tls for details). * getSignature: an optional callback used to get a client-side * signature (see forge.tls for details). * persistCookies: true to use persistent cookies via flash local * storage, false to only keep cookies in javascript. * primeTlsSockets: true to immediately connect TLS sockets on * their creation so that they will cache TLS sessions for reuse. * * @return the client. */ http.createClient = function(options) { // create CA store to share with all TLS connections var caStore = null; if(options.caCerts) { caStore = forge.pki.createCaStore(options.caCerts); } // get scheme, host, and port from url options.url = (options.url || window.location.protocol + '//' + window.location.host); var url; try { url = new URL(options.url); } catch(e) { var error = new Error('Invalid url.'); error.details = {url: options.url}; throw error; } // default to 1 connection options.connections = options.connections || 1; // create client var sp = options.socketPool; var client = { // url url: url, // socket pool socketPool: sp, // the policy port to use policyPort: options.policyPort, // policy url to use policyUrl: options.policyUrl, // queue of requests to service requests: [], // all sockets sockets: [], // idle sockets idle: [], // whether or not the connections are secure secure: (url.protocol === 'https:'), // cookie jar (key'd off of name and then path, there is only 1 domain // and one setting for secure per client so name+path is unique) cookies: {}, // default to flash storage of cookies persistCookies: (typeof(options.persistCookies) === 'undefined') ? true : options.persistCookies }; // load cookies from disk _loadCookies(client); /** * A default certificate verify function that checks a certificate common * name against the client's URL host. * * @param c the TLS connection. * @param verified true if cert is verified, otherwise alert number. * @param depth the chain depth. * @param certs the cert chain. * * @return true if verified and the common name matches the host, error * otherwise. */ var _defaultCertificateVerify = function(c, verified, depth, certs) { if(depth === 0 && verified === true) { // compare common name to url host var cn = certs[depth].subject.getField('CN'); if(cn === null || client.url.hostname !== cn.value) { verified = { message: 'Certificate common name does not match url host.' }; } } return verified; }; // determine if TLS is used var tlsOptions = null; if(client.secure) { tlsOptions = { caStore: caStore, cipherSuites: options.cipherSuites || null, virtualHost: options.virtualHost || url.hostname, verify: options.verify || _defaultCertificateVerify, getCertificate: options.getCertificate || null, getPrivateKey: options.getPrivateKey || null, getSignature: options.getSignature || null, prime: options.primeTlsSockets || false }; // if socket pool uses a flash api, then add deflate support to TLS if(sp.flashApi !== null) { tlsOptions.deflate = function(bytes) { // strip 2 byte zlib header and 4 byte trailer return forge.util.deflate(sp.flashApi, bytes, true); }; tlsOptions.inflate = function(bytes) { return forge.util.inflate(sp.flashApi, bytes, true); }; } } // create and initialize sockets for(var i = 0; i < options.connections; ++i) { _initSocket(client, sp.createSocket(), tlsOptions); } /** * Sends a request. A method 'abort' will be set on the request that * can be called to attempt to abort the request. * * @param options: * request: the request to send. * connected: a callback for when the connection is open. * closed: a callback for when the connection is closed. * headerReady: a callback for when the response header arrives. * bodyReady: a callback for when the response body arrives. * error: a callback for if an error occurs. */ client.send = function(options) { // add host header if not set if(options.request.getField('Host') === null) { options.request.setField('Host', client.url.origin); } // set default dummy handlers var opts = {}; opts.request = options.request; opts.connected = options.connected || function() {}; opts.closed = options.close || function() {}; opts.headerReady = function(e) { // read cookies _readCookies(client, e.response); if(options.headerReady) { options.headerReady(e); } }; opts.bodyReady = options.bodyReady || function() {}; opts.error = options.error || function() {}; // create response opts.response = http.createResponse(); opts.response.time = 0; opts.response.flashApi = client.socketPool.flashApi; opts.request.flashApi = client.socketPool.flashApi; // create abort function opts.request.abort = function() { // set aborted, clear handlers opts.request.aborted = true; opts.connected = function() {}; opts.closed = function() {}; opts.headerReady = function() {}; opts.bodyReady = function() {}; opts.error = function() {}; }; // add cookies to request _writeCookies(client, opts.request); // queue request options if there are no idle sockets if(client.idle.length === 0) { client.requests.push(opts); } else { // use an idle socket, prefer an idle *connected* socket first var socket = null; var len = client.idle.length; for(var i = 0; socket === null && i < len; ++i) { socket = client.idle[i]; if(socket.isConnected()) { client.idle.splice(i, 1); } else { socket = null; } } // no connected socket available, get unconnected socket if(socket === null) { socket = client.idle.pop(); } socket.options = opts; _doRequest(client, socket); } }; /** * Destroys this client. */ client.destroy = function() { // clear pending requests, close and destroy sockets client.requests = []; for(var i = 0; i < client.sockets.length; ++i) { client.sockets[i].close(); client.sockets[i].destroy(); } client.socketPool = null; client.sockets = []; client.idle = []; }; /** * Sets a cookie for use with all connections made by this client. Any * cookie with the same name will be replaced. If the cookie's value * is undefined, null, or the blank string, the cookie will be removed. * * If the cookie's domain doesn't match this client's url host or the * cookie's secure flag doesn't match this client's url scheme, then * setting the cookie will fail with an exception. * * @param cookie the cookie with parameters: * name: the name of the cookie. * value: the value of the cookie. * comment: an optional comment string. * maxAge: the age of the cookie in seconds relative to created time. * secure: true if the cookie must be sent over a secure protocol. * httpOnly: true to restrict access to the cookie from javascript * (inaffective since the cookies are stored in javascript). * path: the path for the cookie. * domain: optional domain the cookie belongs to (must start with dot). * version: optional version of the cookie. * created: creation time, in UTC seconds, of the cookie. */ client.setCookie = function(cookie) { var rval; if(typeof(cookie.name) !== 'undefined') { if(cookie.value === null || typeof(cookie.value) === 'undefined' || cookie.value === '') { // remove cookie rval = client.removeCookie(cookie.name, cookie.path); } else { // set cookie defaults cookie.comment = cookie.comment || ''; cookie.maxAge = cookie.maxAge || 0; cookie.secure = (typeof(cookie.secure) === 'undefined') ? true : cookie.secure; cookie.httpOnly = cookie.httpOnly || true; cookie.path = cookie.path || '/'; cookie.domain = cookie.domain || null; cookie.version = cookie.version || null; cookie.created = _getUtcTime(new Date()); // do secure check if(cookie.secure !== client.secure) { var error = new Error('Http client url scheme is incompatible ' + 'with cookie secure flag.'); error.url = client.url; error.cookie = cookie; throw error; } // make sure url host is within cookie.domain if(!http.withinCookieDomain(client.url, cookie)) { var error = new Error('Http client url scheme is incompatible ' + 'with cookie secure flag.'); error.url = client.url; error.cookie = cookie; throw error; } // add new cookie if(!(cookie.name in client.cookies)) { client.cookies[cookie.name] = {}; } client.cookies[cookie.name][cookie.path] = cookie; rval = true; // save cookies _saveCookies(client); } } return rval; }; /** * Gets a cookie by its name. * * @param name the name of the cookie to retrieve. * @param path an optional path for the cookie (if there are multiple * cookies with the same name but different paths). * * @return the cookie or null if not found. */ client.getCookie = function(name, path) { var rval = null; if(name in client.cookies) { var paths = client.cookies[name]; // get path-specific cookie if(path) { if(path in paths) { rval = paths[path]; } } else { // get first cookie for(var p in paths) { rval = paths[p]; break; } } } return rval; }; /** * Removes a cookie. * * @param name the name of the cookie to remove. * @param path an optional path for the cookie (if there are multiple * cookies with the same name but different paths). * * @return true if a cookie was removed, false if not. */ client.removeCookie = function(name, path) { var rval = false; if(name in client.cookies) { // delete the specific path if(path) { var paths = client.cookies[name]; if(path in paths) { rval = true; delete client.cookies[name][path]; // clean up entry if empty var empty = true; for(var i in client.cookies[name]) { empty = false; break; } if(empty) { delete client.cookies[name]; } } } else { // delete all cookies with the given name rval = true; delete client.cookies[name]; } } if(rval) { // save cookies _saveCookies(client); } return rval; }; /** * Clears all cookies stored in this client. */ client.clearCookies = function() { client.cookies = {}; _clearCookies(client); }; if(forge.log) { forge.log.debug('forge.http', 'created client', options); } return client; }; /** * Trims the whitespace off of the beginning and end of a string. * * @param str the string to trim. * * @return the trimmed string. */ var _trimString = function(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); }; /** * Creates an http header object. * * @return the http header object. */ var _createHeader = function() { var header = { fields: {}, setField: function(name, value) { // normalize field name, trim value header.fields[_normalize(name)] = [_trimString('' + value)]; }, appendField: function(name, value) { name = _normalize(name); if(!(name in header.fields)) { header.fields[name] = []; } header.fields[name].push(_trimString('' + value)); }, getField: function(name, index) { var rval = null; name = _normalize(name); if(name in header.fields) { index = index || 0; rval = header.fields[name][index]; } return rval; } }; return header; }; /** * Gets the time in utc seconds given a date. * * @param d the date to use. * * @return the time in utc seconds. */ var _getUtcTime = function(d) { var utc = +d + d.getTimezoneOffset() * 60000; return Math.floor(+new Date() / 1000); }; /** * Creates an http request. * * @param options: * version: the version. * method: the method. * path: the path. * body: the body. * headers: custom header fields to add, * eg: [{'Content-Length': 0}]. * * @return the http request. */ http.createRequest = function(options) { options = options || {}; var request = _createHeader(); request.version = options.version || 'HTTP/1.1'; request.method = options.method || null; request.path = options.path || null; request.body = options.body || null; request.bodyDeflated = false; request.flashApi = null; // add custom headers var headers = options.headers || []; if(!forge.util.isArray(headers)) { headers = [headers]; } for(var i = 0; i < headers.length; ++i) { for(var name in headers[i]) { request.appendField(name, headers[i][name]); } } /** * Adds a cookie to the request 'Cookie' header. * * @param cookie a cookie to add. */ request.addCookie = function(cookie) { var value = ''; var field = request.getField('Cookie'); if(field !== null) { // separate cookies by semi-colons value = field + '; '; } // get current time in utc seconds var now = _getUtcTime(new Date()); // output cookie name and value value += cookie.name + '=' + cookie.value; request.setField('Cookie', value); }; /** * Converts an http request into a string that can be sent as an * HTTP request. Does not include any data. * * @return the string representation of the request. */ request.toString = function() { /* Sample request header: GET /some/path/?query HTTP/1.1 Host: www.someurl.com Connection: close Accept-Encoding: deflate Accept: image/gif, text/html User-Agent: Mozilla 4.0 */ // set default headers if(request.getField('User-Agent') === null) { request.setField('User-Agent', 'forge.http 1.0'); } if(request.getField('Accept') === null) { request.setField('Accept', '*/*'); } if(request.getField('Connection') === null) { request.setField('Connection', 'keep-alive'); request.setField('Keep-Alive', '115'); } // add Accept-Encoding if not specified if(request.flashApi !== null && request.getField('Accept-Encoding') === null) { request.setField('Accept-Encoding', 'deflate'); } // if the body isn't null, deflate it if its larger than 100 bytes if(request.flashApi !== null && request.body !== null && request.getField('Content-Encoding') === null && !request.bodyDeflated && request.body.length > 100) { // use flash to compress data request.body = forge.util.deflate(request.flashApi, request.body); request.bodyDeflated = true; request.setField('Content-Encoding', 'deflate'); request.setField('Content-Length', request.body.length); } else if(request.body !== null) { // set content length for body request.setField('Content-Length', request.body.length); } // build start line var rval = request.method.toUpperCase() + ' ' + request.path + ' ' + request.version + '\r\n'; // add each header for(var name in request.fields) { var fields = request.fields[name]; for(var i = 0; i < fields.length; ++i) { rval += name + ': ' + fields[i] + '\r\n'; } } // final terminating CRLF rval += '\r\n'; return rval; }; return request; }; /** * Creates an empty http response header. * * @return the empty http response header. */ http.createResponse = function() { // private vars var _first = true; var _chunkSize = 0; var _chunksFinished = false; // create response var response = _createHeader(); response.version = null; response.code = 0; response.message = null; response.body = null; response.headerReceived = false; response.bodyReceived = false; response.flashApi = null; /** * Reads a line that ends in CRLF from a byte buffer. * * @param b the byte buffer. * * @return the line or null if none was found. */ var _readCrlf = function(b) { var line = null; var i = b.data.indexOf('\r\n', b.read); if(i != -1) { // read line, skip CRLF line = b.getBytes(i - b.read); b.getBytes(2); } return line; }; /** * Parses a header field and appends it to the response. * * @param line the header field line. */ var _parseHeader = function(line) { var tmp = line.indexOf(':'); var name = line.substring(0, tmp++); response.appendField( name, (tmp < line.length) ? line.substring(tmp) : ''); }; /** * Reads an http response header from a buffer of bytes. * * @param b the byte buffer to parse the header from. * * @return true if the whole header was read, false if not. */ response.readHeader = function(b) { // read header lines (each ends in CRLF) var line = ''; while(!response.headerReceived && line !== null) { line = _readCrlf(b); if(line !== null) { // parse first line if(_first) { _first = false; var tmp = line.split(' '); if(tmp.length >= 3) { response.version = tmp[0]; response.code = parseInt(tmp[1], 10); response.message = tmp.slice(2).join(' '); } else { // invalid header var error = new Error('Invalid http response header.'); error.details = {'line': line}; throw error; } } else if(line.length === 0) { // handle final line, end of header response.headerReceived = true; } else { _parseHeader(line); } } } return response.headerReceived; }; /** * Reads some chunked http response entity-body from the given buffer of * bytes. * * @param b the byte buffer to read from. * * @return true if the whole body was read, false if not. */ var _readChunkedBody = function(b) { /* Chunked transfer-encoding sends data in a series of chunks, followed by a set of 0-N http trailers. The format is as follows: chunk-size (in hex) CRLF chunk data (with "chunk-size" many bytes) CRLF ... (N many chunks) chunk-size (of 0 indicating the last chunk) CRLF N many http trailers followed by CRLF blank line + CRLF (terminates the trailers) If there are no http trailers, then after the chunk-size of 0, there is still a single CRLF (indicating the blank line + CRLF that terminates the trailers). In other words, you always terminate the trailers with blank line + CRLF, regardless of 0-N trailers. */ /* From RFC-2616, section 3.6.1, here is the pseudo-code for implementing chunked transfer-encoding: length := 0 read chunk-size, chunk-extension (if any) and CRLF while (chunk-size > 0) { read chunk-data and CRLF append chunk-data to entity-body length := length + chunk-size read chunk-size and CRLF } read entity-header while (entity-header not empty) { append entity-header to existing header fields read entity-header } Content-Length := length Remove "chunked" from Transfer-Encoding */ var line = ''; while(line !== null && b.length() > 0) { // if in the process of reading a chunk if(_chunkSize > 0) { // if there are not enough bytes to read chunk and its // trailing CRLF, we must wait for more data to be received if(_chunkSize + 2 > b.length()) { break; } // read chunk data, skip CRLF response.body += b.getBytes(_chunkSize); b.getBytes(2); _chunkSize = 0; } else if(!_chunksFinished) { // more chunks, read next chunk-size line line = _readCrlf(b); if(line !== null) { // parse chunk-size (ignore any chunk extension)
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/x509.js
aws/lti-middleware/node_modules/node-forge/lib/x509.js
/** * Javascript implementation of X.509 and related components (such as * Certification Signing Requests) of a Public Key Infrastructure. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. * * The ASN.1 representation of an X.509v3 certificate is as follows * (see RFC 2459): * * Certificate ::= SEQUENCE { * tbsCertificate TBSCertificate, * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING * } * * TBSCertificate ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * serialNumber CertificateSerialNumber, * signature AlgorithmIdentifier, * issuer Name, * validity Validity, * subject Name, * subjectPublicKeyInfo SubjectPublicKeyInfo, * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version shall be v2 or v3 * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version shall be v2 or v3 * extensions [3] EXPLICIT Extensions OPTIONAL * -- If present, version shall be v3 * } * * Version ::= INTEGER { v1(0), v2(1), v3(2) } * * CertificateSerialNumber ::= INTEGER * * Name ::= CHOICE { * // only one possible choice for now * RDNSequence * } * * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue * } * AttributeType ::= OBJECT IDENTIFIER * AttributeValue ::= ANY DEFINED BY AttributeType * * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time * } * * Time ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime * } * * UniqueIdentifier ::= BIT STRING * * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING * } * * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension * * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING * } * * The only key algorithm currently supported for PKI is RSA. * * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. * * PKCS#10 v1.7 describes certificate signing requests: * * CertificationRequestInfo: * * CertificationRequestInfo ::= SEQUENCE { * version INTEGER { v1(0) } (v1,...), * subject Name, * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, * attributes [0] Attributes{{ CRIAttributes }} * } * * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} * * CRIAttributes ATTRIBUTE ::= { * ... -- add any locally defined attributes here -- } * * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { * type ATTRIBUTE.&id({IOSet}), * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) * } * * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, * signature BIT STRING * } */ var forge = require('./forge'); require('./aes'); require('./asn1'); require('./des'); require('./md'); require('./mgf'); require('./oids'); require('./pem'); require('./pss'); require('./rsa'); require('./util'); // shortcut for asn.1 API var asn1 = forge.asn1; /* Public Key Infrastructure (PKI) implementation. */ var pki = module.exports = forge.pki = forge.pki || {}; var oids = pki.oids; // short name OID mappings var _shortNames = {}; _shortNames['CN'] = oids['commonName']; _shortNames['commonName'] = 'CN'; _shortNames['C'] = oids['countryName']; _shortNames['countryName'] = 'C'; _shortNames['L'] = oids['localityName']; _shortNames['localityName'] = 'L'; _shortNames['ST'] = oids['stateOrProvinceName']; _shortNames['stateOrProvinceName'] = 'ST'; _shortNames['O'] = oids['organizationName']; _shortNames['organizationName'] = 'O'; _shortNames['OU'] = oids['organizationalUnitName']; _shortNames['organizationalUnitName'] = 'OU'; _shortNames['E'] = oids['emailAddress']; _shortNames['emailAddress'] = 'E'; // validator for an SubjectPublicKeyInfo structure // Note: Currently only works with an RSA public key var publicKeyValidator = forge.pki.rsa.publicKeyValidator; // validator for an X.509v3 certificate var x509CertificateValidator = { name: 'Certificate', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'Certificate.TBSCertificate', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'tbsCertificate', value: [{ name: 'Certificate.TBSCertificate.version', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, constructed: true, optional: true, value: [{ name: 'Certificate.TBSCertificate.version.integer', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'certVersion' }] }, { name: 'Certificate.TBSCertificate.serialNumber', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'certSerialNumber' }, { name: 'Certificate.TBSCertificate.signature', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'Certificate.TBSCertificate.signature.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'certinfoSignatureOid' }, { name: 'Certificate.TBSCertificate.signature.parameters', tagClass: asn1.Class.UNIVERSAL, optional: true, captureAsn1: 'certinfoSignatureParams' }] }, { name: 'Certificate.TBSCertificate.issuer', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'certIssuer' }, { name: 'Certificate.TBSCertificate.validity', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, // Note: UTC and generalized times may both appear so the capture // names are based on their detected order, the names used below // are only for the common case, which validity time really means // "notBefore" and which means "notAfter" will be determined by order value: [{ // notBefore (Time) (UTC time case) name: 'Certificate.TBSCertificate.validity.notBefore (utc)', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.UTCTIME, constructed: false, optional: true, capture: 'certValidity1UTCTime' }, { // notBefore (Time) (generalized time case) name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.GENERALIZEDTIME, constructed: false, optional: true, capture: 'certValidity2GeneralizedTime' }, { // notAfter (Time) (only UTC time is supported) name: 'Certificate.TBSCertificate.validity.notAfter (utc)', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.UTCTIME, constructed: false, optional: true, capture: 'certValidity3UTCTime' }, { // notAfter (Time) (only UTC time is supported) name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.GENERALIZEDTIME, constructed: false, optional: true, capture: 'certValidity4GeneralizedTime' }] }, { // Name (subject) (RDNSequence) name: 'Certificate.TBSCertificate.subject', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'certSubject' }, // SubjectPublicKeyInfo publicKeyValidator, { // issuerUniqueID (optional) name: 'Certificate.TBSCertificate.issuerUniqueID', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 1, constructed: true, optional: true, value: [{ name: 'Certificate.TBSCertificate.issuerUniqueID.id', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, // TODO: support arbitrary bit length ids captureBitStringValue: 'certIssuerUniqueId' }] }, { // subjectUniqueID (optional) name: 'Certificate.TBSCertificate.subjectUniqueID', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 2, constructed: true, optional: true, value: [{ name: 'Certificate.TBSCertificate.subjectUniqueID.id', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, // TODO: support arbitrary bit length ids captureBitStringValue: 'certSubjectUniqueId' }] }, { // Extensions (optional) name: 'Certificate.TBSCertificate.extensions', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 3, constructed: true, captureAsn1: 'certExtensions', optional: true }] }, { // AlgorithmIdentifier (signature algorithm) name: 'Certificate.signatureAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // algorithm name: 'Certificate.signatureAlgorithm.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'certSignatureOid' }, { name: 'Certificate.TBSCertificate.signature.parameters', tagClass: asn1.Class.UNIVERSAL, optional: true, captureAsn1: 'certSignatureParams' }] }, { // SignatureValue name: 'Certificate.signatureValue', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, captureBitStringValue: 'certSignature' }] }; var rsassaPssParameterValidator = { name: 'rsapss', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'rsapss.hashAlgorithm', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, constructed: true, value: [{ name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Class.SEQUENCE, constructed: true, optional: true, value: [{ name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'hashOid' /* parameter block omitted, for SHA1 NULL anyhow. */ }] }] }, { name: 'rsapss.maskGenAlgorithm', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 1, constructed: true, value: [{ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Class.SEQUENCE, constructed: true, optional: true, value: [{ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'maskGenOid' }, { name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'maskGenHashOid' /* parameter block omitted, for SHA1 NULL anyhow. */ }] }] }] }, { name: 'rsapss.saltLength', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 2, optional: true, value: [{ name: 'rsapss.saltLength.saltLength', tagClass: asn1.Class.UNIVERSAL, type: asn1.Class.INTEGER, constructed: false, capture: 'saltLength' }] }, { name: 'rsapss.trailerField', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 3, optional: true, value: [{ name: 'rsapss.trailer.trailer', tagClass: asn1.Class.UNIVERSAL, type: asn1.Class.INTEGER, constructed: false, capture: 'trailer' }] }] }; // validator for a CertificationRequestInfo structure var certificationRequestInfoValidator = { name: 'CertificationRequestInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'certificationRequestInfo', value: [{ name: 'CertificationRequestInfo.integer', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'certificationRequestInfoVersion' }, { // Name (subject) (RDNSequence) name: 'CertificationRequestInfo.subject', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'certificationRequestInfoSubject' }, // SubjectPublicKeyInfo publicKeyValidator, { name: 'CertificationRequestInfo.attributes', tagClass: asn1.Class.CONTEXT_SPECIFIC, type: 0, constructed: true, optional: true, capture: 'certificationRequestInfoAttributes', value: [{ name: 'CertificationRequestInfo.attributes', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'CertificationRequestInfo.attributes.type', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false }, { name: 'CertificationRequestInfo.attributes.value', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SET, constructed: true }] }] }] }; // validator for a CertificationRequest structure var certificationRequestValidator = { name: 'CertificationRequest', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'csr', value: [ certificationRequestInfoValidator, { // AlgorithmIdentifier (signature algorithm) name: 'CertificationRequest.signatureAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // algorithm name: 'CertificationRequest.signatureAlgorithm.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'csrSignatureOid' }, { name: 'CertificationRequest.signatureAlgorithm.parameters', tagClass: asn1.Class.UNIVERSAL, optional: true, captureAsn1: 'csrSignatureParams' }] }, { // signature name: 'CertificationRequest.signature', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, captureBitStringValue: 'csrSignature' } ] }; /** * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName * sets into an array with objects that have type and value properties. * * @param rdn the RDNSequence to convert. * @param md a message digest to append type and value to if provided. */ pki.RDNAttributesAsArray = function(rdn, md) { var rval = []; // each value in 'rdn' in is a SET of RelativeDistinguishedName var set, attr, obj; for(var si = 0; si < rdn.value.length; ++si) { // get the RelativeDistinguishedName set set = rdn.value[si]; // each value in the SET is an AttributeTypeAndValue sequence // containing first a type (an OID) and second a value (defined by // the OID) for(var i = 0; i < set.value.length; ++i) { obj = {}; attr = set.value[i]; obj.type = asn1.derToOid(attr.value[0].value); obj.value = attr.value[1].value; obj.valueTagClass = attr.value[1].type; // if the OID is known, get its name and short name if(obj.type in oids) { obj.name = oids[obj.type]; if(obj.name in _shortNames) { obj.shortName = _shortNames[obj.name]; } } if(md) { md.update(obj.type); md.update(obj.value); } rval.push(obj); } } return rval; }; /** * Converts ASN.1 CRIAttributes into an array with objects that have type and * value properties. * * @param attributes the CRIAttributes to convert. */ pki.CRIAttributesAsArray = function(attributes) { var rval = []; // each value in 'attributes' in is a SEQUENCE with an OID and a SET for(var si = 0; si < attributes.length; ++si) { // get the attribute sequence var seq = attributes[si]; // each value in the SEQUENCE containing first a type (an OID) and // second a set of values (defined by the OID) var type = asn1.derToOid(seq.value[0].value); var values = seq.value[1].value; for(var vi = 0; vi < values.length; ++vi) { var obj = {}; obj.type = type; obj.value = values[vi].value; obj.valueTagClass = values[vi].type; // if the OID is known, get its name and short name if(obj.type in oids) { obj.name = oids[obj.type]; if(obj.name in _shortNames) { obj.shortName = _shortNames[obj.name]; } } // parse extensions if(obj.type === oids.extensionRequest) { obj.extensions = []; for(var ei = 0; ei < obj.value.length; ++ei) { obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); } } rval.push(obj); } } return rval; }; /** * Gets an issuer or subject attribute from its name, type, or short name. * * @param obj the issuer or subject object. * @param options a short name string or an object with: * shortName the short name for the attribute. * name the name for the attribute. * type the type for the attribute. * * @return the attribute. */ function _getAttribute(obj, options) { if(typeof options === 'string') { options = {shortName: options}; } var rval = null; var attr; for(var i = 0; rval === null && i < obj.attributes.length; ++i) { attr = obj.attributes[i]; if(options.type && options.type === attr.type) { rval = attr; } else if(options.name && options.name === attr.name) { rval = attr; } else if(options.shortName && options.shortName === attr.shortName) { rval = attr; } } return rval; } /** * Converts signature parameters from ASN.1 structure. * * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had * no parameters. * * RSASSA-PSS-params ::= SEQUENCE { * hashAlgorithm [0] HashAlgorithm DEFAULT * sha1Identifier, * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT * mgf1SHA1Identifier, * saltLength [2] INTEGER DEFAULT 20, * trailerField [3] INTEGER DEFAULT 1 * } * * HashAlgorithm ::= AlgorithmIdentifier * * MaskGenAlgorithm ::= AlgorithmIdentifier * * AlgorithmIdentifer ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * @param oid The OID specifying the signature algorithm * @param obj The ASN.1 structure holding the parameters * @param fillDefaults Whether to use return default values where omitted * @return signature parameter object */ var _readSignatureParameters = function(oid, obj, fillDefaults) { var params = {}; if(oid !== oids['RSASSA-PSS']) { return params; } if(fillDefaults) { params = { hash: { algorithmOid: oids['sha1'] }, mgf: { algorithmOid: oids['mgf1'], hash: { algorithmOid: oids['sha1'] } }, saltLength: 20 }; } var capture = {}; var errors = []; if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { var error = new Error('Cannot read RSASSA-PSS parameter block.'); error.errors = errors; throw error; } if(capture.hashOid !== undefined) { params.hash = params.hash || {}; params.hash.algorithmOid = asn1.derToOid(capture.hashOid); } if(capture.maskGenOid !== undefined) { params.mgf = params.mgf || {}; params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); params.mgf.hash = params.mgf.hash || {}; params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); } if(capture.saltLength !== undefined) { params.saltLength = capture.saltLength.charCodeAt(0); } return params; }; /** * Create signature digest for OID. * * @param options * signatureOid: the OID specifying the signature algorithm. * type: a human readable type for error messages * @return a created md instance. throws if unknown oid. */ var _createSignatureDigest = function(options) { switch(oids[options.signatureOid]) { case 'sha1WithRSAEncryption': // deprecated alias case 'sha1WithRSASignature': return forge.md.sha1.create(); case 'md5WithRSAEncryption': return forge.md.md5.create(); case 'sha256WithRSAEncryption': return forge.md.sha256.create(); case 'sha384WithRSAEncryption': return forge.md.sha384.create(); case 'sha512WithRSAEncryption': return forge.md.sha512.create(); case 'RSASSA-PSS': return forge.md.sha256.create(); default: var error = new Error( 'Could not compute ' + options.type + ' digest. ' + 'Unknown signature OID.'); error.signatureOid = options.signatureOid; throw error; } }; /** * Verify signature on certificate or CSR. * * @param options: * certificate the certificate or CSR to verify. * md the signature digest. * signature the signature * @return a created md instance. throws if unknown oid. */ var _verifySignature = function(options) { var cert = options.certificate; var scheme; switch(cert.signatureOid) { case oids.sha1WithRSAEncryption: // deprecated alias case oids.sha1WithRSASignature: /* use PKCS#1 v1.5 padding scheme */ break; case oids['RSASSA-PSS']: var hash, mgf; /* initialize mgf */ hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; if(hash === undefined || forge.md[hash] === undefined) { var error = new Error('Unsupported MGF hash function.'); error.oid = cert.signatureParameters.mgf.hash.algorithmOid; error.name = hash; throw error; } mgf = oids[cert.signatureParameters.mgf.algorithmOid]; if(mgf === undefined || forge.mgf[mgf] === undefined) { var error = new Error('Unsupported MGF function.'); error.oid = cert.signatureParameters.mgf.algorithmOid; error.name = mgf; throw error; } mgf = forge.mgf[mgf].create(forge.md[hash].create()); /* initialize hash function */ hash = oids[cert.signatureParameters.hash.algorithmOid]; if(hash === undefined || forge.md[hash] === undefined) { var error = new Error('Unsupported RSASSA-PSS hash function.'); error.oid = cert.signatureParameters.hash.algorithmOid; error.name = hash; throw error; } scheme = forge.pss.create( forge.md[hash].create(), mgf, cert.signatureParameters.saltLength ); break; } // verify signature on cert using public key return cert.publicKey.verify( options.md.digest().getBytes(), options.signature, scheme ); }; /** * Converts an X.509 certificate from PEM format. * * Note: If the certificate is to be verified then compute hash should * be set to true. This will scan the TBSCertificate part of the ASN.1 * object while it is converted so it doesn't need to be converted back * to ASN.1-DER-encoding later. * * @param pem the PEM-formatted certificate. * @param computeHash true to compute the hash for verification. * @param strict true to be strict when checking ASN.1 value lengths, false to * allow truncated values (default: true). * * @return the certificate. */ pki.certificateFromPem = function(pem, computeHash, strict) { var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'CERTIFICATE' && msg.type !== 'X509 CERTIFICATE' && msg.type !== 'TRUSTED CERTIFICATE') { var error = new Error( 'Could not convert certificate from PEM; PEM header type ' + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); error.headerType = msg.type; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error( 'Could not convert certificate from PEM; PEM is encrypted.'); } // convert DER to ASN.1 object var obj = asn1.fromDer(msg.body, strict); return pki.certificateFromAsn1(obj, computeHash); }; /** * Converts an X.509 certificate to PEM format. * * @param cert the certificate. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted certificate. */ pki.certificateToPem = function(cert, maxline) { // convert to ASN.1, then DER, then PEM-encode var msg = { type: 'CERTIFICATE', body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); }; /** * Converts an RSA public key from PEM format. * * @param pem the PEM-formatted public key. * * @return the public key. */ pki.publicKeyFromPem = function(pem) { var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { var error = new Error('Could not convert public key from PEM; PEM header ' + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); error.headerType = msg.type; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error('Could not convert public key from PEM; PEM is encrypted.'); } // convert DER to ASN.1 object var obj = asn1.fromDer(msg.body); return pki.publicKeyFromAsn1(obj); }; /** * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). * * @param key the public key. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted public key. */ pki.publicKeyToPem = function(key, maxline) { // convert to ASN.1, then DER, then PEM-encode var msg = { type: 'PUBLIC KEY', body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); }; /** * Converts an RSA public key to PEM format (using an RSAPublicKey). * * @param key the public key. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted public key. */ pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { // convert to ASN.1, then DER, then PEM-encode var msg = { type: 'RSA PUBLIC KEY', body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); }; /** * Gets a fingerprint for the given public key. * * @param options the options to use. * [md] the message digest object to use (defaults to forge.md.sha1). * [type] the type of fingerprint, such as 'RSAPublicKey', * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). * [encoding] an alternative output encoding, such as 'hex' * (defaults to none, outputs a byte buffer). * [delimiter] the delimiter to use between bytes for 'hex' encoded * output, eg: ':' (defaults to none). * * @return the fingerprint as a byte buffer or other encoding based on options. */ pki.getPublicKeyFingerprint = function(key, options) { options = options || {}; var md = options.md || forge.md.sha1.create(); var type = options.type || 'RSAPublicKey'; var bytes; switch(type) { case 'RSAPublicKey': bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); break; case 'SubjectPublicKeyInfo': bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); break; default: throw new Error('Unknown fingerprint type "' + options.type + '".'); } // hash public key bytes md.start(); md.update(bytes); var digest = md.digest(); if(options.encoding === 'hex') { var hex = digest.toHex(); if(options.delimiter) { return hex.match(/.{2}/g).join(options.delimiter); } return hex; } else if(options.encoding === 'binary') { return digest.getBytes(); } else if(options.encoding) { throw new Error('Unknown encoding "' + options.encoding + '".'); } return digest; }; /** * Converts a PKCS#10 certification request (CSR) from PEM format. * * Note: If the certification request is to be verified then compute hash * should be set to true. This will scan the CertificationRequestInfo part of * the ASN.1 object while it is converted so it doesn't need to be converted * back to ASN.1-DER-encoding later. * * @param pem the PEM-formatted certificate. * @param computeHash true to compute the hash for verification. * @param strict true to be strict when checking ASN.1 value lengths, false to * allow truncated values (default: true). * * @return the certification request (CSR). */ pki.certificationRequestFromPem = function(pem, computeHash, strict) { var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'CERTIFICATE REQUEST') { var error = new Error('Could not convert certification request from PEM; ' + 'PEM header type is not "CERTIFICATE REQUEST".'); error.headerType = msg.type; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error('Could not convert certification request from PEM; ' + 'PEM is encrypted.'); } // convert DER to ASN.1 object var obj = asn1.fromDer(msg.body, strict); return pki.certificationRequestFromAsn1(obj, computeHash); }; /** * Converts a PKCS#10 certification request (CSR) to PEM format. * * @param csr the certification request. * @param maxline the maximum characters per line, defaults to 64. * * @return the PEM-formatted certification request. */ pki.certificationRequestToPem = function(csr, maxline) { // convert to ASN.1, then DER, then PEM-encode var msg = { type: 'CERTIFICATE REQUEST', body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() }; return forge.pem.encode(msg, {maxline: maxline}); }; /** * Creates an empty X.509v3 RSA certificate. * * @return the certificate. */ pki.createCertificate = function() { var cert = {}; cert.version = 0x02; cert.serialNumber = '00'; cert.signatureOid = null; cert.signature = null; cert.siginfo = {}; cert.siginfo.algorithmOid = null; cert.validity = {}; cert.validity.notBefore = new Date(); cert.validity.notAfter = new Date(); cert.issuer = {}; cert.issuer.getField = function(sn) { return _getAttribute(cert.issuer, sn); }; cert.issuer.addField = function(attr) { _fillMissingFields([attr]); cert.issuer.attributes.push(attr); }; cert.issuer.attributes = []; cert.issuer.hash = null; cert.subject = {}; cert.subject.getField = function(sn) { return _getAttribute(cert.subject, sn); }; cert.subject.addField = function(attr) { _fillMissingFields([attr]); cert.subject.attributes.push(attr); }; cert.subject.attributes = []; cert.subject.hash = null; cert.extensions = []; cert.publicKey = null; cert.md = null; /** * Sets the subject of this certificate. * * @param attrs the array of subject attributes to use. * @param uniqueId an optional a unique ID to use. */ cert.setSubject = function(attrs, uniqueId) { // set new attributes, clear hash _fillMissingFields(attrs); cert.subject.attributes = attrs; delete cert.subject.uniqueId; if(uniqueId) { // TODO: support arbitrary bit length ids cert.subject.uniqueId = uniqueId; } cert.subject.hash = null; }; /** * Sets the issuer of this certificate. * * @param attrs the array of issuer attributes to use. * @param uniqueId an optional a unique ID to use. */ cert.setIssuer = function(attrs, uniqueId) { // set new attributes, clear hash _fillMissingFields(attrs); cert.issuer.attributes = attrs; delete cert.issuer.uniqueId; if(uniqueId) { // TODO: support arbitrary bit length ids cert.issuer.uniqueId = uniqueId; } cert.issuer.hash = null; }; /** * Sets the extensions of this certificate. * * @param exts the array of extensions to use. */ cert.setExtensions = function(exts) {
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/node-forge/lib/des.js
aws/lti-middleware/node_modules/node-forge/lib/des.js
/** * DES (Data Encryption Standard) implementation. * * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. * It is based on the BSD-licensed implementation by Paul Tero: * * Paul Tero, July 2001 * http://www.tero.co.uk/des/ * * Optimised for performance with large blocks by * Michael Hayworth, November 2001 * http://www.netdealing.com * * THIS SOFTWARE IS PROVIDED "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @author Stefan Siegl * @author Dave Longley * * Copyright (c) 2012 Stefan Siegl <[email protected]> * Copyright (c) 2012-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./cipher'); require('./cipherModes'); require('./util'); /* DES API */ module.exports = forge.des = forge.des || {}; /** * Deprecated. Instead, use: * * var cipher = forge.cipher.createCipher('DES-<mode>', key); * cipher.start({iv: iv}); * * Creates an DES cipher object to encrypt data using the given symmetric key. * The output will be stored in the 'output' member of the returned cipher. * * The key and iv may be given as binary-encoded strings of bytes or * byte buffers. * * @param key the symmetric key to use (64 or 192 bits). * @param iv the initialization vector to use. * @param output the buffer to write to, null to create one. * @param mode the cipher mode to use (default: 'CBC' if IV is * given, 'ECB' if null). * * @return the cipher. */ forge.des.startEncrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key: key, output: output, decrypt: false, mode: mode || (iv === null ? 'ECB' : 'CBC') }); cipher.start(iv); return cipher; }; /** * Deprecated. Instead, use: * * var cipher = forge.cipher.createCipher('DES-<mode>', key); * * Creates an DES cipher object to encrypt data using the given symmetric key. * * The key may be given as a binary-encoded string of bytes or a byte buffer. * * @param key the symmetric key to use (64 or 192 bits). * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.des.createEncryptionCipher = function(key, mode) { return _createCipher({ key: key, output: null, decrypt: false, mode: mode }); }; /** * Deprecated. Instead, use: * * var decipher = forge.cipher.createDecipher('DES-<mode>', key); * decipher.start({iv: iv}); * * Creates an DES cipher object to decrypt data using the given symmetric key. * The output will be stored in the 'output' member of the returned cipher. * * The key and iv may be given as binary-encoded strings of bytes or * byte buffers. * * @param key the symmetric key to use (64 or 192 bits). * @param iv the initialization vector to use. * @param output the buffer to write to, null to create one. * @param mode the cipher mode to use (default: 'CBC' if IV is * given, 'ECB' if null). * * @return the cipher. */ forge.des.startDecrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key: key, output: output, decrypt: true, mode: mode || (iv === null ? 'ECB' : 'CBC') }); cipher.start(iv); return cipher; }; /** * Deprecated. Instead, use: * * var decipher = forge.cipher.createDecipher('DES-<mode>', key); * * Creates an DES cipher object to decrypt data using the given symmetric key. * * The key may be given as a binary-encoded string of bytes or a byte buffer. * * @param key the symmetric key to use (64 or 192 bits). * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.des.createDecryptionCipher = function(key, mode) { return _createCipher({ key: key, output: null, decrypt: true, mode: mode }); }; /** * Creates a new DES cipher algorithm object. * * @param name the name of the algorithm. * @param mode the mode factory function. * * @return the DES algorithm object. */ forge.des.Algorithm = function(name, mode) { var self = this; self.name = name; self.mode = new mode({ blockSize: 8, cipher: { encrypt: function(inBlock, outBlock) { return _updateBlock(self._keys, inBlock, outBlock, false); }, decrypt: function(inBlock, outBlock) { return _updateBlock(self._keys, inBlock, outBlock, true); } } }); self._init = false; }; /** * Initializes this DES algorithm by expanding its key. * * @param options the options to use. * key the key to use with this algorithm. * decrypt true if the algorithm should be initialized for decryption, * false for encryption. */ forge.des.Algorithm.prototype.initialize = function(options) { if(this._init) { return; } var key = forge.util.createBuffer(options.key); if(this.name.indexOf('3DES') === 0) { if(key.length() !== 24) { throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); } } // do key expansion to 16 or 48 subkeys (single or triple DES) this._keys = _createKeys(key); this._init = true; }; /** Register DES algorithms **/ registerAlgorithm('DES-ECB', forge.cipher.modes.ecb); registerAlgorithm('DES-CBC', forge.cipher.modes.cbc); registerAlgorithm('DES-CFB', forge.cipher.modes.cfb); registerAlgorithm('DES-OFB', forge.cipher.modes.ofb); registerAlgorithm('DES-CTR', forge.cipher.modes.ctr); registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb); registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc); registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb); registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb); registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr); function registerAlgorithm(name, mode) { var factory = function() { return new forge.des.Algorithm(name, mode); }; forge.cipher.registerAlgorithm(name, factory); } /** DES implementation **/ var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; /** * Create necessary sub keys. * * @param key the 64-bit or 192-bit key. * * @return the expanded keys. */ function _createKeys(key) { var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; // how many iterations (1 for des, 3 for triple des) // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys var iterations = key.length() > 8 ? 3 : 1; // stores the return keys var keys = []; // now define the left shifts which need to be done var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; var n = 0, tmp; for(var j = 0; j < iterations; j++) { var left = key.getInt32(); var right = key.getInt32(); tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= tmp; left ^= (tmp << 4); tmp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= tmp; right ^= (tmp << -16); tmp = ((left >>> 2) ^ right) & 0x33333333; right ^= tmp; left ^= (tmp << 2); tmp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= tmp; right ^= (tmp << -16); tmp = ((left >>> 1) ^ right) & 0x55555555; right ^= tmp; left ^= (tmp << 1); tmp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= tmp; right ^= (tmp << 8); tmp = ((left >>> 1) ^ right) & 0x55555555; right ^= tmp; left ^= (tmp << 1); // right needs to be shifted and OR'd with last four bits of left tmp = (left << 8) | ((right >>> 20) & 0x000000f0); // left needs to be put upside down left = ((right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); right = tmp; // now go through and perform these shifts on the left and right keys for(var i = 0; i < shifts.length; ++i) { //shift the keys either one or two bits to the left if(shifts[i]) { left = (left << 2) | (left >>> 26); right = (right << 2) | (right >>> 26); } else { left = (left << 1) | (left >>> 27); right = (right << 1) | (right >>> 27); } left &= -0xf; right &= -0xf; // now apply PC-2, in such a way that E is easier when encrypting or // decrypting this conversion will look like PC-2 except only the last 6 // bits of each byte are used rather than 48 consecutive bits and the // order of lines will be according to how the S selection functions will // be applied: S2, S4, S6, S8, S1, S3, S5, S7 var lefttmp = ( pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | pc2bytes6[(left >>> 4) & 0xf]); var righttmp = ( pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | pc2bytes13[(right >>> 4) & 0xf]); tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; keys[n++] = lefttmp ^ tmp; keys[n++] = righttmp ^ (tmp << 16); } } return keys; } /** * Updates a single block (1 byte) using DES. The update will either * encrypt or decrypt the block. * * @param keys the expanded keys. * @param input the input block (an array of 32-bit words). * @param output the updated output block. * @param decrypt true to decrypt the block, false to encrypt it. */ function _updateBlock(keys, input, output, decrypt) { // set up loops for single or triple DES var iterations = keys.length === 32 ? 3 : 9; var looping; if(iterations === 3) { looping = decrypt ? [30, -2, -2] : [0, 32, 2]; } else { looping = (decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]); } var tmp; var left = input[0]; var right = input[1]; // first each 64 bit chunk of the message must be permuted according to IP tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= tmp; left ^= (tmp << 4); tmp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= tmp; left ^= (tmp << 16); tmp = ((right >>> 2) ^ left) & 0x33333333; left ^= tmp; right ^= (tmp << 2); tmp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= tmp; right ^= (tmp << 8); tmp = ((left >>> 1) ^ right) & 0x55555555; right ^= tmp; left ^= (tmp << 1); // rotate left 1 bit left = ((left << 1) | (left >>> 31)); right = ((right << 1) | (right >>> 31)); for(var j = 0; j < iterations; j += 3) { var endloop = looping[j + 1]; var loopinc = looping[j + 2]; // now go through and perform the encryption or decryption for(var i = looping[j]; i != endloop; i += loopinc) { var right1 = right ^ keys[i]; var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; // passing these bytes through the S selection functions tmp = left; left = right; right = tmp ^ ( spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f] | spfunction6[(right1 >>> 8) & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & 0x3f] | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]); } // unreverse left and right tmp = left; left = right; right = tmp; } // rotate right 1 bit left = ((left >>> 1) | (left << 31)); right = ((right >>> 1) | (right << 31)); // now perform IP-1, which is IP in the opposite direction tmp = ((left >>> 1) ^ right) & 0x55555555; right ^= tmp; left ^= (tmp << 1); tmp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= tmp; right ^= (tmp << 8); tmp = ((right >>> 2) ^ left) & 0x33333333; left ^= tmp; right ^= (tmp << 2); tmp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= tmp; left ^= (tmp << 16); tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= tmp; left ^= (tmp << 4); output[0] = left; output[1] = right; } /** * Deprecated. Instead, use: * * forge.cipher.createCipher('DES-<mode>', key); * forge.cipher.createDecipher('DES-<mode>', key); * * Creates a deprecated DES cipher object. This object's mode will default to * CBC (cipher-block-chaining). * * The key may be given as a binary-encoded string of bytes or a byte buffer. * * @param options the options to use. * key the symmetric key to use (64 or 192 bits). * output the buffer to write to. * decrypt true for decryption, false for encryption. * mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ function _createCipher(options) { options = options || {}; var mode = (options.mode || 'CBC').toUpperCase(); var algorithm = 'DES-' + mode; var cipher; if(options.decrypt) { cipher = forge.cipher.createDecipher(algorithm, options.key); } else { cipher = forge.cipher.createCipher(algorithm, options.key); } // backwards compatible start API var start = cipher.start; cipher.start = function(iv, options) { // backwards compatibility: support second arg as output buffer var output = null; if(options instanceof forge.util.ByteBuffer) { output = options; options = {}; } options = options || {}; options.output = output; options.iv = iv; start.call(cipher, options); }; return cipher; }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false