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/node-forge/lib/prng.js
aws/lti-middleware/node_modules/node-forge/lib/prng.js
/** * A javascript implementation of a cryptographically-secure * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed * here though the use of SHA-256 is not enforced; when generating an * a PRNG context, the hashing algorithm and block cipher used for * the generator are specified via a plugin. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); var _crypto = null; if(forge.util.isNodejs && !forge.options.usePureJavaScript && !process.versions['node-webkit']) { _crypto = require('crypto'); } /* PRNG API */ var prng = module.exports = forge.prng = forge.prng || {}; /** * Creates a new PRNG context. * * A PRNG plugin must be passed in that will provide: * * 1. A function that initializes the key and seed of a PRNG context. It * will be given a 16 byte key and a 16 byte seed. Any key expansion * or transformation of the seed from a byte string into an array of * integers (or similar) should be performed. * 2. The cryptographic function used by the generator. It takes a key and * a seed. * 3. A seed increment function. It takes the seed and returns seed + 1. * 4. An api to create a message digest. * * For an example, see random.js. * * @param plugin the PRNG plugin to use. */ prng.create = function(plugin) { var ctx = { plugin: plugin, key: null, seed: null, time: null, // number of reseeds so far reseeds: 0, // amount of data generated so far generated: 0, // no initial key bytes keyBytes: '' }; // create 32 entropy pools (each is a message digest) var md = plugin.md; var pools = new Array(32); for(var i = 0; i < 32; ++i) { pools[i] = md.create(); } ctx.pools = pools; // entropy pools are written to cyclically, starting at index 0 ctx.pool = 0; /** * Generates random bytes. The bytes may be generated synchronously or * asynchronously. Web workers must use the asynchronous interface or * else the behavior is undefined. * * @param count the number of random bytes to generate. * @param [callback(err, bytes)] called once the operation completes. * * @return count random bytes as a string. */ ctx.generate = function(count, callback) { // do synchronously if(!callback) { return ctx.generateSync(count); } // simple generator using counter-based CBC var cipher = ctx.plugin.cipher; var increment = ctx.plugin.increment; var formatKey = ctx.plugin.formatKey; var formatSeed = ctx.plugin.formatSeed; var b = forge.util.createBuffer(); // paranoid deviation from Fortuna: // reset key for every request to protect previously // generated random bytes should the key be discovered; // there is no 100ms based reseeding because of this // forced reseed for every `generate` call ctx.key = null; generate(); function generate(err) { if(err) { return callback(err); } // sufficient bytes generated if(b.length() >= count) { return callback(null, b.getBytes(count)); } // if amount of data generated is greater than 1 MiB, trigger reseed if(ctx.generated > 0xfffff) { ctx.key = null; } if(ctx.key === null) { // prevent stack overflow return forge.util.nextTick(function() { _reseed(generate); }); } // generate the random bytes var bytes = cipher(ctx.key, ctx.seed); ctx.generated += bytes.length; b.putBytes(bytes); // generate bytes for a new key and seed ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); forge.util.setImmediate(generate); } }; /** * Generates random bytes synchronously. * * @param count the number of random bytes to generate. * * @return count random bytes as a string. */ ctx.generateSync = function(count) { // simple generator using counter-based CBC var cipher = ctx.plugin.cipher; var increment = ctx.plugin.increment; var formatKey = ctx.plugin.formatKey; var formatSeed = ctx.plugin.formatSeed; // paranoid deviation from Fortuna: // reset key for every request to protect previously // generated random bytes should the key be discovered; // there is no 100ms based reseeding because of this // forced reseed for every `generateSync` call ctx.key = null; var b = forge.util.createBuffer(); while(b.length() < count) { // if amount of data generated is greater than 1 MiB, trigger reseed if(ctx.generated > 0xfffff) { ctx.key = null; } if(ctx.key === null) { _reseedSync(); } // generate the random bytes var bytes = cipher(ctx.key, ctx.seed); ctx.generated += bytes.length; b.putBytes(bytes); // generate bytes for a new key and seed ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); } return b.getBytes(count); }; /** * Private function that asynchronously reseeds a generator. * * @param callback(err) called once the operation completes. */ function _reseed(callback) { if(ctx.pools[0].messageLength >= 32) { _seed(); return callback(); } // not enough seed data... var needed = (32 - ctx.pools[0].messageLength) << 5; ctx.seedFile(needed, function(err, bytes) { if(err) { return callback(err); } ctx.collect(bytes); _seed(); callback(); }); } /** * Private function that synchronously reseeds a generator. */ function _reseedSync() { if(ctx.pools[0].messageLength >= 32) { return _seed(); } // not enough seed data... var needed = (32 - ctx.pools[0].messageLength) << 5; ctx.collect(ctx.seedFileSync(needed)); _seed(); } /** * Private function that seeds a generator once enough bytes are available. */ function _seed() { // update reseed count ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; // goal is to update `key` via: // key = hash(key + s) // where 's' is all collected entropy from selected pools, then... // create a plugin-based message digest var md = ctx.plugin.md.create(); // consume current key bytes md.update(ctx.keyBytes); // digest the entropy of pools whose index k meet the // condition 'n mod 2^k == 0' where n is the number of reseeds var _2powK = 1; for(var k = 0; k < 32; ++k) { if(ctx.reseeds % _2powK === 0) { md.update(ctx.pools[k].digest().getBytes()); ctx.pools[k].start(); } _2powK = _2powK << 1; } // get digest for key bytes ctx.keyBytes = md.digest().getBytes(); // paranoid deviation from Fortuna: // update `seed` via `seed = hash(key)` // instead of initializing to zero once and only // ever incrementing it md.start(); md.update(ctx.keyBytes); var seedBytes = md.digest().getBytes(); // update state ctx.key = ctx.plugin.formatKey(ctx.keyBytes); ctx.seed = ctx.plugin.formatSeed(seedBytes); ctx.generated = 0; } /** * The built-in default seedFile. This seedFile is used when entropy * is needed immediately. * * @param needed the number of bytes that are needed. * * @return the random bytes. */ function defaultSeedFile(needed) { // use window.crypto.getRandomValues strong source of entropy if available var getRandomValues = null; var globalScope = forge.util.globalScope; var _crypto = globalScope.crypto || globalScope.msCrypto; if(_crypto && _crypto.getRandomValues) { getRandomValues = function(arr) { return _crypto.getRandomValues(arr); }; } var b = forge.util.createBuffer(); if(getRandomValues) { while(b.length() < needed) { // max byte length is 65536 before QuotaExceededError is thrown // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); var entropy = new Uint32Array(Math.floor(count)); try { getRandomValues(entropy); for(var i = 0; i < entropy.length; ++i) { b.putInt32(entropy[i]); } } catch(e) { /* only ignore QuotaExceededError */ if(!(typeof QuotaExceededError !== 'undefined' && e instanceof QuotaExceededError)) { throw e; } } } } // be sad and add some weak random data if(b.length() < needed) { /* Draws from Park-Miller "minimal standard" 31 bit PRNG, implemented with David G. Carta's optimization: with 32 bit math and without division (Public Domain). */ var hi, lo, next; var seed = Math.floor(Math.random() * 0x010000); while(b.length() < needed) { lo = 16807 * (seed & 0xFFFF); hi = 16807 * (seed >> 16); lo += (hi & 0x7FFF) << 16; lo += hi >> 15; lo = (lo & 0x7FFFFFFF) + (lo >> 31); seed = lo & 0xFFFFFFFF; // consume lower 3 bytes of seed for(var i = 0; i < 3; ++i) { // throw in more pseudo random next = seed >>> (i << 3); next ^= Math.floor(Math.random() * 0x0100); b.putByte(next & 0xFF); } } } return b.getBytes(needed); } // initialize seed file APIs if(_crypto) { // use nodejs async API ctx.seedFile = function(needed, callback) { _crypto.randomBytes(needed, function(err, bytes) { if(err) { return callback(err); } callback(null, bytes.toString()); }); }; // use nodejs sync API ctx.seedFileSync = function(needed) { return _crypto.randomBytes(needed).toString(); }; } else { ctx.seedFile = function(needed, callback) { try { callback(null, defaultSeedFile(needed)); } catch(e) { callback(e); } }; ctx.seedFileSync = defaultSeedFile; } /** * Adds entropy to a prng ctx's accumulator. * * @param bytes the bytes of entropy as a string. */ ctx.collect = function(bytes) { // iterate over pools distributing entropy cyclically var count = bytes.length; for(var i = 0; i < count; ++i) { ctx.pools[ctx.pool].update(bytes.substr(i, 1)); ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; } }; /** * Collects an integer of n bits. * * @param i the integer entropy. * @param n the number of bits in the integer. */ ctx.collectInt = function(i, n) { var bytes = ''; for(var x = 0; x < n; x += 8) { bytes += String.fromCharCode((i >> x) & 0xFF); } ctx.collect(bytes); }; /** * Registers a Web Worker to receive immediate entropy from the main thread. * This method is required until Web Workers can access the native crypto * API. This method should be called twice for each created worker, once in * the main thread, and once in the worker itself. * * @param worker the worker to register. */ ctx.registerWorker = function(worker) { // worker receives random bytes if(worker === self) { ctx.seedFile = function(needed, callback) { function listener(e) { var data = e.data; if(data.forge && data.forge.prng) { self.removeEventListener('message', listener); callback(data.forge.prng.err, data.forge.prng.bytes); } } self.addEventListener('message', listener); self.postMessage({forge: {prng: {needed: needed}}}); }; } else { // main thread sends random bytes upon request var listener = function(e) { var data = e.data; if(data.forge && data.forge.prng) { ctx.seedFile(data.forge.prng.needed, function(err, bytes) { worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); }); } }; // TODO: do we need to remove the event listener when the worker dies? worker.addEventListener('message', listener); } }; return ctx; };
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/tlssocket.js
aws/lti-middleware/node_modules/node-forge/lib/tlssocket.js
/** * Socket wrapping functions for TLS. * * @author Dave Longley * * Copyright (c) 2009-2012 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./tls'); /** * Wraps a forge.net socket with a TLS layer. * * @param options: * sessionId: a session ID to reuse, null for a new connection if no session * cache is provided or it is empty. * caStore: an array of certificates to trust. * sessionCache: a session cache to use. * cipherSuites: an optional array of cipher suites to use, see * tls.CipherSuites. * socket: the socket to wrap. * virtualHost: the virtual server name to use in a TLS SNI extension. * verify: a handler used to custom verify certificates in the chain. * getCertificate: an optional callback used to get a certificate. * getPrivateKey: an optional callback used to get a private key. * getSignature: an optional callback used to get a signature. * deflate: function(inBytes) if provided, will deflate TLS records using * the deflate algorithm if the server supports it. * inflate: function(inBytes) if provided, will inflate TLS records using * the deflate algorithm if the server supports it. * * @return the TLS-wrapped socket. */ forge.tls.wrapSocket = function(options) { // get raw socket var socket = options.socket; // create TLS socket var tlsSocket = { id: socket.id, // set handlers connected: socket.connected || function(e) {}, closed: socket.closed || function(e) {}, data: socket.data || function(e) {}, error: socket.error || function(e) {} }; // create TLS connection var c = forge.tls.createConnection({ server: false, sessionId: options.sessionId || null, caStore: options.caStore || [], sessionCache: options.sessionCache || null, cipherSuites: options.cipherSuites || null, virtualHost: options.virtualHost, verify: options.verify, getCertificate: options.getCertificate, getPrivateKey: options.getPrivateKey, getSignature: options.getSignature, deflate: options.deflate, inflate: options.inflate, connected: function(c) { // first handshake complete, call handler if(c.handshakes === 1) { tlsSocket.connected({ id: socket.id, type: 'connect', bytesAvailable: c.data.length() }); } }, tlsDataReady: function(c) { // send TLS data over socket return socket.send(c.tlsData.getBytes()); }, dataReady: function(c) { // indicate application data is ready tlsSocket.data({ id: socket.id, type: 'socketData', bytesAvailable: c.data.length() }); }, closed: function(c) { // close socket socket.close(); }, error: function(c, e) { // send error, close socket tlsSocket.error({ id: socket.id, type: 'tlsError', message: e.message, bytesAvailable: 0, error: e }); socket.close(); } }); // handle doing handshake after connecting socket.connected = function(e) { c.handshake(options.sessionId); }; // handle closing TLS connection socket.closed = function(e) { if(c.open && c.handshaking) { // error tlsSocket.error({ id: socket.id, type: 'ioError', message: 'Connection closed during handshake.', bytesAvailable: 0 }); } c.close(); // call socket handler tlsSocket.closed({ id: socket.id, type: 'close', bytesAvailable: 0 }); }; // handle error on socket socket.error = function(e) { // error tlsSocket.error({ id: socket.id, type: e.type, message: e.message, bytesAvailable: 0 }); c.close(); }; // handle receiving raw TLS data from socket var _requiredBytes = 0; socket.data = function(e) { // drop data if connection not open if(!c.open) { socket.receive(e.bytesAvailable); } else { // only receive if there are enough bytes available to // process a record if(e.bytesAvailable >= _requiredBytes) { var count = Math.max(e.bytesAvailable, _requiredBytes); var data = socket.receive(count); if(data !== null) { _requiredBytes = c.process(data); } } } }; /** * Destroys this socket. */ tlsSocket.destroy = function() { socket.destroy(); }; /** * Sets this socket's TLS session cache. This should be called before * the socket is connected or after it is closed. * * The cache is an object mapping session IDs to internal opaque state. * An application might need to change the cache used by a particular * tlsSocket between connections if it accesses multiple TLS hosts. * * @param cache the session cache to use. */ tlsSocket.setSessionCache = function(cache) { c.sessionCache = tls.createSessionCache(cache); }; /** * Connects this socket. * * @param options: * host: the host to connect to. * port: the port to connect to. * policyPort: the policy port to use (if non-default), 0 to * use the flash default. * policyUrl: the policy file URL to use (instead of port). */ tlsSocket.connect = function(options) { socket.connect(options); }; /** * Closes this socket. */ tlsSocket.close = function() { c.close(); }; /** * Determines if the socket is connected or not. * * @return true if connected, false if not. */ tlsSocket.isConnected = function() { return c.isConnected && socket.isConnected(); }; /** * Writes bytes to this socket. * * @param bytes the bytes (as a string) to write. * * @return true on success, false on failure. */ tlsSocket.send = function(bytes) { return c.prepare(bytes); }; /** * Reads bytes from this socket (non-blocking). Fewer than the number of * bytes requested may be read if enough bytes are not available. * * This method should be called from the data handler if there are enough * bytes available. To see how many bytes are available, check the * 'bytesAvailable' property on the event in the data handler or call the * bytesAvailable() function on the socket. If the browser is msie, then the * bytesAvailable() function should be used to avoid race conditions. * Otherwise, using the property on the data handler's event may be quicker. * * @param count the maximum number of bytes to read. * * @return the bytes read (as a string) or null on error. */ tlsSocket.receive = function(count) { return c.data.getBytes(count); }; /** * Gets the number of bytes available for receiving on the socket. * * @return the number of bytes available for receiving. */ tlsSocket.bytesAvailable = function() { return c.data.length(); }; return tlsSocket; };
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/aes.js
aws/lti-middleware/node_modules/node-forge/lib/aes.js
/** * Advanced Encryption Standard (AES) implementation. * * This implementation is based on the public domain library 'jscrypto' which * was written by: * * Emily Stark ([email protected]) * Mike Hamburg ([email protected]) * Dan Boneh ([email protected]) * * Parts of this code are based on the OpenSSL implementation of AES: * http://www.openssl.org * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./cipher'); require('./cipherModes'); require('./util'); /* AES API */ module.exports = forge.aes = forge.aes || {}; /** * Deprecated. Instead, use: * * var cipher = forge.cipher.createCipher('AES-<mode>', key); * cipher.start({iv: iv}); * * Creates an AES 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 a string of bytes, an array of bytes, * a byte buffer, or an array of 32-bit words. * * @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. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.startEncrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key: key, output: output, decrypt: false, mode: mode }); cipher.start(iv); return cipher; }; /** * Deprecated. Instead, use: * * var cipher = forge.cipher.createCipher('AES-<mode>', key); * * Creates an AES cipher object to encrypt data using the given symmetric key. * * The key may be given as a string of bytes, an array of bytes, a * byte buffer, or an array of 32-bit words. * * @param key the symmetric key to use. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.createEncryptionCipher = function(key, mode) { return _createCipher({ key: key, output: null, decrypt: false, mode: mode }); }; /** * Deprecated. Instead, use: * * var decipher = forge.cipher.createDecipher('AES-<mode>', key); * decipher.start({iv: iv}); * * Creates an AES 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 a string of bytes, an array of bytes, * a byte buffer, or an array of 32-bit words. * * @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. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.startDecrypting = function(key, iv, output, mode) { var cipher = _createCipher({ key: key, output: output, decrypt: true, mode: mode }); cipher.start(iv); return cipher; }; /** * Deprecated. Instead, use: * * var decipher = forge.cipher.createDecipher('AES-<mode>', key); * * Creates an AES cipher object to decrypt data using the given symmetric key. * * The key may be given as a string of bytes, an array of bytes, a * byte buffer, or an array of 32-bit words. * * @param key the symmetric key to use. * @param mode the cipher mode to use (default: 'CBC'). * * @return the cipher. */ forge.aes.createDecryptionCipher = function(key, mode) { return _createCipher({ key: key, output: null, decrypt: true, mode: mode }); }; /** * Creates a new AES cipher algorithm object. * * @param name the name of the algorithm. * @param mode the mode factory function. * * @return the AES algorithm object. */ forge.aes.Algorithm = function(name, mode) { if(!init) { initialize(); } var self = this; self.name = name; self.mode = new mode({ blockSize: 16, cipher: { encrypt: function(inBlock, outBlock) { return _updateBlock(self._w, inBlock, outBlock, false); }, decrypt: function(inBlock, outBlock) { return _updateBlock(self._w, inBlock, outBlock, true); } } }); self._init = false; }; /** * Initializes this AES 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.aes.Algorithm.prototype.initialize = function(options) { if(this._init) { return; } var key = options.key; var tmp; /* Note: The key may be a string of bytes, an array of bytes, a byte buffer, or an array of 32-bit integers. If the key is in bytes, then it must be 16, 24, or 32 bytes in length. If it is in 32-bit integers, it must be 4, 6, or 8 integers long. */ if(typeof key === 'string' && (key.length === 16 || key.length === 24 || key.length === 32)) { // convert key string into byte buffer key = forge.util.createBuffer(key); } else if(forge.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { // convert key integer array into byte buffer tmp = key; key = forge.util.createBuffer(); for(var i = 0; i < tmp.length; ++i) { key.putByte(tmp[i]); } } // convert key byte buffer into 32-bit integer array if(!forge.util.isArray(key)) { tmp = key; key = []; // key lengths of 16, 24, 32 bytes allowed var len = tmp.length(); if(len === 16 || len === 24 || len === 32) { len = len >>> 2; for(var i = 0; i < len; ++i) { key.push(tmp.getInt32()); } } } // key must be an array of 32-bit integers by now if(!forge.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { throw new Error('Invalid key parameter.'); } // encryption operation is always used for these modes var mode = this.mode.name; var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); // do key expansion this._w = _expandKey(key, options.decrypt && !encryptOp); this._init = true; }; /** * Expands a key. Typically only used for testing. * * @param key the symmetric key to expand, as an array of 32-bit words. * @param decrypt true to expand for decryption, false for encryption. * * @return the expanded key. */ forge.aes._expandKey = function(key, decrypt) { if(!init) { initialize(); } return _expandKey(key, decrypt); }; /** * Updates a single block. Typically only used for testing. * * @param w the expanded key to use. * @param input an array of block-size 32-bit words. * @param output an array of block-size 32-bit words. * @param decrypt true to decrypt, false to encrypt. */ forge.aes._updateBlock = _updateBlock; /** Register AES algorithms **/ registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); function registerAlgorithm(name, mode) { var factory = function() { return new forge.aes.Algorithm(name, mode); }; forge.cipher.registerAlgorithm(name, factory); } /** AES implementation **/ var init = false; // not yet initialized var Nb = 4; // number of words comprising the state (AES = 4) var sbox; // non-linear substitution table used in key expansion var isbox; // inversion of sbox var rcon; // round constant word array var mix; // mix-columns table var imix; // inverse mix-columns table /** * Performs initialization, ie: precomputes tables to optimize for speed. * * One way to understand how AES works is to imagine that 'addition' and * 'multiplication' are interfaces that require certain mathematical * properties to hold true (ie: they are associative) but they might have * different implementations and produce different kinds of results ... * provided that their mathematical properties remain true. AES defines * its own methods of addition and multiplication but keeps some important * properties the same, ie: associativity and distributivity. The * explanation below tries to shed some light on how AES defines addition * and multiplication of bytes and 32-bit words in order to perform its * encryption and decryption algorithms. * * The basics: * * The AES algorithm views bytes as binary representations of polynomials * that have either 1 or 0 as the coefficients. It defines the addition * or subtraction of two bytes as the XOR operation. It also defines the * multiplication of two bytes as a finite field referred to as GF(2^8) * (Note: 'GF' means "Galois Field" which is a field that contains a finite * number of elements so GF(2^8) has 256 elements). * * This means that any two bytes can be represented as binary polynomials; * when they multiplied together and modularly reduced by an irreducible * polynomial of the 8th degree, the results are the field GF(2^8). The * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. * This multiplication is associative with 0x01 as the identity: * * (b * 0x01 = GF(b, 0x01) = b). * * The operation GF(b, 0x02) can be performed at the byte level by left * shifting b once and then XOR'ing it (to perform the modular reduction) * with 0x11b if b is >= 128. Repeated application of the multiplication * of 0x02 can be used to implement the multiplication of any two bytes. * * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these * factors can each be multiplied by 0x57 and then added together. To do * the multiplication, values for 0x57 multiplied by each of these 3 factors * can be precomputed and stored in a table. To add them, the values from * the table are XOR'd together. * * AES also defines addition and multiplication of words, that is 4-byte * numbers represented as polynomials of 3 degrees where the coefficients * are the values of the bytes. * * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. * * Addition is performed by XOR'ing like powers of x. Multiplication * is performed in two steps, the first is an algebriac expansion as * you would do normally (where addition is XOR). But the result is * a polynomial larger than 3 degrees and thus it cannot fit in a word. So * next the result is modularly reduced by an AES-specific polynomial of * degree 4 which will always produce a polynomial of less than 4 degrees * such that it will fit in a word. In AES, this polynomial is x^4 + 1. * * The modular product of two polynomials 'a' and 'b' is thus: * * d(x) = d3x^3 + d2x^2 + d1x + d0 * with * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) * * As a matrix: * * [d0] = [a0 a3 a2 a1][b0] * [d1] [a1 a0 a3 a2][b1] * [d2] [a2 a1 a0 a3][b2] * [d3] [a3 a2 a1 a0][b3] * * Special polynomials defined by AES (0x02 == {02}): * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. * * These polynomials are used in the MixColumns() and InverseMixColumns() * operations, respectively, to cause each element in the state to affect * the output (referred to as diffusing). * * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the * polynomial x3. * * The ShiftRows() method modifies the last 3 rows in the state (where * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. * The 1st byte in the second row is moved to the end of the row. The 1st * and 2nd bytes in the third row are moved to the end of the row. The 1st, * 2nd, and 3rd bytes are moved in the fourth row. * * More details on how AES arithmetic works: * * In the polynomial representation of binary numbers, XOR performs addition * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) * corresponds with the multiplication of polynomials modulo an irreducible * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply * polynomial 'a' with polynomial 'b' and then do a modular reduction by * an AES-specific irreducible polynomial of degree 8. * * A polynomial is irreducible if its only divisors are one and itself. For * the AES algorithm, this irreducible polynomial is: * * m(x) = x^8 + x^4 + x^3 + x + 1, * * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: * 100011011 = 283 = 0x11b. * * For example, GF(0x57, 0x83) = 0xc1 because * * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 * 0x85 = 131 = 10000101 = x^7 + x + 1 * * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) * = x^13 + x^11 + x^9 + x^8 + x^7 + * x^7 + x^5 + x^3 + x^2 + x + * x^6 + x^4 + x^2 + x + 1 * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y * y modulo (x^8 + x^4 + x^3 + x + 1) * = x^7 + x^6 + 1. * * The modular reduction by m(x) guarantees the result will be a binary * polynomial of less than degree 8, so that it can fit in a byte. * * The operation to multiply a binary polynomial b with x (the polynomial * x in binary representation is 00000010) is: * * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 * * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the * most significant bit is 0 in b) then the result is already reduced. If * it is 1, then we can reduce it by subtracting m(x) via an XOR. * * It follows that multiplication by x (00000010 or 0x02) can be implemented * by performing a left shift followed by a conditional bitwise XOR with * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by * higher powers of x can be implemented by repeated application of xtime(). * * By adding intermediate results, multiplication by any constant can be * implemented. For instance: * * GF(0x57, 0x13) = 0xfe because: * * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) * * Note: We XOR with 0x11b instead of 0x1b because in javascript our * datatype for b can be larger than 1 byte, so a left shift will not * automatically eliminate bits that overflow a byte ... by XOR'ing the * overflow bit with 1 (the extra one from 0x11b) we zero it out. * * GF(0x57, 0x02) = xtime(0x57) = 0xae * GF(0x57, 0x04) = xtime(0xae) = 0x47 * GF(0x57, 0x08) = xtime(0x47) = 0x8e * GF(0x57, 0x10) = xtime(0x8e) = 0x07 * * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) * * And by the distributive property (since XOR is addition and GF() is * multiplication): * * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) * = 0x57 ^ 0xae ^ 0x07 * = 0xfe. */ function initialize() { init = true; /* Populate the Rcon table. These are the values given by [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) in the field of GF(2^8), where i starts at 1. rcon[0] = [0x00, 0x00, 0x00, 0x00] rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 ... rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 We only store the first byte because it is the only one used. */ rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; // compute xtime table which maps i onto GF(i, 0x02) var xtime = new Array(256); for(var i = 0; i < 128; ++i) { xtime[i] = i << 1; xtime[i + 128] = (i + 128) << 1 ^ 0x11B; } // compute all other tables sbox = new Array(256); isbox = new Array(256); mix = new Array(4); imix = new Array(4); for(var i = 0; i < 4; ++i) { mix[i] = new Array(256); imix[i] = new Array(256); } var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; for(var i = 0; i < 256; ++i) { /* We need to generate the SubBytes() sbox and isbox tables so that we can perform byte substitutions. This requires us to traverse all of the elements in GF, find their multiplicative inverses, and apply to each the following affine transformation: bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ b(i + 7) mod 8 ^ ci for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the ith bit of a byte c with the value {63} or {01100011}. It is possible to traverse every possible value in a Galois field using what is referred to as a 'generator'. There are many generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully traverse GF we iterate 255 times, multiplying by our generator each time. On each iteration we can determine the multiplicative inverse for the current element. Suppose there is an element in GF 'e'. For a given generator 'g', e = g^x. The multiplicative inverse of e is g^(255 - x). It turns out that if use the inverse of a generator as another generator it will produce all of the corresponding multiplicative inverses at the same time. For this reason, we choose 5 as our inverse generator because it only requires 2 multiplies and 1 add and its inverse, 82, requires relatively few operations as well. In order to apply the affine transformation, the multiplicative inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and 'x'. Then 's' is left shifted and the high bit of 's' is made the low bit. The resulting value is stored in 's'. Then 'x' is XOR'd with 's' and stored in 'x'. On each subsequent iteration the same operation is performed. When 4 iterations are complete, 'x' is XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. For example: s = 01000001 x = 01000001 iteration 1: s = 10000010, x ^= s iteration 2: s = 00000101, x ^= s iteration 3: s = 00001010, x ^= s iteration 4: s = 00010100, x ^= s x ^= 0x63 This can be done with a loop where s = (s << 1) | (s >> 7). However, it can also be done by using a single 16-bit (in this case 32-bit) number 'sx'. Since XOR is an associative operation, we can set 'sx' to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. The most significant bits will flow into the high 8 bit positions and be correctly XOR'd with one another. All that remains will be to cycle the high 8 bits by XOR'ing them all with the lower 8 bits afterwards. At the same time we're populating sbox and isbox we can precompute the multiplication we'll need to do to do MixColumns() later. */ // apply affine transformation sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); sx = (sx >> 8) ^ (sx & 255) ^ 0x63; // update tables sbox[e] = sx; isbox[sx] = e; /* Mixing columns is done using matrix multiplication. The columns that are to be mixed are each a single word in the current state. The state has Nb columns (4 columns). Therefore each column is a 4 byte word. So to mix the columns in a single column 'c' where its rows are r0, r1, r2, and r3, we use the following matrix multiplication: [2 3 1 1]*[r0,c]=[r'0,c] [1 2 3 1] [r1,c] [r'1,c] [1 1 2 3] [r2,c] [r'2,c] [3 1 1 2] [r3,c] [r'3,c] r0, r1, r2, and r3 are each 1 byte of one of the words in the state (a column). To do matrix multiplication for each mixed column c' we multiply the corresponding row from the left matrix with the corresponding column from the right matrix. In total, we get 4 equations: r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c As usual, the multiplication is as previously defined and the addition is XOR. In order to optimize mixing columns we can store the multiplication results in tables. If you think of the whole column as a word (it might help to visualize by mentally rotating the equations above by counterclockwise 90 degrees) then you can see that it would be useful to map the multiplications performed on each byte (r0, r1, r2, r3) onto a word as well. For instance, we could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the highest 8 bits and 3*r0 in the lowest 8 bits (with the other two respectively in the middle). This means that a table can be constructed that uses r0 as an index to the word. We can do the same with r1, r2, and r3, creating a total of 4 tables. To construct a full c', we can just look up each byte of c in their respective tables and XOR the results together. Also, to build each table we only have to calculate the word for 2,1,1,3 for every byte ... which we can do on each iteration of this loop since we will iterate over every byte. After we have calculated 2,1,1,3 we can get the results for the other tables by cycling the byte at the end to the beginning. For instance we can take the result of table 2,1,1,3 and produce table 3,2,1,1 by moving the right most byte to the left most position just like how you can imagine the 3 moved out of 2,1,1,3 and to the front to produce 3,2,1,1. There is another optimization in that the same multiples of the current element we need in order to advance our generator to the next iteration can be reused in performing the 2,1,1,3 calculation. We also calculate the inverse mix column tables, with e,9,d,b being the inverse of 2,1,1,3. When we're done, and we need to actually mix columns, the first byte of each state word should be put through mix[0] (2,1,1,3), the second through mix[1] (3,2,1,1) and so forth. Then they should be XOR'd together to produce the fully mixed column. */ // calculate mix and imix table values sx2 = xtime[sx]; e2 = xtime[e]; e4 = xtime[e2]; e8 = xtime[e4]; me = (sx2 << 24) ^ // 2 (sx << 16) ^ // 1 (sx << 8) ^ // 1 (sx ^ sx2); // 3 ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) (e ^ e8) << 16 ^ // 9 (e ^ e4 ^ e8) << 8 ^ // D (13) (e ^ e2 ^ e8); // B (11) // produce each of the mix tables by rotating the 2,1,1,3 value for(var n = 0; n < 4; ++n) { mix[n][e] = me; imix[n][sx] = ime; // cycle the right most byte to the left most position // ie: 2,1,1,3 becomes 3,2,1,1 me = me << 24 | me >>> 8; ime = ime << 24 | ime >>> 8; } // get next element and inverse if(e === 0) { // 1 is the inverse of 1 e = ei = 1; } else { // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; ei ^= xtime[xtime[ei]]; } } } /** * Generates a key schedule using the AES key expansion algorithm. * * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion * routine to generate a key schedule. The Key Expansion generates a total * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, * and each of the Nr rounds requires Nb words of key data. The resulting * key schedule consists of a linear array of 4-byte words, denoted [wi ], * with i in the range 0 <= i < Nb(Nr + 1). * * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) * AES-128 (Nb=4, Nk=4, Nr=10) * AES-192 (Nb=4, Nk=6, Nr=12) * AES-256 (Nb=4, Nk=8, Nr=14) * Note: Nr=Nk+6. * * Nb is the number of columns (32-bit words) comprising the State (or * number of bytes in a block). For AES, Nb=4. * * @param key the key to schedule (as an array of 32-bit words). * @param decrypt true to modify the key schedule to decrypt, false not to. * * @return the generated key schedule. */ function _expandKey(key, decrypt) { // copy the key's words to initialize the key schedule var w = key.slice(0); /* RotWord() will rotate a word, moving the first byte to the last byte's position (shifting the other bytes left). We will be getting the value of Rcon at i / Nk. 'i' will iterate from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will increase by 1. We use a counter iNk to keep track of this. */ // go through the rounds expanding the key var temp, iNk = 1; var Nk = w.length; var Nr1 = Nk + 6 + 1; var end = Nb * Nr1; for(var i = Nk; i < end; ++i) { temp = w[i - 1]; if(i % Nk === 0) { // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ (rcon[iNk] << 24); iNk++; } else if(Nk > 6 && (i % Nk === 4)) { // temp = SubWord(temp) temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; } w[i] = w[i - Nk] ^ temp; } /* When we are updating a cipher block we always use the code path for encryption whether we are decrypting or not (to shorten code and simplify the generation of look up tables). However, because there are differences in the decryption algorithm, other than just swapping in different look up tables, we must transform our key schedule to account for these changes: 1. The decryption algorithm gets its key rounds in reverse order. 2. The decryption algorithm adds the round key before mixing columns instead of afterwards. We don't need to modify our key schedule to handle the first case, we can just traverse the key schedule in reverse order when decrypting. The second case requires a little work. The tables we built for performing rounds will take an input and then perform SubBytes() and MixColumns() or, for the decrypt version, InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires us to AddRoundKey() before InvMixColumns(). This means we'll need to apply some transformations to the round key to inverse-mix its columns so they'll be correct for moving AddRoundKey() to after the state has had its columns inverse-mixed. To inverse-mix the columns of the state when we're decrypting we use a lookup table that will apply InvSubBytes() and InvMixColumns() at the same time. However, the round key's bytes are not inverse-substituted in the decryption algorithm. To get around this problem, we can first substitute the bytes in the round key so that when we apply the transformation via the InvSubBytes()+InvMixColumns() table, it will undo our substitution leaving us with the original value that we want -- and then inverse-mix that value. This change will correctly alter our key schedule so that we can XOR each round key with our already transformed decryption state. This allows us to use the same code path as the encryption algorithm. We make one more change to the decryption key. Since the decryption algorithm runs in reverse from the encryption algorithm, we reverse the order of the round keys to avoid having to iterate over the key schedule backwards when running the encryption algorithm later in decryption mode. In addition to reversing the order of the round keys, we also swap each round key's 2nd and 4th rows. See the comments section where rounds are performed for more details about why this is done. These changes are done inline with the other substitution described above. */ if(decrypt) { var tmp; var m0 = imix[0]; var m1 = imix[1]; var m2 = imix[2]; var m3 = imix[3]; var wnew = w.slice(0); end = w.length; for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { // do not sub the first or last round key (round keys are Nb // words) as no column mixing is performed before they are added, // but do change the key order if(i === 0 || i === (end - Nb)) { wnew[i] = w[wi]; wnew[i + 1] = w[wi + 3]; wnew[i + 2] = w[wi + 2]; wnew[i + 3] = w[wi + 1]; } else { // substitute each round key byte because the inverse-mix // table will inverse-substitute it (effectively cancel the // substitution because round key bytes aren't sub'd in // decryption mode) and swap indexes 3 and 1 for(var n = 0; n < Nb; ++n) { tmp = w[wi + n]; wnew[i + (3&-n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; } } } w = wnew; } return w; } /** * Updates a single block (16 bytes) using AES. The update will either * encrypt or decrypt the block. * * @param w the key schedule. * @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(w, input, output, decrypt) { /* Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) begin byte state[4,Nb] state = in AddRoundKey(state, w[0, Nb-1]) for round = 1 step 1 to Nr-1 SubBytes(state) ShiftRows(state) MixColumns(state) AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) end for SubBytes(state) ShiftRows(state) AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) out = state end InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) begin byte state[4,Nb] state = in AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) for round = Nr-1 step -1 downto 1 InvShiftRows(state) InvSubBytes(state) AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) InvMixColumns(state) end for InvShiftRows(state) InvSubBytes(state) AddRoundKey(state, w[0, Nb-1]) out = state end */ // Encrypt: AddRoundKey(state, w[0, Nb-1]) // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) var Nr = w.length / 4 - 1; var m0, m1, m2, m3, sub; if(decrypt) { m0 = imix[0]; m1 = imix[1]; m2 = imix[2]; m3 = imix[3]; sub = isbox; } else { m0 = mix[0]; m1 = mix[1]; m2 = mix[2]; m3 = mix[3]; sub = sbox; } var a, b, c, d, a2, b2, c2; a = input[0] ^ w[0]; b = input[decrypt ? 3 : 1] ^ w[1]; c = input[2] ^ w[2]; d = input[decrypt ? 1 : 3] ^ w[3]; var i = 3; /* In order to share code we follow the encryption algorithm when both encrypting and decrypting. To account for the changes required in the decryption algorithm, we use different lookup tables when decrypting and use a modified key schedule to account for the difference in the order of transformations applied when performing rounds. We also get key rounds in reverse order (relative to encryption). */ for(var round = 1; round < Nr; ++round) { /* As described above, we'll be using table lookups to perform the column mixing. Each column is stored as a word in the state (the array 'input' has one column as a word at each index). In order to mix a column, we perform these transformations on each row in c, which is 1 byte in each word. The new column for c0 is c'0: m0 m1 m2 m3 r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 So using mix tables where c0 is a word with r0 being its upper 8 bits and r3 being its lower 8 bits: m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] ... m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] Therefore to mix the columns in each word in the state we do the following (& 255 omitted for brevity): c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
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/oids.js
aws/lti-middleware/node_modules/node-forge/lib/oids.js
/** * Object IDs for ASN.1. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = require('./forge'); forge.pki = forge.pki || {}; var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {}; // set id to name mapping and name to id mapping function _IN(id, name) { oids[id] = name; oids[name] = id; } // set id to name mapping only function _I_(id, name) { oids[id] = name; } // algorithm OIDs _IN('1.2.840.113549.1.1.1', 'rsaEncryption'); // Note: md2 & md4 not implemented //_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); //_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); _IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); _IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); _IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); _IN('1.2.840.113549.1.1.8', 'mgf1'); _IN('1.2.840.113549.1.1.9', 'pSpecified'); _IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); _IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); _IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); _IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); // Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 _IN('1.3.101.112', 'EdDSA25519'); _IN('1.2.840.10040.4.3', 'dsa-with-sha1'); _IN('1.3.14.3.2.7', 'desCBC'); _IN('1.3.14.3.2.26', 'sha1'); // Deprecated equivalent of sha1WithRSAEncryption _IN('1.3.14.3.2.29', 'sha1WithRSASignature'); _IN('2.16.840.1.101.3.4.2.1', 'sha256'); _IN('2.16.840.1.101.3.4.2.2', 'sha384'); _IN('2.16.840.1.101.3.4.2.3', 'sha512'); _IN('2.16.840.1.101.3.4.2.4', 'sha224'); _IN('2.16.840.1.101.3.4.2.5', 'sha512-224'); _IN('2.16.840.1.101.3.4.2.6', 'sha512-256'); _IN('1.2.840.113549.2.2', 'md2'); _IN('1.2.840.113549.2.5', 'md5'); // pkcs#7 content types _IN('1.2.840.113549.1.7.1', 'data'); _IN('1.2.840.113549.1.7.2', 'signedData'); _IN('1.2.840.113549.1.7.3', 'envelopedData'); _IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); _IN('1.2.840.113549.1.7.5', 'digestedData'); _IN('1.2.840.113549.1.7.6', 'encryptedData'); // pkcs#9 oids _IN('1.2.840.113549.1.9.1', 'emailAddress'); _IN('1.2.840.113549.1.9.2', 'unstructuredName'); _IN('1.2.840.113549.1.9.3', 'contentType'); _IN('1.2.840.113549.1.9.4', 'messageDigest'); _IN('1.2.840.113549.1.9.5', 'signingTime'); _IN('1.2.840.113549.1.9.6', 'counterSignature'); _IN('1.2.840.113549.1.9.7', 'challengePassword'); _IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); _IN('1.2.840.113549.1.9.14', 'extensionRequest'); _IN('1.2.840.113549.1.9.20', 'friendlyName'); _IN('1.2.840.113549.1.9.21', 'localKeyId'); _IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); // pkcs#12 safe bags _IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); _IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); _IN('1.2.840.113549.1.12.10.1.3', 'certBag'); _IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); _IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); _IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); // password-based-encryption for pkcs#12 _IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); _IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); _IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); _IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); _IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); _IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); _IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); _IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); // hmac OIDs _IN('1.2.840.113549.2.7', 'hmacWithSHA1'); _IN('1.2.840.113549.2.8', 'hmacWithSHA224'); _IN('1.2.840.113549.2.9', 'hmacWithSHA256'); _IN('1.2.840.113549.2.10', 'hmacWithSHA384'); _IN('1.2.840.113549.2.11', 'hmacWithSHA512'); // symmetric key algorithm oids _IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); _IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); _IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); _IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); // certificate issuer/subject OIDs _IN('2.5.4.3', 'commonName'); _IN('2.5.4.4', 'surname'); _IN('2.5.4.5', 'serialNumber'); _IN('2.5.4.6', 'countryName'); _IN('2.5.4.7', 'localityName'); _IN('2.5.4.8', 'stateOrProvinceName'); _IN('2.5.4.9', 'streetAddress'); _IN('2.5.4.10', 'organizationName'); _IN('2.5.4.11', 'organizationalUnitName'); _IN('2.5.4.12', 'title'); _IN('2.5.4.13', 'description'); _IN('2.5.4.15', 'businessCategory'); _IN('2.5.4.17', 'postalCode'); _IN('2.5.4.42', 'givenName'); _IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); _IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); // X.509 extension OIDs _IN('2.16.840.1.113730.1.1', 'nsCertType'); _IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used _I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 _I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 _I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 _I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 _I_('2.5.29.5', 'policyMapping'); // deprecated use .33 _I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 _I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 _I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 _I_('2.5.29.9', 'subjectDirectoryAttributes'); _I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 _I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 _I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 _I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 _IN('2.5.29.14', 'subjectKeyIdentifier'); _IN('2.5.29.15', 'keyUsage'); _I_('2.5.29.16', 'privateKeyUsagePeriod'); _IN('2.5.29.17', 'subjectAltName'); _IN('2.5.29.18', 'issuerAltName'); _IN('2.5.29.19', 'basicConstraints'); _I_('2.5.29.20', 'cRLNumber'); _I_('2.5.29.21', 'cRLReason'); _I_('2.5.29.22', 'expirationDate'); _I_('2.5.29.23', 'instructionCode'); _I_('2.5.29.24', 'invalidityDate'); _I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 _I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 _I_('2.5.29.27', 'deltaCRLIndicator'); _I_('2.5.29.28', 'issuingDistributionPoint'); _I_('2.5.29.29', 'certificateIssuer'); _I_('2.5.29.30', 'nameConstraints'); _IN('2.5.29.31', 'cRLDistributionPoints'); _IN('2.5.29.32', 'certificatePolicies'); _I_('2.5.29.33', 'policyMappings'); _I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 _IN('2.5.29.35', 'authorityKeyIdentifier'); _I_('2.5.29.36', 'policyConstraints'); _IN('2.5.29.37', 'extKeyUsage'); _I_('2.5.29.46', 'freshestCRL'); _I_('2.5.29.54', 'inhibitAnyPolicy'); // extKeyUsage purposes _IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); _IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); _IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); _IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); _IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); _IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); _IN('1.3.6.1.5.5.7.3.8', 'timeStamping');
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/baseN.js
aws/lti-middleware/node_modules/node-forge/lib/baseN.js
/** * Base-N/Base-X encoding/decoding functions. * * Original implementation from base-x: * https://github.com/cryptocoinjs/base-x * * Which is MIT licensed: * * The MIT License (MIT) * * Copyright base-x contributors (c) 2016 * * 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. */ var api = {}; module.exports = api; // baseN alphabet indexes var _reverseAlphabets = {}; /** * BaseN-encodes a Uint8Array using the given alphabet. * * @param input the Uint8Array to encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the baseN-encoded output string. */ api.encode = function(input, alphabet, maxline) { if(typeof alphabet !== 'string') { throw new TypeError('"alphabet" must be a string.'); } if(maxline !== undefined && typeof maxline !== 'number') { throw new TypeError('"maxline" must be a number.'); } var output = ''; if(!(input instanceof Uint8Array)) { // assume forge byte buffer output = _encodeWithByteBuffer(input, alphabet); } else { var i = 0; var base = alphabet.length; var first = alphabet.charAt(0); var digits = [0]; for(i = 0; i < input.length; ++i) { for(var j = 0, carry = input[i]; j < digits.length; ++j) { carry += digits[j] << 8; digits[j] = carry % base; carry = (carry / base) | 0; } while(carry > 0) { digits.push(carry % base); carry = (carry / base) | 0; } } // deal with leading zeros for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { output += first; } // convert digits to a string for(i = digits.length - 1; i >= 0; --i) { output += alphabet[digits[i]]; } } if(maxline) { var regex = new RegExp('.{1,' + maxline + '}', 'g'); output = output.match(regex).join('\r\n'); } return output; }; /** * Decodes a baseN-encoded (using the given alphabet) string to a * Uint8Array. * * @param input the baseN-encoded input string. * * @return the Uint8Array. */ api.decode = function(input, alphabet) { if(typeof input !== 'string') { throw new TypeError('"input" must be a string.'); } if(typeof alphabet !== 'string') { throw new TypeError('"alphabet" must be a string.'); } var table = _reverseAlphabets[alphabet]; if(!table) { // compute reverse alphabet table = _reverseAlphabets[alphabet] = []; for(var i = 0; i < alphabet.length; ++i) { table[alphabet.charCodeAt(i)] = i; } } // remove whitespace characters input = input.replace(/\s/g, ''); var base = alphabet.length; var first = alphabet.charAt(0); var bytes = [0]; for(var i = 0; i < input.length; i++) { var value = table[input.charCodeAt(i)]; if(value === undefined) { return; } for(var j = 0, carry = value; j < bytes.length; ++j) { carry += bytes[j] * base; bytes[j] = carry & 0xff; carry >>= 8; } while(carry > 0) { bytes.push(carry & 0xff); carry >>= 8; } } // deal with leading zeros for(var k = 0; input[k] === first && k < input.length - 1; ++k) { bytes.push(0); } if(typeof Buffer !== 'undefined') { return Buffer.from(bytes.reverse()); } return new Uint8Array(bytes.reverse()); }; function _encodeWithByteBuffer(input, alphabet) { var i = 0; var base = alphabet.length; var first = alphabet.charAt(0); var digits = [0]; for(i = 0; i < input.length(); ++i) { for(var j = 0, carry = input.at(i); j < digits.length; ++j) { carry += digits[j] << 8; digits[j] = carry % base; carry = (carry / base) | 0; } while(carry > 0) { digits.push(carry % base); carry = (carry / base) | 0; } } var output = ''; // deal with leading zeros for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { output += first; } // convert digits to a string for(i = digits.length - 1; i >= 0; --i) { output += alphabet[digits[i]]; } return output; }
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/asn1.js
aws/lti-middleware/node_modules/node-forge/lib/asn1.js
/** * Javascript implementation of Abstract Syntax Notation Number One. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. * * An API for storing data using the Abstract Syntax Notation Number One * format using DER (Distinguished Encoding Rules) encoding. This encoding is * commonly used to store data for PKI, i.e. X.509 Certificates, and this * implementation exists for that purpose. * * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract * syntax of information without restricting the way the information is encoded * for transmission. It provides a standard that allows for open systems * communication. ASN.1 defines the syntax of information data and a number of * simple data types as well as a notation for describing them and specifying * values for them. * * The RSA algorithm creates public and private keys that are often stored in * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This * class provides the most basic functionality required to store and load DSA * keys that are encoded according to ASN.1. * * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) * and DER (Distinguished Encoding Rules). DER is just a subset of BER that * has stricter requirements for how data must be encoded. * * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) * and a byte array for the value of this ASN1 structure which may be data or a * list of ASN.1 structures. * * Each ASN.1 structure using BER is (Tag-Length-Value): * * | byte 0 | bytes X | bytes Y | * |--------|---------|---------- * | tag | length | value | * * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to * be two or more octets, but that is not supported by this class. A tag is * only 1 byte. Bits 1-5 give the tag number (ie the data type within a * particular 'class'), 6 indicates whether or not the ASN.1 value is * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, * then the class is APPLICATION. If only bit 8 is set, then the class is * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. * The tag numbers for the data types for the class UNIVERSAL are listed below: * * UNIVERSAL 0 Reserved for use by the encoding rules * UNIVERSAL 1 Boolean type * UNIVERSAL 2 Integer type * UNIVERSAL 3 Bitstring type * UNIVERSAL 4 Octetstring type * UNIVERSAL 5 Null type * UNIVERSAL 6 Object identifier type * UNIVERSAL 7 Object descriptor type * UNIVERSAL 8 External type and Instance-of type * UNIVERSAL 9 Real type * UNIVERSAL 10 Enumerated type * UNIVERSAL 11 Embedded-pdv type * UNIVERSAL 12 UTF8String type * UNIVERSAL 13 Relative object identifier type * UNIVERSAL 14-15 Reserved for future editions * UNIVERSAL 16 Sequence and Sequence-of types * UNIVERSAL 17 Set and Set-of types * UNIVERSAL 18-22, 25-30 Character string types * UNIVERSAL 23-24 Time types * * The length of an ASN.1 structure is specified after the tag identifier. * There is a definite form and an indefinite form. The indefinite form may * be used if the encoding is constructed and not all immediately available. * The indefinite form is encoded using a length byte with only the 8th bit * set. The end of the constructed object is marked using end-of-contents * octets (two zero bytes). * * The definite form looks like this: * * The length may take up 1 or more bytes, it depends on the length of the * value of the ASN.1 structure. DER encoding requires that if the ASN.1 * structure has a value that has a length greater than 127, more than 1 byte * will be used to store its length, otherwise just one byte will be used. * This is strict. * * In the case that the length of the ASN.1 value is less than 127, 1 octet * (byte) is used to store the "short form" length. The 8th bit has a value of * 0 indicating the length is "short form" and not "long form" and bits 7-1 * give the length of the data. (The 8th bit is the left-most, most significant * bit: also known as big endian or network format). * * In the case that the length of the ASN.1 value is greater than 127, 2 to * 127 octets (bytes) are used to store the "long form" length. The first * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 * give the number of additional octets. All following octets are in base 256 * with the most significant digit first (typical big-endian binary unsigned * integer storage). So, for instance, if the length of a value was 257, the * first byte would be set to: * * 10000010 = 130 = 0x82. * * This indicates there are 2 octets (base 256) for the length. The second and * third bytes (the octets just mentioned) would store the length in base 256: * * octet 2: 00000001 = 1 * 256^1 = 256 * octet 3: 00000001 = 1 * 256^0 = 1 * total = 257 * * The algorithm for converting a js integer value of 257 to base-256 is: * * var value = 257; * var bytes = []; * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first * bytes[1] = value & 0xFF; // least significant byte last * * On the ASN.1 UNIVERSAL Object Identifier (OID) type: * * An OID can be written like: "value1.value2.value3...valueN" * * The DER encoding rules: * * The first byte has the value 40 * value1 + value2. * The following bytes, if any, encode the remaining values. Each value is * encoded in base 128, most significant digit first (big endian), with as * few digits as possible, and the most significant bit of each byte set * to 1 except the last in each value's encoding. For example: Given the * OID "1.2.840.113549", its DER encoding is (remember each byte except the * last one in each encoding is OR'd with 0x80): * * byte 1: 40 * 1 + 2 = 42 = 0x2A. * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D * * The final value is: 0x2A864886F70D. * The full OID (including ASN.1 tag and length of 6 bytes) is: * 0x06062A864886F70D */ var forge = require('./forge'); require('./util'); require('./oids'); /* ASN.1 API */ var asn1 = module.exports = forge.asn1 = forge.asn1 || {}; /** * ASN.1 classes. */ asn1.Class = { UNIVERSAL: 0x00, APPLICATION: 0x40, CONTEXT_SPECIFIC: 0x80, PRIVATE: 0xC0 }; /** * ASN.1 types. Not all types are supported by this implementation, only * those necessary to implement a simple PKI are implemented. */ asn1.Type = { NONE: 0, BOOLEAN: 1, INTEGER: 2, BITSTRING: 3, OCTETSTRING: 4, NULL: 5, OID: 6, ODESC: 7, EXTERNAL: 8, REAL: 9, ENUMERATED: 10, EMBEDDED: 11, UTF8: 12, ROID: 13, SEQUENCE: 16, SET: 17, PRINTABLESTRING: 19, IA5STRING: 22, UTCTIME: 23, GENERALIZEDTIME: 24, BMPSTRING: 30 }; /** * Creates a new asn1 object. * * @param tagClass the tag class for the object. * @param type the data type (tag number) for the object. * @param constructed true if the asn1 object is in constructed form. * @param value the value for the object, if it is not constructed. * @param [options] the options to use: * [bitStringContents] the plain BIT STRING content including padding * byte. * * @return the asn1 object. */ asn1.create = function(tagClass, type, constructed, value, options) { /* An asn1 object has a tagClass, a type, a constructed flag, and a value. The value's type depends on the constructed flag. If constructed, it will contain a list of other asn1 objects. If not, it will contain the ASN.1 value as an array of bytes formatted according to the ASN.1 data type. */ // remove undefined values if(forge.util.isArray(value)) { var tmp = []; for(var i = 0; i < value.length; ++i) { if(value[i] !== undefined) { tmp.push(value[i]); } } value = tmp; } var obj = { tagClass: tagClass, type: type, constructed: constructed, composed: constructed || forge.util.isArray(value), value: value }; if(options && 'bitStringContents' in options) { // TODO: copy byte buffer if it's a buffer not a string obj.bitStringContents = options.bitStringContents; // TODO: add readonly flag to avoid this overhead // save copy to detect changes obj.original = asn1.copy(obj); } return obj; }; /** * Copies an asn1 object. * * @param obj the asn1 object. * @param [options] copy options: * [excludeBitStringContents] true to not copy bitStringContents * * @return the a copy of the asn1 object. */ asn1.copy = function(obj, options) { var copy; if(forge.util.isArray(obj)) { copy = []; for(var i = 0; i < obj.length; ++i) { copy.push(asn1.copy(obj[i], options)); } return copy; } if(typeof obj === 'string') { // TODO: copy byte buffer if it's a buffer not a string return obj; } copy = { tagClass: obj.tagClass, type: obj.type, constructed: obj.constructed, composed: obj.composed, value: asn1.copy(obj.value, options) }; if(options && !options.excludeBitStringContents) { // TODO: copy byte buffer if it's a buffer not a string copy.bitStringContents = obj.bitStringContents; } return copy; }; /** * Compares asn1 objects for equality. * * Note this function does not run in constant time. * * @param obj1 the first asn1 object. * @param obj2 the second asn1 object. * @param [options] compare options: * [includeBitStringContents] true to compare bitStringContents * * @return true if the asn1 objects are equal. */ asn1.equals = function(obj1, obj2, options) { if(forge.util.isArray(obj1)) { if(!forge.util.isArray(obj2)) { return false; } if(obj1.length !== obj2.length) { return false; } for(var i = 0; i < obj1.length; ++i) { if(!asn1.equals(obj1[i], obj2[i])) { return false; } } return true; } if(typeof obj1 !== typeof obj2) { return false; } if(typeof obj1 === 'string') { return obj1 === obj2; } var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); if(options && options.includeBitStringContents) { equal = equal && (obj1.bitStringContents === obj2.bitStringContents); } return equal; }; /** * Gets the length of a BER-encoded ASN.1 value. * * In case the length is not specified, undefined is returned. * * @param b the BER-encoded ASN.1 byte buffer, starting with the first * length byte. * * @return the length of the BER-encoded ASN.1 value or undefined. */ asn1.getBerValueLength = function(b) { // TODO: move this function and related DER/BER functions to a der.js // file; better abstract ASN.1 away from der/ber. var b2 = b.getByte(); if(b2 === 0x80) { return undefined; } // see if the length is "short form" or "long form" (bit 8 set) var length; var longForm = b2 & 0x80; if(!longForm) { // length is just the first byte length = b2; } else { // the number of bytes the length is specified in bits 7 through 1 // and each length byte is in big-endian base-256 length = b.getInt((b2 & 0x7F) << 3); } return length; }; /** * Check if the byte buffer has enough bytes. Throws an Error if not. * * @param bytes the byte buffer to parse from. * @param remaining the bytes remaining in the current parsing state. * @param n the number of bytes the buffer must have. */ function _checkBufferLength(bytes, remaining, n) { if(n > remaining) { var error = new Error('Too few bytes to parse DER.'); error.available = bytes.length(); error.remaining = remaining; error.requested = n; throw error; } } /** * Gets the length of a BER-encoded ASN.1 value. * * In case the length is not specified, undefined is returned. * * @param bytes the byte buffer to parse from. * @param remaining the bytes remaining in the current parsing state. * * @return the length of the BER-encoded ASN.1 value or undefined. */ var _getValueLength = function(bytes, remaining) { // TODO: move this function and related DER/BER functions to a der.js // file; better abstract ASN.1 away from der/ber. // fromDer already checked that this byte exists var b2 = bytes.getByte(); remaining--; if(b2 === 0x80) { return undefined; } // see if the length is "short form" or "long form" (bit 8 set) var length; var longForm = b2 & 0x80; if(!longForm) { // length is just the first byte length = b2; } else { // the number of bytes the length is specified in bits 7 through 1 // and each length byte is in big-endian base-256 var longFormBytes = b2 & 0x7F; _checkBufferLength(bytes, remaining, longFormBytes); length = bytes.getInt(longFormBytes << 3); } // FIXME: this will only happen for 32 bit getInt with high bit set if(length < 0) { throw new Error('Negative length: ' + length); } return length; }; /** * Parses an asn1 object from a byte buffer in DER format. * * @param bytes the byte buffer to parse from. * @param [strict] true to be strict when checking value lengths, false to * allow truncated values (default: true). * @param [options] object with options or boolean strict flag * [strict] true to be strict when checking value lengths, false to * allow truncated values (default: true). * [parseAllBytes] true to ensure all bytes are parsed * (default: true) * [decodeBitStrings] true to attempt to decode the content of * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that * without schema support to understand the data context this can * erroneously decode values that happen to be valid ASN.1. This * flag will be deprecated or removed as soon as schema support is * available. (default: true) * * @throws Will throw an error for various malformed input conditions. * * @return the parsed asn1 object. */ asn1.fromDer = function(bytes, options) { if(options === undefined) { options = { strict: true, parseAllBytes: true, decodeBitStrings: true }; } if(typeof options === 'boolean') { options = { strict: options, parseAllBytes: true, decodeBitStrings: true }; } if(!('strict' in options)) { options.strict = true; } if(!('parseAllBytes' in options)) { options.parseAllBytes = true; } if(!('decodeBitStrings' in options)) { options.decodeBitStrings = true; } // wrap in buffer if needed if(typeof bytes === 'string') { bytes = forge.util.createBuffer(bytes); } var byteCount = bytes.length(); var value = _fromDer(bytes, bytes.length(), 0, options); if(options.parseAllBytes && bytes.length() !== 0) { var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.'); error.byteCount = byteCount; error.remaining = bytes.length(); throw error; } return value; }; /** * Internal function to parse an asn1 object from a byte buffer in DER format. * * @param bytes the byte buffer to parse from. * @param remaining the number of bytes remaining for this chunk. * @param depth the current parsing depth. * @param options object with same options as fromDer(). * * @return the parsed asn1 object. */ function _fromDer(bytes, remaining, depth, options) { // temporary storage for consumption calculations var start; // minimum length for ASN.1 DER structure is 2 _checkBufferLength(bytes, remaining, 2); // get the first byte var b1 = bytes.getByte(); // consumed one byte remaining--; // get the tag class var tagClass = (b1 & 0xC0); // get the type (bits 1-5) var type = b1 & 0x1F; // get the variable value length and adjust remaining bytes start = bytes.length(); var length = _getValueLength(bytes, remaining); remaining -= start - bytes.length(); // ensure there are enough bytes to get the value if(length !== undefined && length > remaining) { if(options.strict) { var error = new Error('Too few bytes to read ASN.1 value.'); error.available = bytes.length(); error.remaining = remaining; error.requested = length; throw error; } // Note: be lenient with truncated values and use remaining state bytes length = remaining; } // value storage var value; // possible BIT STRING contents storage var bitStringContents; // constructed flag is bit 6 (32 = 0x20) of the first byte var constructed = ((b1 & 0x20) === 0x20); if(constructed) { // parse child asn1 objects from the value value = []; if(length === undefined) { // asn1 object of indefinite length, read until end tag for(;;) { _checkBufferLength(bytes, remaining, 2); if(bytes.bytes(2) === String.fromCharCode(0, 0)) { bytes.getBytes(2); remaining -= 2; break; } start = bytes.length(); value.push(_fromDer(bytes, remaining, depth + 1, options)); remaining -= start - bytes.length(); } } else { // parsing asn1 object of definite length while(length > 0) { start = bytes.length(); value.push(_fromDer(bytes, length, depth + 1, options)); remaining -= start - bytes.length(); length -= start - bytes.length(); } } } // if a BIT STRING, save the contents including padding if(value === undefined && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { bitStringContents = bytes.bytes(length); } // determine if a non-constructed value should be decoded as a composed // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) // can be used this way. if(value === undefined && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here // .. other parts of forge expect to decode OCTET STRINGs manually (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && length > 1) { // save read position var savedRead = bytes.read; var savedRemaining = remaining; var unused = 0; if(type === asn1.Type.BITSTRING) { /* The first octet gives the number of bits by which the length of the bit string is less than the next multiple of eight (this is called the "number of unused bits"). The second and following octets give the value of the bit string converted to an octet string. */ _checkBufferLength(bytes, remaining, 1); unused = bytes.getByte(); remaining--; } // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs if(unused === 0) { try { // attempt to parse child asn1 object from the value // (stored in array to signal composed value) start = bytes.length(); var subOptions = { // enforce strict mode to avoid parsing ASN.1 from plain data strict: true, decodeBitStrings: true }; var composed = _fromDer(bytes, remaining, depth + 1, subOptions); var used = start - bytes.length(); remaining -= used; if(type == asn1.Type.BITSTRING) { used++; } // if the data all decoded and the class indicates UNIVERSAL or // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object var tc = composed.tagClass; if(used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { value = [composed]; } } catch(ex) { } } if(value === undefined) { // restore read position bytes.read = savedRead; remaining = savedRemaining; } } if(value === undefined) { // asn1 not constructed or composed, get raw value // TODO: do DER to OID conversion and vice-versa in .toDer? if(length === undefined) { if(options.strict) { throw new Error('Non-constructed ASN.1 object of indefinite length.'); } // be lenient and use remaining state bytes length = remaining; } if(type === asn1.Type.BMPSTRING) { value = ''; for(; length > 0; length -= 2) { _checkBufferLength(bytes, remaining, 2); value += String.fromCharCode(bytes.getInt16()); remaining -= 2; } } else { value = bytes.getBytes(length); remaining -= length; } } // add BIT STRING contents if available var asn1Options = bitStringContents === undefined ? null : { bitStringContents: bitStringContents }; // create and return asn1 object return asn1.create(tagClass, type, constructed, value, asn1Options); } /** * Converts the given asn1 object to a buffer of bytes in DER format. * * @param asn1 the asn1 object to convert to bytes. * * @return the buffer of bytes. */ asn1.toDer = function(obj) { var bytes = forge.util.createBuffer(); // build the first byte var b1 = obj.tagClass | obj.type; // for storing the ASN.1 value var value = forge.util.createBuffer(); // use BIT STRING contents if available and data not changed var useBitStringContents = false; if('bitStringContents' in obj) { useBitStringContents = true; if(obj.original) { useBitStringContents = asn1.equals(obj, obj.original); } } if(useBitStringContents) { value.putBytes(obj.bitStringContents); } else if(obj.composed) { // if composed, use each child asn1 object's DER bytes as value // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed // from other asn1 objects if(obj.constructed) { b1 |= 0x20; } else { // type is a bit string, add unused bits of 0x00 value.putByte(0x00); } // add all of the child DER bytes together for(var i = 0; i < obj.value.length; ++i) { if(obj.value[i] !== undefined) { value.putBuffer(asn1.toDer(obj.value[i])); } } } else { // use asn1.value directly if(obj.type === asn1.Type.BMPSTRING) { for(var i = 0; i < obj.value.length; ++i) { value.putInt16(obj.value.charCodeAt(i)); } } else { // ensure integer is minimally-encoded // TODO: should all leading bytes be stripped vs just one? // .. ex '00 00 01' => '01'? if(obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer ((obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 0x80) === 0) || // leading 0xFF for negative integer (obj.value.charCodeAt(0) === 0xFF && (obj.value.charCodeAt(1) & 0x80) === 0x80))) { value.putBytes(obj.value.substr(1)); } else { value.putBytes(obj.value); } } } // add tag byte bytes.putByte(b1); // use "short form" encoding if(value.length() <= 127) { // one byte describes the length // bit 8 = 0 and bits 7-1 = length bytes.putByte(value.length() & 0x7F); } else { // use "long form" encoding // 2 to 127 bytes describe the length // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes // other bytes: length in base 256, big-endian var len = value.length(); var lenBytes = ''; do { lenBytes += String.fromCharCode(len & 0xFF); len = len >>> 8; } while(len > 0); // set first byte to # bytes used to store the length and turn on // bit 8 to indicate long-form length is used bytes.putByte(lenBytes.length | 0x80); // concatenate length bytes in reverse since they were generated // little endian and we need big endian for(var i = lenBytes.length - 1; i >= 0; --i) { bytes.putByte(lenBytes.charCodeAt(i)); } } // concatenate value bytes bytes.putBuffer(value); return bytes; }; /** * Converts an OID dot-separated string to a byte buffer. The byte buffer * contains only the DER-encoded value, not any tag or length bytes. * * @param oid the OID dot-separated string. * * @return the byte buffer. */ asn1.oidToDer = function(oid) { // split OID into individual values var values = oid.split('.'); var bytes = forge.util.createBuffer(); // first byte is 40 * value1 + value2 bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); // other bytes are each value in base 128 with 8th bit set except for // the last byte for each value var last, valueBytes, value, b; for(var i = 2; i < values.length; ++i) { // produce value bytes in reverse because we don't know how many // bytes it will take to store the value last = true; valueBytes = []; value = parseInt(values[i], 10); do { b = value & 0x7F; value = value >>> 7; // if value is not last, then turn on 8th bit if(!last) { b |= 0x80; } valueBytes.push(b); last = false; } while(value > 0); // add value bytes in reverse (needs to be in big endian) for(var n = valueBytes.length - 1; n >= 0; --n) { bytes.putByte(valueBytes[n]); } } return bytes; }; /** * Converts a DER-encoded byte buffer to an OID dot-separated string. The * byte buffer should contain only the DER-encoded value, not any tag or * length bytes. * * @param bytes the byte buffer. * * @return the OID dot-separated string. */ asn1.derToOid = function(bytes) { var oid; // wrap in buffer if needed if(typeof bytes === 'string') { bytes = forge.util.createBuffer(bytes); } // first byte is 40 * value1 + value2 var b = bytes.getByte(); oid = Math.floor(b / 40) + '.' + (b % 40); // other bytes are each value in base 128 with 8th bit set except for // the last byte for each value var value = 0; while(bytes.length() > 0) { b = bytes.getByte(); value = value << 7; // not the last byte for the value if(b & 0x80) { value += b & 0x7F; } else { // last byte oid += '.' + (value + b); value = 0; } } return oid; }; /** * Converts a UTCTime value to a date. * * Note: GeneralizedTime has 4 digits for the year and is used for X.509 * dates past 2049. Parsing that structure hasn't been implemented yet. * * @param utc the UTCTime value to convert. * * @return the date. */ asn1.utcTimeToDate = function(utc) { /* The following formats can be used: YYMMDDhhmmZ YYMMDDhhmm+hh'mm' YYMMDDhhmm-hh'mm' YYMMDDhhmmssZ YYMMDDhhmmss+hh'mm' YYMMDDhhmmss-hh'mm' Where: YY is the least significant two digits of the year MM is the month (01 to 12) DD is the day (01 to 31) hh is the hour (00 to 23) mm are the minutes (00 to 59) ss are the seconds (00 to 59) Z indicates that local time is GMT, + indicates that local time is later than GMT, and - indicates that local time is earlier than GMT hh' is the absolute value of the offset from GMT in hours mm' is the absolute value of the offset from GMT in minutes */ var date = new Date(); // if YY >= 50 use 19xx, if YY < 50 use 20xx var year = parseInt(utc.substr(0, 2), 10); year = (year >= 50) ? 1900 + year : 2000 + year; var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month var DD = parseInt(utc.substr(4, 2), 10); var hh = parseInt(utc.substr(6, 2), 10); var mm = parseInt(utc.substr(8, 2), 10); var ss = 0; // not just YYMMDDhhmmZ if(utc.length > 11) { // get character after minutes var c = utc.charAt(10); var end = 10; // see if seconds are present if(c !== '+' && c !== '-') { // get seconds ss = parseInt(utc.substr(10, 2), 10); end += 2; } } // update date date.setUTCFullYear(year, MM, DD); date.setUTCHours(hh, mm, ss, 0); if(end) { // get +/- after end of time c = utc.charAt(end); if(c === '+' || c === '-') { // get hours+minutes offset var hhoffset = parseInt(utc.substr(end + 1, 2), 10); var mmoffset = parseInt(utc.substr(end + 4, 2), 10); // calculate offset in milliseconds var offset = hhoffset * 60 + mmoffset; offset *= 60000; // apply offset if(c === '+') { date.setTime(+date - offset); } else { date.setTime(+date + offset); } } } return date; }; /** * Converts a GeneralizedTime value to a date. * * @param gentime the GeneralizedTime value to convert. * * @return the date. */ asn1.generalizedTimeToDate = function(gentime) { /* The following formats can be used: YYYYMMDDHHMMSS YYYYMMDDHHMMSS.fff YYYYMMDDHHMMSSZ YYYYMMDDHHMMSS.fffZ YYYYMMDDHHMMSS+hh'mm' YYYYMMDDHHMMSS.fff+hh'mm' YYYYMMDDHHMMSS-hh'mm' YYYYMMDDHHMMSS.fff-hh'mm' Where: YYYY is the year MM is the month (01 to 12) DD is the day (01 to 31) hh is the hour (00 to 23) mm are the minutes (00 to 59) ss are the seconds (00 to 59) .fff is the second fraction, accurate to three decimal places Z indicates that local time is GMT, + indicates that local time is later than GMT, and - indicates that local time is earlier than GMT hh' is the absolute value of the offset from GMT in hours mm' is the absolute value of the offset from GMT in minutes */ var date = new Date(); var YYYY = parseInt(gentime.substr(0, 4), 10); var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month var DD = parseInt(gentime.substr(6, 2), 10); var hh = parseInt(gentime.substr(8, 2), 10); var mm = parseInt(gentime.substr(10, 2), 10); var ss = parseInt(gentime.substr(12, 2), 10); var fff = 0; var offset = 0; var isUTC = false; if(gentime.charAt(gentime.length - 1) === 'Z') { isUTC = true; } var end = gentime.length - 5, c = gentime.charAt(end); if(c === '+' || c === '-') { // get hours+minutes offset var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); // calculate offset in milliseconds offset = hhoffset * 60 + mmoffset; offset *= 60000; // apply offset if(c === '+') { offset *= -1; } isUTC = true; } // check for second fraction if(gentime.charAt(14) === '.') { fff = parseFloat(gentime.substr(14), 10) * 1000; } if(isUTC) { date.setUTCFullYear(YYYY, MM, DD); date.setUTCHours(hh, mm, ss, fff); // apply offset date.setTime(+date + offset); } else { date.setFullYear(YYYY, MM, DD); date.setHours(hh, mm, ss, fff); } return date; }; /** * Converts a date to a UTCTime value. * * Note: GeneralizedTime has 4 digits for the year and is used for X.509 * dates past 2049. Converting to a GeneralizedTime hasn't been * implemented yet. * * @param date the date to convert. * * @return the UTCTime value. */ asn1.dateToUtcTime = function(date) { // TODO: validate; currently assumes proper format if(typeof date === 'string') { return date; } var rval = ''; // create format YYMMDDhhmmssZ var format = []; format.push(('' + date.getUTCFullYear()).substr(2)); format.push('' + (date.getUTCMonth() + 1)); format.push('' + date.getUTCDate()); format.push('' + date.getUTCHours()); format.push('' + date.getUTCMinutes()); format.push('' + date.getUTCSeconds()); // ensure 2 digits are used for each format entry for(var i = 0; i < format.length; ++i) { if(format[i].length < 2) { rval += '0'; } rval += format[i]; } rval += 'Z'; return rval; }; /** * Converts a date to a GeneralizedTime value. * * @param date the date to convert. * * @return the GeneralizedTime value as a string. */ asn1.dateToGeneralizedTime = function(date) { // TODO: validate; currently assumes proper format if(typeof date === 'string') { return date; } var rval = ''; // create format YYYYMMDDHHMMSSZ var format = []; format.push('' + date.getUTCFullYear()); format.push('' + (date.getUTCMonth() + 1)); format.push('' + date.getUTCDate()); format.push('' + date.getUTCHours()); format.push('' + date.getUTCMinutes()); format.push('' + date.getUTCSeconds()); // ensure 2 digits are used for each format entry for(var i = 0; i < format.length; ++i) { if(format[i].length < 2) { rval += '0';
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/pkcs7.js
aws/lti-middleware/node_modules/node-forge/lib/pkcs7.js
/** * Javascript implementation of PKCS#7 v1.5. * * @author Stefan Siegl * @author Dave Longley * * Copyright (c) 2012 Stefan Siegl <[email protected]> * Copyright (c) 2012-2015 Digital Bazaar, Inc. * * Currently this implementation only supports ContentType of EnvelopedData, * EncryptedData, or SignedData at the root level. The top level elements may * contain only a ContentInfo of ContentType Data, i.e. plain data. Further * nesting is not (yet) supported. * * The Forge validators for PKCS #7's ASN.1 structures are available from * a separate file pkcs7asn1.js, since those are referenced from other * PKCS standards like PKCS #12. */ var forge = require('./forge'); require('./aes'); require('./asn1'); require('./des'); require('./oids'); require('./pem'); require('./pkcs7asn1'); require('./random'); require('./util'); require('./x509'); // shortcut for ASN.1 API var asn1 = forge.asn1; // shortcut for PKCS#7 API var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {}; /** * Converts a PKCS#7 message from PEM format. * * @param pem the PEM-formatted PKCS#7 message. * * @return the PKCS#7 message. */ p7.messageFromPem = function(pem) { var msg = forge.pem.decode(pem)[0]; if(msg.type !== 'PKCS7') { var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + 'header type is not "PKCS#7".'); error.headerType = msg.type; throw error; } if(msg.procType && msg.procType.type === 'ENCRYPTED') { throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); } // convert DER to ASN.1 object var obj = asn1.fromDer(msg.body); return p7.messageFromAsn1(obj); }; /** * Converts a PKCS#7 message to PEM format. * * @param msg The PKCS#7 message object * @param maxline The maximum characters per line, defaults to 64. * * @return The PEM-formatted PKCS#7 message. */ p7.messageToPem = function(msg, maxline) { // convert to ASN.1, then DER, then PEM-encode var pemObj = { type: 'PKCS7', body: asn1.toDer(msg.toAsn1()).getBytes() }; return forge.pem.encode(pemObj, {maxline: maxline}); }; /** * Converts a PKCS#7 message from an ASN.1 object. * * @param obj the ASN.1 representation of a ContentInfo. * * @return the PKCS#7 message. */ p7.messageFromAsn1 = function(obj) { // validate root level ContentInfo and capture data var capture = {}; var errors = []; if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { var error = new Error('Cannot read PKCS#7 message. ' + 'ASN.1 object is not an PKCS#7 ContentInfo.'); error.errors = errors; throw error; } var contentType = asn1.derToOid(capture.contentType); var msg; switch(contentType) { case forge.pki.oids.envelopedData: msg = p7.createEnvelopedData(); break; case forge.pki.oids.encryptedData: msg = p7.createEncryptedData(); break; case forge.pki.oids.signedData: msg = p7.createSignedData(); break; default: throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + contentType + ' is not (yet) supported.'); } msg.fromAsn1(capture.content.value[0]); return msg; }; p7.createSignedData = function() { var msg = null; msg = { type: forge.pki.oids.signedData, version: 1, certificates: [], crls: [], // TODO: add json-formatted signer stuff here? signers: [], // populated during sign() digestAlgorithmIdentifiers: [], contentInfo: null, signerInfos: [], fromAsn1: function(obj) { // validate SignedData content block and capture data. _fromAsn1(msg, obj, p7.asn1.signedDataValidator); msg.certificates = []; msg.crls = []; msg.digestAlgorithmIdentifiers = []; msg.contentInfo = null; msg.signerInfos = []; if(msg.rawCapture.certificates) { var certs = msg.rawCapture.certificates.value; for(var i = 0; i < certs.length; ++i) { msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); } } // TODO: parse crls }, toAsn1: function() { // degenerate case with no content if(!msg.contentInfo) { msg.sign(); } var certs = []; for(var i = 0; i < msg.certificates.length; ++i) { certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); } var crls = []; // TODO: implement CRLs // [0] SignedData var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Version asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(msg.version).getBytes()), // DigestAlgorithmIdentifiers asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SET, true, msg.digestAlgorithmIdentifiers), // ContentInfo msg.contentInfo ]) ]); if(certs.length > 0) { // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL signedData.value[0].value.push( asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); } if(crls.length > 0) { // [1] IMPLICIT CertificateRevocationLists OPTIONAL signedData.value[0].value.push( asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); } // SignerInfos signedData.value[0].value.push( asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, msg.signerInfos)); // ContentInfo return asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // ContentType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(msg.type).getBytes()), // [0] SignedData signedData ]); }, /** * Add (another) entity to list of signers. * * Note: If authenticatedAttributes are provided, then, per RFC 2315, * they must include at least two attributes: content type and * message digest. The message digest attribute value will be * auto-calculated during signing and will be ignored if provided. * * Here's an example of providing these two attributes: * * forge.pkcs7.createSignedData(); * p7.addSigner({ * issuer: cert.issuer.attributes, * serialNumber: cert.serialNumber, * key: privateKey, * digestAlgorithm: forge.pki.oids.sha1, * authenticatedAttributes: [{ * type: forge.pki.oids.contentType, * value: forge.pki.oids.data * }, { * type: forge.pki.oids.messageDigest * }] * }); * * TODO: Support [subjectKeyIdentifier] as signer's ID. * * @param signer the signer information: * key the signer's private key. * [certificate] a certificate containing the public key * associated with the signer's private key; use this option as * an alternative to specifying signer.issuer and * signer.serialNumber. * [issuer] the issuer attributes (eg: cert.issuer.attributes). * [serialNumber] the signer's certificate's serial number in * hexadecimal (eg: cert.serialNumber). * [digestAlgorithm] the message digest OID, as a string, to use * (eg: forge.pki.oids.sha1). * [authenticatedAttributes] an optional array of attributes * to also sign along with the content. */ addSigner: function(signer) { var issuer = signer.issuer; var serialNumber = signer.serialNumber; if(signer.certificate) { var cert = signer.certificate; if(typeof cert === 'string') { cert = forge.pki.certificateFromPem(cert); } issuer = cert.issuer.attributes; serialNumber = cert.serialNumber; } var key = signer.key; if(!key) { throw new Error( 'Could not add PKCS#7 signer; no private key specified.'); } if(typeof key === 'string') { key = forge.pki.privateKeyFromPem(key); } // ensure OID known for digest algorithm var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; switch(digestAlgorithm) { case forge.pki.oids.sha1: case forge.pki.oids.sha256: case forge.pki.oids.sha384: case forge.pki.oids.sha512: case forge.pki.oids.md5: break; default: throw new Error( 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + digestAlgorithm); } // if authenticatedAttributes is present, then the attributes // must contain at least PKCS #9 content-type and message-digest var authenticatedAttributes = signer.authenticatedAttributes || []; if(authenticatedAttributes.length > 0) { var contentType = false; var messageDigest = false; for(var i = 0; i < authenticatedAttributes.length; ++i) { var attr = authenticatedAttributes[i]; if(!contentType && attr.type === forge.pki.oids.contentType) { contentType = true; if(messageDigest) { break; } continue; } if(!messageDigest && attr.type === forge.pki.oids.messageDigest) { messageDigest = true; if(contentType) { break; } continue; } } if(!contentType || !messageDigest) { throw new Error('Invalid signer.authenticatedAttributes. If ' + 'signer.authenticatedAttributes is specified, then it must ' + 'contain at least two attributes, PKCS #9 content-type and ' + 'PKCS #9 message-digest.'); } } msg.signers.push({ key: key, version: 1, issuer: issuer, serialNumber: serialNumber, digestAlgorithm: digestAlgorithm, signatureAlgorithm: forge.pki.oids.rsaEncryption, signature: null, authenticatedAttributes: authenticatedAttributes, unauthenticatedAttributes: [] }); }, /** * Signs the content. * @param options Options to apply when signing: * [detached] boolean. If signing should be done in detached mode. Defaults to false. */ sign: function(options) { options = options || {}; // auto-generate content info if(typeof msg.content !== 'object' || msg.contentInfo === null) { // use Data ContentInfo msg.contentInfo = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // ContentType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(forge.pki.oids.data).getBytes()) ]); // add actual content, if present if('content' in msg) { var content; if(msg.content instanceof forge.util.ByteBuffer) { content = msg.content.bytes(); } else if(typeof msg.content === 'string') { content = forge.util.encodeUtf8(msg.content); } if (options.detached) { msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); } else { msg.contentInfo.value.push( // [0] EXPLICIT content asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content) ])); } } } // no signers, return early (degenerate case for certificate container) if(msg.signers.length === 0) { return; } // generate digest algorithm identifiers var mds = addDigestAlgorithmIds(); // generate signerInfos addSignerInfos(mds); }, verify: function() { throw new Error('PKCS#7 signature verification not yet implemented.'); }, /** * Add a certificate. * * @param cert the certificate to add. */ addCertificate: function(cert) { // convert from PEM if(typeof cert === 'string') { cert = forge.pki.certificateFromPem(cert); } msg.certificates.push(cert); }, /** * Add a certificate revokation list. * * @param crl the certificate revokation list to add. */ addCertificateRevokationList: function(crl) { throw new Error('PKCS#7 CRL support not yet implemented.'); } }; return msg; function addDigestAlgorithmIds() { var mds = {}; for(var i = 0; i < msg.signers.length; ++i) { var signer = msg.signers[i]; var oid = signer.digestAlgorithm; if(!(oid in mds)) { // content digest mds[oid] = forge.md[forge.pki.oids[oid]].create(); } if(signer.authenticatedAttributes.length === 0) { // no custom attributes to digest; use content message digest signer.md = mds[oid]; } else { // custom attributes to be digested; use own message digest // TODO: optimize to just copy message digest state if that // feature is ever supported with message digests signer.md = forge.md[forge.pki.oids[oid]].create(); } } // add unique digest algorithm identifiers msg.digestAlgorithmIdentifiers = []; for(var oid in mds) { msg.digestAlgorithmIdentifiers.push( // AlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oid).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ])); } return mds; } function addSignerInfos(mds) { var content; if (msg.detachedContent) { // Signature has been made in detached mode. content = msg.detachedContent; } else { // Note: ContentInfo is a SEQUENCE with 2 values, second value is // the content field and is optional for a ContentInfo but required here // since signers are present // get ContentInfo content content = msg.contentInfo.value[1]; // skip [0] EXPLICIT content wrapper content = content.value[0]; } if(!content) { throw new Error( 'Could not sign PKCS#7 message; there is no content to sign.'); } // get ContentInfo content type var contentType = asn1.derToOid(msg.contentInfo.value[0].value); // serialize content var bytes = asn1.toDer(content); // skip identifier and length per RFC 2315 9.3 // skip identifier (1 byte) bytes.getByte(); // read and discard length bytes asn1.getBerValueLength(bytes); bytes = bytes.getBytes(); // digest content DER value bytes for(var oid in mds) { mds[oid].start().update(bytes); } // sign content var signingTime = new Date(); for(var i = 0; i < msg.signers.length; ++i) { var signer = msg.signers[i]; if(signer.authenticatedAttributes.length === 0) { // if ContentInfo content type is not "Data", then // authenticatedAttributes must be present per RFC 2315 if(contentType !== forge.pki.oids.data) { throw new Error( 'Invalid signer; authenticatedAttributes must be present ' + 'when the ContentInfo content type is not PKCS#7 Data.'); } } else { // process authenticated attributes // [0] IMPLICIT signer.authenticatedAttributesAsn1 = asn1.create( asn1.Class.CONTEXT_SPECIFIC, 0, true, []); // per RFC 2315, attributes are to be digested using a SET container // not the above [0] IMPLICIT container var attrsAsn1 = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { var attr = signer.authenticatedAttributes[ai]; if(attr.type === forge.pki.oids.messageDigest) { // use content message digest as value attr.value = mds[signer.digestAlgorithm].digest(); } else if(attr.type === forge.pki.oids.signingTime) { // auto-populate signing time if not already set if(!attr.value) { attr.value = signingTime; } } // convert to ASN.1 and push onto Attributes SET (for signing) and // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 // TODO: optimize away duplication attrsAsn1.value.push(_attributeToAsn1(attr)); signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); } // DER-serialize and digest SET OF attributes only bytes = asn1.toDer(attrsAsn1).getBytes(); signer.md.start().update(bytes); } // sign digest signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); } // add signer info msg.signerInfos = _signersToAsn1(msg.signers); } }; /** * Creates an empty PKCS#7 message of type EncryptedData. * * @return the message. */ p7.createEncryptedData = function() { var msg = null; msg = { type: forge.pki.oids.encryptedData, version: 0, encryptedContent: { algorithm: forge.pki.oids['aes256-CBC'] }, /** * Reads an EncryptedData content block (in ASN.1 format) * * @param obj The ASN.1 representation of the EncryptedData content block */ fromAsn1: function(obj) { // Validate EncryptedData content block and capture data. _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); }, /** * Decrypt encrypted content * * @param key The (symmetric) key as a byte buffer */ decrypt: function(key) { if(key !== undefined) { msg.encryptedContent.key = key; } _decryptContent(msg); } }; return msg; }; /** * Creates an empty PKCS#7 message of type EnvelopedData. * * @return the message. */ p7.createEnvelopedData = function() { var msg = null; msg = { type: forge.pki.oids.envelopedData, version: 0, recipients: [], encryptedContent: { algorithm: forge.pki.oids['aes256-CBC'] }, /** * Reads an EnvelopedData content block (in ASN.1 format) * * @param obj the ASN.1 representation of the EnvelopedData content block. */ fromAsn1: function(obj) { // validate EnvelopedData content block and capture data var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); }, toAsn1: function() { // ContentInfo return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // ContentType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(msg.type).getBytes()), // [0] EnvelopedData asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Version asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(msg.version).getBytes()), // RecipientInfos asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, _recipientsToAsn1(msg.recipients)), // EncryptedContentInfo asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, _encryptedContentToAsn1(msg.encryptedContent)) ]) ]) ]); }, /** * Find recipient by X.509 certificate's issuer. * * @param cert the certificate with the issuer to look for. * * @return the recipient object. */ findRecipient: function(cert) { var sAttr = cert.issuer.attributes; for(var i = 0; i < msg.recipients.length; ++i) { var r = msg.recipients[i]; var rAttr = r.issuer; if(r.serialNumber !== cert.serialNumber) { continue; } if(rAttr.length !== sAttr.length) { continue; } var match = true; for(var j = 0; j < sAttr.length; ++j) { if(rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { match = false; break; } } if(match) { return r; } } return null; }, /** * Decrypt enveloped content * * @param recipient The recipient object related to the private key * @param privKey The (RSA) private key object */ decrypt: function(recipient, privKey) { if(msg.encryptedContent.key === undefined && recipient !== undefined && privKey !== undefined) { switch(recipient.encryptedContent.algorithm) { case forge.pki.oids.rsaEncryption: case forge.pki.oids.desCBC: var key = privKey.decrypt(recipient.encryptedContent.content); msg.encryptedContent.key = forge.util.createBuffer(key); break; default: throw new Error('Unsupported asymmetric cipher, ' + 'OID ' + recipient.encryptedContent.algorithm); } } _decryptContent(msg); }, /** * Add (another) entity to list of recipients. * * @param cert The certificate of the entity to add. */ addRecipient: function(cert) { msg.recipients.push({ version: 0, issuer: cert.issuer.attributes, serialNumber: cert.serialNumber, encryptedContent: { // We simply assume rsaEncryption here, since forge.pki only // supports RSA so far. If the PKI module supports other // ciphers one day, we need to modify this one as well. algorithm: forge.pki.oids.rsaEncryption, key: cert.publicKey } }); }, /** * Encrypt enveloped content. * * This function supports two optional arguments, cipher and key, which * can be used to influence symmetric encryption. Unless cipher is * provided, the cipher specified in encryptedContent.algorithm is used * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key * is (re-)used. If that one's not set, a random key will be generated * automatically. * * @param [key] The key to be used for symmetric encryption. * @param [cipher] The OID of the symmetric cipher to use. */ encrypt: function(key, cipher) { // Part 1: Symmetric encryption if(msg.encryptedContent.content === undefined) { cipher = cipher || msg.encryptedContent.algorithm; key = key || msg.encryptedContent.key; var keyLen, ivLen, ciphFn; switch(cipher) { case forge.pki.oids['aes128-CBC']: keyLen = 16; ivLen = 16; ciphFn = forge.aes.createEncryptionCipher; break; case forge.pki.oids['aes192-CBC']: keyLen = 24; ivLen = 16; ciphFn = forge.aes.createEncryptionCipher; break; case forge.pki.oids['aes256-CBC']: keyLen = 32; ivLen = 16; ciphFn = forge.aes.createEncryptionCipher; break; case forge.pki.oids['des-EDE3-CBC']: keyLen = 24; ivLen = 8; ciphFn = forge.des.createEncryptionCipher; break; default: throw new Error('Unsupported symmetric cipher, OID ' + cipher); } if(key === undefined) { key = forge.util.createBuffer(forge.random.getBytes(keyLen)); } else if(key.length() != keyLen) { throw new Error('Symmetric key has wrong length; ' + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); } // Keep a copy of the key & IV in the object, so the caller can // use it for whatever reason. msg.encryptedContent.algorithm = cipher; msg.encryptedContent.key = key; msg.encryptedContent.parameter = forge.util.createBuffer( forge.random.getBytes(ivLen)); var ciph = ciphFn(key); ciph.start(msg.encryptedContent.parameter.copy()); ciph.update(msg.content); // The finish function does PKCS#7 padding by default, therefore // no action required by us. if(!ciph.finish()) { throw new Error('Symmetric encryption failed.'); } msg.encryptedContent.content = ciph.output; } // Part 2: asymmetric encryption for each recipient for(var i = 0; i < msg.recipients.length; ++i) { var recipient = msg.recipients[i]; // Nothing to do, encryption already done. if(recipient.encryptedContent.content !== undefined) { continue; } switch(recipient.encryptedContent.algorithm) { case forge.pki.oids.rsaEncryption: recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( msg.encryptedContent.key.data); break; default: throw new Error('Unsupported asymmetric cipher, OID ' + recipient.encryptedContent.algorithm); } } } }; return msg; }; /** * Converts a single recipient from an ASN.1 object. * * @param obj the ASN.1 RecipientInfo. * * @return the recipient object. */ function _recipientFromAsn1(obj) { // validate EnvelopedData content block and capture data var capture = {}; var errors = []; if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); error.errors = errors; throw error; } return { version: capture.version.charCodeAt(0), issuer: forge.pki.RDNAttributesAsArray(capture.issuer), serialNumber: forge.util.createBuffer(capture.serial).toHex(), encryptedContent: { algorithm: asn1.derToOid(capture.encAlgorithm), parameter: capture.encParameter ? capture.encParameter.value : undefined, content: capture.encKey } }; } /** * Converts a single recipient object to an ASN.1 object. * * @param obj the recipient object. * * @return the ASN.1 RecipientInfo. */ function _recipientToAsn1(obj) { return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Version asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()), // IssuerAndSerialNumber asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Name forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), // Serial asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber)) ]), // KeyEncryptionAlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // Algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), // Parameter, force NULL, only RSA supported for now. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // EncryptedKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.encryptedContent.content) ]); } /** * Map a set of RecipientInfo ASN.1 objects to recipient objects. * * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). * * @return an array of recipient objects. */ function _recipientsFromAsn1(infos) { var ret = []; for(var i = 0; i < infos.length; ++i) { ret.push(_recipientFromAsn1(infos[i])); } return ret; } /** * Map an array of recipient objects to ASN.1 RecipientInfo objects. * * @param recipients an array of recipientInfo objects. * * @return an array of ASN.1 RecipientInfos. */ function _recipientsToAsn1(recipients) { var ret = []; for(var i = 0; i < recipients.length; ++i) { ret.push(_recipientToAsn1(recipients[i])); } return ret; } /** * Converts a single signer from an ASN.1 object. * * @param obj the ASN.1 representation of a SignerInfo. * * @return the signer object. */ function _signerFromAsn1(obj) { // validate EnvelopedData content block and capture data var capture = {}; var errors = []; if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) { var error = new Error('Cannot read PKCS#7 SignerInfo. ' + 'ASN.1 object is not an PKCS#7 SignerInfo.'); error.errors = errors; throw error; } var rval = { version: capture.version.charCodeAt(0), issuer: forge.pki.RDNAttributesAsArray(capture.issuer), serialNumber: forge.util.createBuffer(capture.serial).toHex(), digestAlgorithm: asn1.derToOid(capture.digestAlgorithm), signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm), signature: capture.signature, authenticatedAttributes: [], unauthenticatedAttributes: [] }; // TODO: convert attributes var authenticatedAttributes = capture.authenticatedAttributes || []; var unauthenticatedAttributes = capture.unauthenticatedAttributes || []; return rval; } /** * Converts a single signerInfo object to an ASN.1 object. * * @param obj the signerInfo object. * * @return the ASN.1 representation of a SignerInfo. */ function _signerToAsn1(obj) { // SignerInfo var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(obj.version).getBytes()), // issuerAndSerialNumber asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // name forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), // serial asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(obj.serialNumber)) ]), // digestAlgorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.digestAlgorithm).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]) ]); // authenticatedAttributes (OPTIONAL) if(obj.authenticatedAttributesAsn1) { // add ASN.1 previously generated during signing rval.value.push(obj.authenticatedAttributesAsn1); } // digestEncryptionAlgorithm rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(obj.signatureAlgorithm).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ])); // encryptedDigest rval.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); // unauthenticatedAttributes (OPTIONAL) if(obj.unauthenticatedAttributes.length > 0) { // [1] IMPLICIT var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { var attr = obj.unauthenticatedAttributes[i]; attrsAsn1.values.push(_attributeToAsn1(attr)); } rval.value.push(attrsAsn1); } return rval; } /** * Map a set of SignerInfo ASN.1 objects to an array of signer objects. * * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF). * * @return an array of signers objects. */ function _signersFromAsn1(signerInfoAsn1s) { var ret = []; for(var i = 0; i < signerInfoAsn1s.length; ++i) { ret.push(_signerFromAsn1(signerInfoAsn1s[i])); } return ret; } /** * Map an array of signer objects to ASN.1 objects. * * @param signers an array of signer objects. * * @return an array of ASN.1 SignerInfos. */ function _signersToAsn1(signers) { var ret = []; for(var i = 0; i < signers.length; ++i) { ret.push(_signerToAsn1(signers[i])); } return ret; } /** * Convert an attribute object to an ASN.1 Attribute. * * @param attr the attribute object. * * @return the ASN.1 Attribute. */ function _attributeToAsn1(attr) { var value; // TODO: generalize to support more attributes if(attr.type === forge.pki.oids.contentType) { value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
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/mgf1.js
aws/lti-middleware/node_modules/node-forge/lib/mgf1.js
/** * Javascript implementation of mask generation function MGF1. * * @author Stefan Siegl * @author Dave Longley * * Copyright (c) 2012 Stefan Siegl <[email protected]> * Copyright (c) 2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); forge.mgf = forge.mgf || {}; var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; /** * Creates a MGF1 mask generation function object. * * @param md the message digest API to use (eg: forge.md.sha1.create()). * * @return a mask generation function object. */ mgf1.create = function(md) { var mgf = { /** * Generate mask of specified length. * * @param {String} seed The seed for mask generation. * @param maskLen Number of bytes to generate. * @return {String} The generated mask. */ generate: function(seed, maskLen) { /* 2. Let T be the empty octet string. */ var t = new forge.util.ByteBuffer(); /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ var len = Math.ceil(maskLen / md.digestLength); for(var i = 0; i < len; i++) { /* a. Convert counter to an octet string C of length 4 octets */ var c = new forge.util.ByteBuffer(); c.putInt32(i); /* b. Concatenate the hash of the seed mgfSeed and C to the octet * string T: */ md.start(); md.update(seed + c.getBytes()); t.putBuffer(md.digest()); } /* Output the leading maskLen octets of T as the octet string mask. */ t.truncate(t.length() - maskLen); return t.getBytes(); } }; return mgf; };
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/mgf.js
aws/lti-middleware/node_modules/node-forge/lib/mgf.js
/** * Node.js module for Forge mask generation functions. * * @author Stefan Siegl * * Copyright 2012 Stefan Siegl <[email protected]> */ var forge = require('./forge'); require('./mgf1'); module.exports = forge.mgf = forge.mgf || {}; forge.mgf.mgf1 = forge.mgf1;
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/ed25519.js
aws/lti-middleware/node_modules/node-forge/lib/ed25519.js
/** * JavaScript implementation of Ed25519. * * Copyright (c) 2017-2019 Digital Bazaar, Inc. * * This implementation is based on the most excellent TweetNaCl which is * in the public domain. Many thanks to its contributors: * * https://github.com/dchest/tweetnacl-js */ var forge = require('./forge'); require('./jsbn'); require('./random'); require('./sha512'); require('./util'); var asn1Validator = require('./asn1-validator'); var publicKeyValidator = asn1Validator.publicKeyValidator; var privateKeyValidator = asn1Validator.privateKeyValidator; if(typeof BigInteger === 'undefined') { var BigInteger = forge.jsbn.BigInteger; } var ByteBuffer = forge.util.ByteBuffer; var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; /* * Ed25519 algorithms, see RFC 8032: * https://tools.ietf.org/html/rfc8032 */ forge.pki = forge.pki || {}; module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; var ed25519 = forge.ed25519; ed25519.constants = {}; ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; ed25519.constants.SEED_BYTE_LENGTH = 32; ed25519.constants.SIGN_BYTE_LENGTH = 64; ed25519.constants.HASH_BYTE_LENGTH = 64; ed25519.generateKeyPair = function(options) { options = options || {}; var seed = options.seed; if(seed === undefined) { // generate seed seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); } else if(typeof seed === 'string') { if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { throw new TypeError( '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + ' bytes in length.'); } } else if(!(seed instanceof Uint8Array)) { throw new TypeError( '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); } seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); for(var i = 0; i < 32; ++i) { sk[i] = seed[i]; } crypto_sign_keypair(pk, sk); return {publicKey: pk, privateKey: sk}; }; /** * Converts a private key from a RFC8410 ASN.1 encoding. * * @param obj - The asn1 representation of a private key. * * @returns {Object} keyInfo - The key information. * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. */ ed25519.privateKeyFromAsn1 = function(obj) { var capture = {}; var errors = []; var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); if(!valid) { var error = new Error('Invalid Key.'); error.errors = errors; throw error; } var oid = forge.asn1.derToOid(capture.privateKeyOid); var ed25519Oid = forge.oids.EdDSA25519; if(oid !== ed25519Oid) { throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); } var privateKey = capture.privateKey; // manually extract the private key bytes from nested octet string, see FIXME: // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 var privateKeyBytes = messageToNativeBuffer({ message: forge.asn1.fromDer(privateKey).value, encoding: 'binary' }); // TODO: RFC8410 specifies a format for encoding the public key bytes along // with the private key bytes. `publicKeyBytes` can be returned in the // future. https://tools.ietf.org/html/rfc8410#section-10.3 return {privateKeyBytes: privateKeyBytes}; }; /** * Converts a public key from a RFC8410 ASN.1 encoding. * * @param obj - The asn1 representation of a public key. * * @return {Buffer|Uint8Array} - 32 public key bytes. */ ed25519.publicKeyFromAsn1 = function(obj) { // get SubjectPublicKeyInfo var capture = {}; var errors = []; var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); if(!valid) { var error = new Error('Invalid Key.'); error.errors = errors; throw error; } var oid = forge.asn1.derToOid(capture.publicKeyOid); var ed25519Oid = forge.oids.EdDSA25519; if(oid !== ed25519Oid) { throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); } var publicKeyBytes = capture.ed25519PublicKey; if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { throw new Error('Key length is invalid.'); } return messageToNativeBuffer({ message: publicKeyBytes, encoding: 'binary' }); }; ed25519.publicKeyFromPrivateKey = function(options) { options = options || {}; var privateKey = messageToNativeBuffer({ message: options.privateKey, encoding: 'binary' }); if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { throw new TypeError( '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); } var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); for(var i = 0; i < pk.length; ++i) { pk[i] = privateKey[32 + i]; } return pk; }; ed25519.sign = function(options) { options = options || {}; var msg = messageToNativeBuffer(options); var privateKey = messageToNativeBuffer({ message: options.privateKey, encoding: 'binary' }); if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { var keyPair = ed25519.generateKeyPair({seed: privateKey}); privateKey = keyPair.privateKey; } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { throw new TypeError( '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + ' or ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); } var signedMsg = new NativeBuffer( ed25519.constants.SIGN_BYTE_LENGTH + msg.length); crypto_sign(signedMsg, msg, msg.length, privateKey); var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); for(var i = 0; i < sig.length; ++i) { sig[i] = signedMsg[i]; } return sig; }; ed25519.verify = function(options) { options = options || {}; var msg = messageToNativeBuffer(options); if(options.signature === undefined) { throw new TypeError( '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + 'ByteBuffer, or a binary string.'); } var sig = messageToNativeBuffer({ message: options.signature, encoding: 'binary' }); if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { throw new TypeError( '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH); } var publicKey = messageToNativeBuffer({ message: options.publicKey, encoding: 'binary' }); if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { throw new TypeError( '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); } var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); var i; for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { sm[i] = sig[i]; } for(i = 0; i < msg.length; ++i) { sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; } return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; function messageToNativeBuffer(options) { var message = options.message; if(message instanceof Uint8Array || message instanceof NativeBuffer) { return message; } var encoding = options.encoding; if(message === undefined) { if(options.md) { // TODO: more rigorous validation that `md` is a MessageDigest message = options.md.digest().getBytes(); encoding = 'binary'; } else { throw new TypeError('"options.message" or "options.md" not specified.'); } } if(typeof message === 'string' && !encoding) { throw new TypeError('"options.encoding" must be "binary" or "utf8".'); } if(typeof message === 'string') { if(typeof Buffer !== 'undefined') { return Buffer.from(message, encoding); } message = new ByteBuffer(message, encoding); } else if(!(message instanceof ByteBuffer)) { throw new TypeError( '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + 'ByteBuffer, or a string with "options.encoding" specifying its ' + 'encoding.'); } // convert to native buffer var buffer = new NativeBuffer(message.length()); for(var i = 0; i < buffer.length; ++i) { buffer[i] = message.at(i); } return buffer; } var gf0 = gf(); var gf1 = gf([1]); var D = gf([ 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); var D2 = gf([ 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); var X = gf([ 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); var Y = gf([ 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); var L = new Float64Array([ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); var I = gf([ 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); // TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, // whichever is available, to improve performance function sha512(msg, msgLen) { // Note: `out` and `msg` are NativeBuffer var md = forge.md.sha512.create(); var buffer = new ByteBuffer(msg); md.update(buffer.getBytes(msgLen), 'binary'); var hash = md.digest().getBytes(); if(typeof Buffer !== 'undefined') { return Buffer.from(hash, 'binary'); } var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); for(var i = 0; i < 64; ++i) { out[i] = hash.charCodeAt(i); } return out; } function crypto_sign_keypair(pk, sk) { var p = [gf(), gf(), gf(), gf()]; var i; var d = sha512(sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for(i = 0; i < 32; ++i) { sk[i + 32] = pk[i]; } return 0; } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; var d = sha512(sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for(i = 0; i < n; ++i) { sm[64 + i] = m[i]; } for(i = 0; i < 32; ++i) { sm[32 + i] = d[32 + i]; } var r = sha512(sm.subarray(32), n + 32); reduce(r); scalarbase(p, r); pack(sm, p); for(i = 32; i < 64; ++i) { sm[i] = sk[i]; } var h = sha512(sm, n + 64); reduce(h); for(i = 32; i < 64; ++i) { x[i] = 0; } for(i = 0; i < 32; ++i) { x[i] = r[i]; } for(i = 0; i < 32; ++i) { for(j = 0; j < 32; j++) { x[i + j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new NativeBuffer(32); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if(n < 64) { return -1; } if(unpackneg(q, pk)) { return -1; } for(i = 0; i < n; ++i) { m[i] = sm[i]; } for(i = 0; i < 32; ++i) { m[i + 32] = pk[i]; } var h = sha512(m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if(crypto_verify_32(sm, 0, t, 0)) { for(i = 0; i < n; ++i) { m[i] = 0; } return -1; } for(i = 0; i < n; ++i) { m[i] = sm[i + 64]; } mlen = n; return mlen; } function modL(r, x) { var carry, i, j, k; for(i = 63; i >= 32; --i) { carry = 0; for(j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for(j = 0; j < 32; ++j) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for(j = 0; j < 32; ++j) { x[j] -= carry * L[j]; } for(i = 0; i < 32; ++i) { x[i + 1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64); for(var i = 0; i < 64; ++i) { x[i] = r[i]; r[i] = 0; } modL(r, x); } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { for(var i = 0; i < 4; ++i) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for(i = 0; i < 16; ++i) { t[i] = n[i]; } car25519(t); car25519(t); car25519(t); for(j = 0; j < 2; ++j) { m[0] = t[0] - 0xffed; for(i = 1; i < 15; ++i) { m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); b = (m[15] >> 16) & 1; m[14] &= 0xffff; sel25519(t, m, 1 - b); } for (i = 0; i < 16; i++) { o[2 * i] = t[i] & 0xff; o[2 * i + 1] = t[i] >> 8; } } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if(neq25519(chk, num)) { M(r[0], r[0], I); } S(chk, r[0]); M(chk, chk, den); if(neq25519(chk, num)) { return -1; } if(par25519(r[0]) === (p[31] >> 7)) { Z(r[0], gf0, r[0]); } M(r[3], r[0], r[1]); return 0; } function unpack25519(o, n) { var i; for(i = 0; i < 16; ++i) { o[i] = n[2 * i] + (n[2 * i + 1] << 8); } o[15] &= 0x7fff; } function pow2523(o, i) { var c = gf(); var a; for(a = 0; a < 16; ++a) { c[a] = i[a]; } for(a = 250; a >= 0; --a) { S(c, c); if(a !== 1) { M(c, c, i); } } for(a = 0; a < 16; ++a) { o[a] = c[a]; } } function neq25519(a, b) { var c = new NativeBuffer(32); var d = new NativeBuffer(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function crypto_verify_32(x, xi, y, yi) { return vn(x, xi, y, yi, 32); } function vn(x, xi, y, yi, n) { var i, d = 0; for(i = 0; i < n; ++i) { d |= x[xi + i] ^ y[yi + i]; } return (1 & ((d - 1) >>> 8)) - 1; } function par25519(a) { var d = new NativeBuffer(32); pack25519(d, a); return d[0] & 1; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for(i = 255; i >= 0; --i) { b = (s[(i / 8)|0] >> (i & 7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function set25519(r, a) { var i; for(i = 0; i < 16; i++) { r[i] = a[i] | 0; } } function inv25519(o, i) { var c = gf(); var a; for(a = 0; a < 16; ++a) { c[a] = i[a]; } for(a = 253; a >= 0; --a) { S(c, c); if(a !== 2 && a !== 4) { M(c, c, i); } } for(a = 0; a < 16; ++a) { o[a] = c[a]; } } function car25519(o) { var i, v, c = 1; for(i = 0; i < 16; ++i) { v = o[i] + c + 65535; c = Math.floor(v / 65536); o[i] = v - c * 65536; } o[0] += c - 1 + 37 * (c - 1); } function sel25519(p, q, b) { var t, c = ~(b - 1); for(var i = 0; i < 16; ++i) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function gf(init) { var i, r = new Float64Array(16); if(init) { for(i = 0; i < init.length; ++i) { r[i] = init[i]; } } return r; } function A(o, a, b) { for(var i = 0; i < 16; ++i) { o[i] = a[i] + b[i]; } } function Z(o, a, b) { for(var i = 0; i < 16; ++i) { o[i] = a[i] - b[i]; } } function S(o, a) { M(o, a, a); } function M(o, a, b) { var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; v = a[0]; t0 += v * b0; t1 += v * b1; t2 += v * b2; t3 += v * b3; t4 += v * b4; t5 += v * b5; t6 += v * b6; t7 += v * b7; t8 += v * b8; t9 += v * b9; t10 += v * b10; t11 += v * b11; t12 += v * b12; t13 += v * b13; t14 += v * b14; t15 += v * b15; v = a[1]; t1 += v * b0; t2 += v * b1; t3 += v * b2; t4 += v * b3; t5 += v * b4; t6 += v * b5; t7 += v * b6; t8 += v * b7; t9 += v * b8; t10 += v * b9; t11 += v * b10; t12 += v * b11; t13 += v * b12; t14 += v * b13; t15 += v * b14; t16 += v * b15; v = a[2]; t2 += v * b0; t3 += v * b1; t4 += v * b2; t5 += v * b3; t6 += v * b4; t7 += v * b5; t8 += v * b6; t9 += v * b7; t10 += v * b8; t11 += v * b9; t12 += v * b10; t13 += v * b11; t14 += v * b12; t15 += v * b13; t16 += v * b14; t17 += v * b15; v = a[3]; t3 += v * b0; t4 += v * b1; t5 += v * b2; t6 += v * b3; t7 += v * b4; t8 += v * b5; t9 += v * b6; t10 += v * b7; t11 += v * b8; t12 += v * b9; t13 += v * b10; t14 += v * b11; t15 += v * b12; t16 += v * b13; t17 += v * b14; t18 += v * b15; v = a[4]; t4 += v * b0; t5 += v * b1; t6 += v * b2; t7 += v * b3; t8 += v * b4; t9 += v * b5; t10 += v * b6; t11 += v * b7; t12 += v * b8; t13 += v * b9; t14 += v * b10; t15 += v * b11; t16 += v * b12; t17 += v * b13; t18 += v * b14; t19 += v * b15; v = a[5]; t5 += v * b0; t6 += v * b1; t7 += v * b2; t8 += v * b3; t9 += v * b4; t10 += v * b5; t11 += v * b6; t12 += v * b7; t13 += v * b8; t14 += v * b9; t15 += v * b10; t16 += v * b11; t17 += v * b12; t18 += v * b13; t19 += v * b14; t20 += v * b15; v = a[6]; t6 += v * b0; t7 += v * b1; t8 += v * b2; t9 += v * b3; t10 += v * b4; t11 += v * b5; t12 += v * b6; t13 += v * b7; t14 += v * b8; t15 += v * b9; t16 += v * b10; t17 += v * b11; t18 += v * b12; t19 += v * b13; t20 += v * b14; t21 += v * b15; v = a[7]; t7 += v * b0; t8 += v * b1; t9 += v * b2; t10 += v * b3; t11 += v * b4; t12 += v * b5; t13 += v * b6; t14 += v * b7; t15 += v * b8; t16 += v * b9; t17 += v * b10; t18 += v * b11; t19 += v * b12; t20 += v * b13; t21 += v * b14; t22 += v * b15; v = a[8]; t8 += v * b0; t9 += v * b1; t10 += v * b2; t11 += v * b3; t12 += v * b4; t13 += v * b5; t14 += v * b6; t15 += v * b7; t16 += v * b8; t17 += v * b9; t18 += v * b10; t19 += v * b11; t20 += v * b12; t21 += v * b13; t22 += v * b14; t23 += v * b15; v = a[9]; t9 += v * b0; t10 += v * b1; t11 += v * b2; t12 += v * b3; t13 += v * b4; t14 += v * b5; t15 += v * b6; t16 += v * b7; t17 += v * b8; t18 += v * b9; t19 += v * b10; t20 += v * b11; t21 += v * b12; t22 += v * b13; t23 += v * b14; t24 += v * b15; v = a[10]; t10 += v * b0; t11 += v * b1; t12 += v * b2; t13 += v * b3; t14 += v * b4; t15 += v * b5; t16 += v * b6; t17 += v * b7; t18 += v * b8; t19 += v * b9; t20 += v * b10; t21 += v * b11; t22 += v * b12; t23 += v * b13; t24 += v * b14; t25 += v * b15; v = a[11]; t11 += v * b0; t12 += v * b1; t13 += v * b2; t14 += v * b3; t15 += v * b4; t16 += v * b5; t17 += v * b6; t18 += v * b7; t19 += v * b8; t20 += v * b9; t21 += v * b10; t22 += v * b11; t23 += v * b12; t24 += v * b13; t25 += v * b14; t26 += v * b15; v = a[12]; t12 += v * b0; t13 += v * b1; t14 += v * b2; t15 += v * b3; t16 += v * b4; t17 += v * b5; t18 += v * b6; t19 += v * b7; t20 += v * b8; t21 += v * b9; t22 += v * b10; t23 += v * b11; t24 += v * b12; t25 += v * b13; t26 += v * b14; t27 += v * b15; v = a[13]; t13 += v * b0; t14 += v * b1; t15 += v * b2; t16 += v * b3; t17 += v * b4; t18 += v * b5; t19 += v * b6; t20 += v * b7; t21 += v * b8; t22 += v * b9; t23 += v * b10; t24 += v * b11; t25 += v * b12; t26 += v * b13; t27 += v * b14; t28 += v * b15; v = a[14]; t14 += v * b0; t15 += v * b1; t16 += v * b2; t17 += v * b3; t18 += v * b4; t19 += v * b5; t20 += v * b6; t21 += v * b7; t22 += v * b8; t23 += v * b9; t24 += v * b10; t25 += v * b11; t26 += v * b12; t27 += v * b13; t28 += v * b14; t29 += v * b15; v = a[15]; t15 += v * b0; t16 += v * b1; t17 += v * b2; t18 += v * b3; t19 += v * b4; t20 += v * b5; t21 += v * b6; t22 += v * b7; t23 += v * b8; t24 += v * b9; t25 += v * b10; t26 += v * b11; t27 += v * b12; t28 += v * b13; t29 += v * b14; t30 += v * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; // t15 left as is // first car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); // second car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); o[ 0] = t0; o[ 1] = t1; o[ 2] = t2; o[ 3] = t3; o[ 4] = t4; o[ 5] = t5; o[ 6] = t6; o[ 7] = t7; o[ 8] = t8; o[ 9] = t9; o[10] = t10; o[11] = t11; o[12] = t12; o[13] = t13; o[14] = t14; o[15] = t15; }
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/sha1.js
aws/lti-middleware/node_modules/node-forge/lib/sha1.js
/** * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./md'); require('./util'); var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; forge.md.sha1 = forge.md.algorithms.sha1 = sha1; /** * Creates a SHA-1 message digest object. * * @return a message digest object. */ sha1.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // SHA-1 state contains five 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(80); // message digest object var md = { algorithm: 'sha1', blockLength: 64, digestLength: 20, // 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, h4: 0xC3D2E1F0 }; 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 SHA-1 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 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 s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3, h4: _state.h4 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); return rval; }; return md; }; // sha-1 padding bytes not initialized yet var _padding = null; var _initialized = false; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // now initialized _initialized = true; } /** * Updates a SHA-1 state with the given byte buffer. * * @param s the SHA-1 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, e, f, i; var len = bytes.length(); while(len >= 64) { // the w array will be populated with sixteen 32-bit big-endian words // and then extended into 80 32-bit words according to SHA-1 algorithm // and for 32-79 using Max Locktyukhin's optimization // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; e = s.h4; // round 1 for(i = 0; i < 16; ++i) { t = bytes.getInt32(); w[i] = t; f = d ^ (b & (c ^ d)); t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } for(; i < 20; ++i) { t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); t = (t << 1) | (t >>> 31); w[i] = t; f = d ^ (b & (c ^ d)); t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 2 for(; i < 32; ++i) { t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); t = (t << 1) | (t >>> 31); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } for(; i < 40; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 3 for(; i < 60; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = (b & c) | (d & (b ^ c)); t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 4 for(; i < 80; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // 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; s.h4 = (s.h4 + e) | 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/index.all.js
aws/lti-middleware/node_modules/node-forge/lib/index.all.js
/** * Node.js module for Forge with extra utils and networking. * * @author Dave Longley * * Copyright 2011-2016 Digital Bazaar, Inc. */ module.exports = require('./forge'); // require core forge require('./index'); // additional utils and networking support require('./form'); require('./socket'); require('./tlssocket'); require('./http'); require('./xhr');
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/log.js
aws/lti-middleware/node_modules/node-forge/lib/log.js
/** * Cross-browser support for logging in a web application. * * @author David I. Lehn <[email protected]> * * Copyright (c) 2008-2013 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); /* LOG API */ module.exports = forge.log = forge.log || {}; /** * Application logging system. * * Each logger level available as it's own function of the form: * forge.log.level(category, args...) * The category is an arbitrary string, and the args are the same as * Firebug's console.log API. By default the call will be output as: * 'LEVEL [category] <args[0]>, args[1], ...' * This enables proper % formatting via the first argument. * Each category is enabled by default but can be enabled or disabled with * the setCategoryEnabled() function. */ // list of known levels forge.log.levels = [ 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; // info on the levels indexed by name: // index: level index // name: uppercased display name var sLevelInfo = {}; // list of loggers var sLoggers = []; /** * Standard console logger. If no console support is enabled this will * remain null. Check before using. */ var sConsoleLogger = null; // logger flags /** * Lock the level at the current value. Used in cases where user config may * set the level such that only critical messages are seen but more verbose * messages are needed for debugging or other purposes. */ forge.log.LEVEL_LOCKED = (1 << 1); /** * Always call log function. By default, the logging system will check the * message level against logger.level before calling the log function. This * flag allows the function to do its own check. */ forge.log.NO_LEVEL_CHECK = (1 << 2); /** * Perform message interpolation with the passed arguments. "%" style * fields in log messages will be replaced by arguments as needed. Some * loggers, such as Firebug, may do this automatically. The original log * message will be available as 'message' and the interpolated version will * be available as 'fullMessage'. */ forge.log.INTERPOLATE = (1 << 3); // setup each log level for(var i = 0; i < forge.log.levels.length; ++i) { var level = forge.log.levels[i]; sLevelInfo[level] = { index: i, name: level.toUpperCase() }; } /** * Message logger. Will dispatch a message to registered loggers as needed. * * @param message message object */ forge.log.logMessage = function(message) { var messageLevelIndex = sLevelInfo[message.level].index; for(var i = 0; i < sLoggers.length; ++i) { var logger = sLoggers[i]; if(logger.flags & forge.log.NO_LEVEL_CHECK) { logger.f(message); } else { // get logger level var loggerLevelIndex = sLevelInfo[logger.level].index; // check level if(messageLevelIndex <= loggerLevelIndex) { // message critical enough, call logger logger.f(logger, message); } } } }; /** * Sets the 'standard' key on a message object to: * "LEVEL [category] " + message * * @param message a message log object */ forge.log.prepareStandard = function(message) { if(!('standard' in message)) { message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + ' [' + message.category + '] ' + message.message; } }; /** * Sets the 'full' key on a message object to the original message * interpolated via % formatting with the message arguments. * * @param message a message log object. */ forge.log.prepareFull = function(message) { if(!('full' in message)) { // copy args and insert message at the front var args = [message.message]; args = args.concat([] || message['arguments']); // format the message message.full = forge.util.format.apply(this, args); } }; /** * Applies both preparseStandard() and prepareFull() to a message object and * store result in 'standardFull'. * * @param message a message log object. */ forge.log.prepareStandardFull = function(message) { if(!('standardFull' in message)) { // FIXME implement 'standardFull' logging forge.log.prepareStandard(message); message.standardFull = message.standard; } }; // create log level functions if(true) { // levels for which we want functions var levels = ['error', 'warning', 'info', 'debug', 'verbose']; for(var i = 0; i < levels.length; ++i) { // wrap in a function to ensure proper level var is passed (function(level) { // create function for this level forge.log[level] = function(category, message/*, args...*/) { // convert arguments to real array, remove category and message var args = Array.prototype.slice.call(arguments).slice(2); // create message object // Note: interpolation and standard formatting is done lazily var msg = { timestamp: new Date(), level: level, category: category, message: message, 'arguments': args /*standard*/ /*full*/ /*fullMessage*/ }; // process this message forge.log.logMessage(msg); }; })(levels[i]); } } /** * Creates a new logger with specified custom logging function. * * The logging function has a signature of: * function(logger, message) * logger: current logger * message: object: * level: level id * category: category * message: string message * arguments: Array of extra arguments * fullMessage: interpolated message and arguments if INTERPOLATE flag set * * @param logFunction a logging function which takes a log message object * as a parameter. * * @return a logger object. */ forge.log.makeLogger = function(logFunction) { var logger = { flags: 0, f: logFunction }; forge.log.setLevel(logger, 'none'); return logger; }; /** * Sets the current log level on a logger. * * @param logger the target logger. * @param level the new maximum log level as a string. * * @return true if set, false if not. */ forge.log.setLevel = function(logger, level) { var rval = false; if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) { for(var i = 0; i < forge.log.levels.length; ++i) { var aValidLevel = forge.log.levels[i]; if(level == aValidLevel) { // set level logger.level = level; rval = true; break; } } } return rval; }; /** * Locks the log level at its current value. * * @param logger the target logger. * @param lock boolean lock value, default to true. */ forge.log.lock = function(logger, lock) { if(typeof lock === 'undefined' || lock) { logger.flags |= forge.log.LEVEL_LOCKED; } else { logger.flags &= ~forge.log.LEVEL_LOCKED; } }; /** * Adds a logger. * * @param logger the logger object. */ forge.log.addLogger = function(logger) { sLoggers.push(logger); }; // setup the console logger if possible, else create fake console.log if(typeof(console) !== 'undefined' && 'log' in console) { var logger; if(console.error && console.warn && console.info && console.debug) { // looks like Firebug-style logging is available // level handlers map var levelHandlers = { error: console.error, warning: console.warn, info: console.info, debug: console.debug, verbose: console.debug }; var f = function(logger, message) { forge.log.prepareStandard(message); var handler = levelHandlers[message.level]; // prepend standard message and concat args var args = [message.standard]; args = args.concat(message['arguments'].slice()); // apply to low-level console function handler.apply(console, args); }; logger = forge.log.makeLogger(f); } else { // only appear to have basic console.log var f = function(logger, message) { forge.log.prepareStandardFull(message); console.log(message.standardFull); }; logger = forge.log.makeLogger(f); } forge.log.setLevel(logger, 'debug'); forge.log.addLogger(logger); sConsoleLogger = logger; } else { // define fake console.log to avoid potential script errors on // browsers that do not have console logging console = { log: function() {} }; } /* * Check for logging control query vars in current URL. * * console.level=<level-name> * Set's the console log level by name. Useful to override defaults and * allow more verbose logging before a user config is loaded. * * console.lock=<true|false> * Lock the console log level at whatever level it is set at. This is run * after console.level is processed. Useful to force a level of verbosity * that could otherwise be limited by a user config. */ if(sConsoleLogger !== null && typeof window !== 'undefined' && window.location ) { var query = new URL(window.location.href).searchParams; if(query.has('console.level')) { // set with last value forge.log.setLevel( sConsoleLogger, query.get('console.level').slice(-1)[0]); } if(query.has('console.lock')) { // set with last value var lock = query.get('console.lock').slice(-1)[0]; if(lock == 'true') { forge.log.lock(sConsoleLogger); } } } // provide public access to console logger forge.log.consoleLogger = sConsoleLogger;
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/sha256.js
aws/lti-middleware/node_modules/node-forge/lib/sha256.js
/** * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. * * See FIPS 180-2 for details. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./md'); require('./util'); var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; forge.md.sha256 = forge.md.algorithms.sha256 = sha256; /** * Creates a SHA-256 message digest object. * * @return a message digest object. */ sha256.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // SHA-256 state contains eight 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(64); // message digest object var md = { algorithm: 'sha256', blockLength: 64, digestLength: 32, // 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: 0x6A09E667, h1: 0xBB67AE85, h2: 0x3C6EF372, h3: 0xA54FF53A, h4: 0x510E527F, h5: 0x9B05688C, h6: 0x1F83D9AB, h7: 0x5BE0CD19 }; 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 SHA-256 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 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 s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3, h4: _state.h4, h5: _state.h5, h6: _state.h6, h7: _state.h7 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); rval.putInt32(s2.h5); rval.putInt32(s2.h6); rval.putInt32(s2.h7); return rval; }; return md; }; // sha-256 padding bytes not initialized yet var _padding = null; var _initialized = false; // table of constants var _k = null; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // create K table for SHA-256 _k = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; // now initialized _initialized = true; } /** * Updates a SHA-256 state with the given byte buffer. * * @param s the SHA-256 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 t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; var len = bytes.length(); while(len >= 64) { // the w array will be populated with sixteen 32-bit big-endian words // and then extended into 64 32-bit words according to SHA-256 for(i = 0; i < 16; ++i) { w[i] = bytes.getInt32(); } for(; i < 64; ++i) { // XOR word 2 words ago rot right 17, rot right 19, shft right 10 t1 = w[i - 2]; t1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); // XOR word 15 words ago rot right 7, rot right 18, shft right 3 t2 = w[i - 15]; t2 = ((t2 >>> 7) | (t2 << 25)) ^ ((t2 >>> 18) | (t2 << 14)) ^ (t2 >>> 3); // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; } // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; e = s.h4; f = s.h5; g = s.h6; h = s.h7; // round function for(i = 0; i < 64; ++i) { // Sum1(e) s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); // Ch(e, f, g) (optimized the same way as SHA-1) ch = g ^ (e & (f ^ g)); // Sum0(a) s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); // Maj(a, b, c) (optimized the same way as SHA-1) maj = (a & b) | (c & (a ^ b)); // main algorithm t1 = h + s1 + ch + _k[i] + w[i]; t2 = s0 + maj; h = g; g = f; f = e; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug // can't truncate with `| 0` e = (d + t1) >>> 0; d = c; c = b; b = a; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug // can't truncate with `| 0` a = (t1 + t2) >>> 0; } // 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; s.h4 = (s.h4 + e) | 0; s.h5 = (s.h5 + f) | 0; s.h6 = (s.h6 + g) | 0; s.h7 = (s.h7 + h) | 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/prime.worker.js
aws/lti-middleware/node_modules/node-forge/lib/prime.worker.js
/** * RSA Key Generation Worker. * * @author Dave Longley * * Copyright (c) 2013 Digital Bazaar, Inc. */ // worker is built using CommonJS syntax to include all code in one worker file //importScripts('jsbn.js'); var forge = require('./forge'); require('./jsbn'); // prime constants var LOW_PRIMES = [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,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var LP_LIMIT = (1 << 26) / LOW_PRIMES[LOW_PRIMES.length - 1]; var BigInteger = forge.jsbn.BigInteger; var BIG_TWO = new BigInteger(null); BIG_TWO.fromInt(2); self.addEventListener('message', function(e) { var result = findPrime(e.data); self.postMessage(result); }); // start receiving ranges to check self.postMessage({found: false}); // 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]; function findPrime(data) { // TODO: abstract based on data.algorithm (PRIMEINC vs. others) // create BigInteger from given random bytes var num = new BigInteger(data.hex, 16); /* 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; // find nearest prime var workLoad = data.workLoad; for(var i = 0; i < workLoad; ++i) { // do primality test if(isProbablePrime(num)) { return {found: true, prime: num.toString(16)}; } // get next potential prime num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); } return {found: false}; } function isProbablePrime(n) { // divide by low primes, ignore even checks, etc (n alread aligned properly) var i = 1; while(i < LOW_PRIMES.length) { var m = LOW_PRIMES[i]; var j = i + 1; while(j < LOW_PRIMES.length && m < LP_LIMIT) { m *= LOW_PRIMES[j++]; } m = n.modInt(m); while(i < j) { if(m % LOW_PRIMES[i++] === 0) { return false; } } } return runMillerRabin(n); } // HAC 4.24, Miller-Rabin function runMillerRabin(n) { // n1 = n - 1 var n1 = n.subtract(BigInteger.ONE); // get s and d such that n1 = 2^s * d var s = n1.getLowestSetBit(); if(s <= 0) { return false; } var d = n1.shiftRight(s); var k = _getMillerRabinTests(n.bitLength()); var prng = getPrng(); var a; for(var i = 0; i < k; ++i) { // select witness 'a' at random from between 1 and n - 1 do { a = new BigInteger(n.bitLength(), prng); } while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); /* See if 'a' is a composite witness. */ // x = a^d mod n var x = a.modPow(d, n); // probably prime if(x.compareTo(BigInteger.ONE) === 0 || x.compareTo(n1) === 0) { continue; } var j = s; while(--j) { // x = x^2 mod a x = x.modPowInt(2, n); // 'n' is composite because no previous x == -1 mod n if(x.compareTo(BigInteger.ONE) === 0) { return false; } // x == -1 mod n, so probably prime if(x.compareTo(n1) === 0) { break; } } // 'x' is first_x^(n1/2) and is not +/- 1, so 'n' is not prime if(j === 0) { return false; } } return true; } // get pseudo random number generator function getPrng() { // create prng with api that matches BigInteger secure random return { // x is an array to fill with bytes nextBytes: function(x) { for(var i = 0; i < x.length; ++i) { x[i] = Math.floor(Math.random() * 0xFF); } } }; } /** * 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/aesCipherSuites.js
aws/lti-middleware/node_modules/node-forge/lib/aesCipherSuites.js
/** * A Javascript implementation of AES Cipher Suites for TLS. * * @author Dave Longley * * Copyright (c) 2009-2015 Digital Bazaar, Inc. * */ var forge = require('./forge'); require('./aes'); require('./tls'); var tls = module.exports = forge.tls; /** * Supported cipher suites. */ tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { id: [0x00, 0x2f], name: 'TLS_RSA_WITH_AES_128_CBC_SHA', initSecurityParameters: function(sp) { sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; sp.cipher_type = tls.CipherType.block; sp.enc_key_length = 16; sp.block_length = 16; sp.fixed_iv_length = 16; sp.record_iv_length = 16; sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; sp.mac_length = 20; sp.mac_key_length = 20; }, initConnectionState: initConnectionState }; tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { id: [0x00, 0x35], name: 'TLS_RSA_WITH_AES_256_CBC_SHA', initSecurityParameters: function(sp) { sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; sp.cipher_type = tls.CipherType.block; sp.enc_key_length = 32; sp.block_length = 16; sp.fixed_iv_length = 16; sp.record_iv_length = 16; sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; sp.mac_length = 20; sp.mac_key_length = 20; }, initConnectionState: initConnectionState }; function initConnectionState(state, c, sp) { var client = (c.entity === forge.tls.ConnectionEnd.client); // cipher setup state.read.cipherState = { init: false, cipher: forge.cipher.createDecipher('AES-CBC', client ? sp.keys.server_write_key : sp.keys.client_write_key), iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV }; state.write.cipherState = { init: false, cipher: forge.cipher.createCipher('AES-CBC', client ? sp.keys.client_write_key : sp.keys.server_write_key), iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV }; state.read.cipherFunction = decrypt_aes_cbc_sha1; state.write.cipherFunction = encrypt_aes_cbc_sha1; // MAC setup state.read.macLength = state.write.macLength = sp.mac_length; state.read.macFunction = state.write.macFunction = tls.hmac_sha1; } /** * Encrypts the TLSCompressed record into a TLSCipherText record using AES * in CBC mode. * * @param record the TLSCompressed record to encrypt. * @param s the ConnectionState to use. * * @return true on success, false on failure. */ function encrypt_aes_cbc_sha1(record, s) { var rval = false; // append MAC to fragment, update sequence number var mac = s.macFunction(s.macKey, s.sequenceNumber, record); record.fragment.putBytes(mac); s.updateSequenceNumber(); // TLS 1.1+ use an explicit IV every time to protect against CBC attacks var iv; if(record.version.minor === tls.Versions.TLS_1_0.minor) { // use the pre-generated IV when initializing for TLS 1.0, otherwise use // the residue from the previous encryption iv = s.cipherState.init ? null : s.cipherState.iv; } else { iv = forge.random.getBytesSync(16); } s.cipherState.init = true; // start cipher var cipher = s.cipherState.cipher; cipher.start({iv: iv}); // TLS 1.1+ write IV into output if(record.version.minor >= tls.Versions.TLS_1_1.minor) { cipher.output.putBytes(iv); } // do encryption (default padding is appropriate) cipher.update(record.fragment); if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { // set record fragment to encrypted output record.fragment = cipher.output; record.length = record.fragment.length(); rval = true; } return rval; } /** * Handles padding for aes_cbc_sha1 in encrypt mode. * * @param blockSize the block size. * @param input the input buffer. * @param decrypt true in decrypt mode, false in encrypt mode. * * @return true on success, false on failure. */ function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { /* The encrypted data length (TLSCiphertext.length) is one more than the sum of SecurityParameters.block_length, TLSCompressed.length, SecurityParameters.mac_length, and padding_length. The padding may be any length up to 255 bytes long, 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 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 padding length should 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. This is slightly different from PKCS#7 because the padding value is 1 less than the actual number of padding bytes if you include the padding_length uint8 itself as a padding byte. */ if(!decrypt) { // get the number of padding bytes required to reach the blockSize and // subtract 1 for the padding value (to make room for the padding_length // uint8) var padding = blockSize - (input.length() % blockSize); input.fillWithByte(padding - 1, padding); } return true; } /** * Handles padding for aes_cbc_sha1 in decrypt mode. * * @param blockSize the block size. * @param output the output buffer. * @param decrypt true in decrypt mode, false in encrypt mode. * * @return true on success, false on failure. */ function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { var rval = true; if(decrypt) { /* The last byte in the output specifies the number of padding bytes not including itself. Each of the padding bytes has the same value as that last byte (known as the padding_length). Here we check all padding bytes to ensure they have the value of padding_length even if one of them is bad in order to ward-off timing attacks. */ var len = output.length(); var paddingLength = output.last(); for(var i = len - 1 - paddingLength; i < len - 1; ++i) { rval = rval && (output.at(i) == paddingLength); } if(rval) { // trim off padding bytes and last padding length byte output.truncate(paddingLength + 1); } } return rval; } /** * Decrypts a TLSCipherText record into a TLSCompressed record using * AES in CBC mode. * * @param record the TLSCipherText record to decrypt. * @param s the ConnectionState to use. * * @return true on success, false on failure. */ function decrypt_aes_cbc_sha1(record, s) { var rval = false; var iv; if(record.version.minor === tls.Versions.TLS_1_0.minor) { // use pre-generated IV when initializing for TLS 1.0, otherwise use the // residue from the previous decryption iv = s.cipherState.init ? null : s.cipherState.iv; } else { // TLS 1.1+ use an explicit IV every time to protect against CBC attacks // that is appended to the record fragment iv = record.fragment.getBytes(16); } s.cipherState.init = true; // start cipher var cipher = s.cipherState.cipher; cipher.start({iv: iv}); // do decryption cipher.update(record.fragment); rval = cipher.finish(decrypt_aes_cbc_sha1_padding); // even if decryption fails, keep going to minimize timing attacks // decrypted data: // first (len - 20) bytes = application data // last 20 bytes = MAC var macLen = s.macLength; // create a random MAC to check against should the mac length check fail // Note: do this regardless of the failure to keep timing consistent var mac = forge.random.getBytesSync(macLen); // get fragment and mac var len = cipher.output.length(); if(len >= macLen) { record.fragment = cipher.output.getBytes(len - macLen); mac = cipher.output.getBytes(macLen); } else { // bad data, but get bytes anyway to try to keep timing consistent record.fragment = cipher.output.getBytes(); } record.fragment = forge.util.createBuffer(record.fragment); record.length = record.fragment.length(); // see if data integrity checks out, update sequence number var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); s.updateSequenceNumber(); rval = compareMacs(s.macKey, mac, mac2) && rval; return rval; } /** * Safely compare two MACs. This function will compare two MACs in a way * that protects against timing attacks. * * TODO: Expose elsewhere as a utility API. * * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ * * @param key the MAC key to use. * @param mac1 as a binary-encoded string of bytes. * @param mac2 as a binary-encoded string of bytes. * * @return true if the MACs are the same, false if not. */ function compareMacs(key, mac1, mac2) { var hmac = forge.hmac.create(); hmac.start('SHA1', key); hmac.update(mac1); mac1 = hmac.digest().getBytes(); hmac.start(null, null); hmac.update(mac2); mac2 = hmac.digest().getBytes(); return mac1 === mac2; }
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/pem.js
aws/lti-middleware/node_modules/node-forge/lib/pem.js
/** * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. * * See: RFC 1421. * * @author Dave Longley * * Copyright (c) 2013-2014 Digital Bazaar, Inc. * * A Forge PEM object has the following fields: * * type: identifies the type of message (eg: "RSA PRIVATE KEY"). * * procType: identifies the type of processing performed on the message, * it has two subfields: version and type, eg: 4,ENCRYPTED. * * contentDomain: identifies the type of content in the message, typically * only uses the value: "RFC822". * * dekInfo: identifies the message encryption algorithm and mode and includes * any parameters for the algorithm, it has two subfields: algorithm and * parameters, eg: DES-CBC,F8143EDE5960C597. * * headers: contains all other PEM encapsulated headers -- where order is * significant (for pairing data like recipient ID + key info). * * body: the binary-encoded body. */ var forge = require('./forge'); require('./util'); // shortcut for pem API var pem = module.exports = forge.pem = forge.pem || {}; /** * Encodes (serializes) the given PEM object. * * @param msg the PEM message object to encode. * @param options the options to use: * maxline the maximum characters per line for the body, (default: 64). * * @return the PEM-formatted string. */ pem.encode = function(msg, options) { options = options || {}; var rval = '-----BEGIN ' + msg.type + '-----\r\n'; // encode special headers var header; if(msg.procType) { header = { name: 'Proc-Type', values: [String(msg.procType.version), msg.procType.type] }; rval += foldHeader(header); } if(msg.contentDomain) { header = {name: 'Content-Domain', values: [msg.contentDomain]}; rval += foldHeader(header); } if(msg.dekInfo) { header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; if(msg.dekInfo.parameters) { header.values.push(msg.dekInfo.parameters); } rval += foldHeader(header); } if(msg.headers) { // encode all other headers for(var i = 0; i < msg.headers.length; ++i) { rval += foldHeader(msg.headers[i]); } } // terminate header if(msg.procType) { rval += '\r\n'; } // add body rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n'; rval += '-----END ' + msg.type + '-----\r\n'; return rval; }; /** * Decodes (deserializes) all PEM messages found in the given string. * * @param str the PEM-formatted string to decode. * * @return the PEM message objects in an array. */ pem.decode = function(str) { var rval = []; // split string into PEM messages (be lenient w/EOF on BEGIN line) var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; var rCRLF = /\r?\n/; var match; while(true) { match = rMessage.exec(str); if(!match) { break; } // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST" // https://datatracker.ietf.org/doc/html/rfc7468#section-7 var type = match[1]; if(type === 'NEW CERTIFICATE REQUEST') { type = 'CERTIFICATE REQUEST'; } var msg = { type: type, procType: null, contentDomain: null, dekInfo: null, headers: [], body: forge.util.decode64(match[3]) }; rval.push(msg); // no headers if(!match[2]) { continue; } // parse headers var lines = match[2].split(rCRLF); var li = 0; while(match && li < lines.length) { // get line, trim any rhs whitespace var line = lines[li].replace(/\s+$/, ''); // RFC2822 unfold any following folded lines for(var nl = li + 1; nl < lines.length; ++nl) { var next = lines[nl]; if(!/\s/.test(next[0])) { break; } line += next; li = nl; } // parse header match = line.match(rHeader); if(match) { var header = {name: match[1], values: []}; var values = match[2].split(','); for(var vi = 0; vi < values.length; ++vi) { header.values.push(ltrim(values[vi])); } // Proc-Type must be the first header if(!msg.procType) { if(header.name !== 'Proc-Type') { throw new Error('Invalid PEM formatted message. The first ' + 'encapsulated header must be "Proc-Type".'); } else if(header.values.length !== 2) { throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + 'header must have two subfields.'); } msg.procType = {version: values[0], type: values[1]}; } else if(!msg.contentDomain && header.name === 'Content-Domain') { // special-case Content-Domain msg.contentDomain = values[0] || ''; } else if(!msg.dekInfo && header.name === 'DEK-Info') { // special-case DEK-Info if(header.values.length === 0) { throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + 'header must have at least one subfield.'); } msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; } else { msg.headers.push(header); } } ++li; } if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + 'header must be present if "Proc-Type" is "ENCRYPTED".'); } } if(rval.length === 0) { throw new Error('Invalid PEM formatted message.'); } return rval; }; function foldHeader(header) { var rval = header.name + ': '; // ensure values with CRLF are folded var values = []; var insertSpace = function(match, $1) { return ' ' + $1; }; for(var i = 0; i < header.values.length; ++i) { values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); } rval += values.join(',') + '\r\n'; // do folding var length = 0; var candidate = -1; for(var i = 0; i < rval.length; ++i, ++length) { if(length > 65 && candidate !== -1) { var insert = rval[candidate]; if(insert === ',') { ++candidate; rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); } else { rval = rval.substr(0, candidate) + '\r\n' + insert + rval.substr(candidate + 1); } length = (i - candidate - 1); candidate = -1; ++i; } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { candidate = i; } } return rval; } function ltrim(str) { return str.replace(/^\s+/, ''); }
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/socket.js
aws/lti-middleware/node_modules/node-forge/lib/socket.js
/** * Socket implementation that uses flash SocketPool class as a backend. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); // define net namespace var net = module.exports = forge.net = forge.net || {}; // map of flash ID to socket pool net.socketPools = {}; /** * Creates a flash socket pool. * * @param options: * flashId: the dom ID for the flash object element. * policyPort: the default policy port for sockets, 0 to use the * flash default. * policyUrl: the default policy file URL for sockets (if provided * used instead of a policy port). * msie: true if the browser is msie, false if not. * * @return the created socket pool. */ net.createSocketPool = function(options) { // set default options.msie = options.msie || false; // initialize the flash interface var spId = options.flashId; var api = document.getElementById(spId); api.init({marshallExceptions: !options.msie}); // create socket pool entry var sp = { // ID of the socket pool id: spId, // flash interface flashApi: api, // map of socket ID to sockets sockets: {}, // default policy port policyPort: options.policyPort || 0, // default policy URL policyUrl: options.policyUrl || null }; net.socketPools[spId] = sp; // create event handler, subscribe to flash events if(options.msie === true) { sp.handler = function(e) { if(e.id in sp.sockets) { // get handler function var f; switch(e.type) { case 'connect': f = 'connected'; break; case 'close': f = 'closed'; break; case 'socketData': f = 'data'; break; default: f = 'error'; break; } /* IE calls javascript on the thread of the external object that triggered the event (in this case flash) ... which will either run concurrently with other javascript or pre-empt any running javascript in the middle of its execution (BAD!) ... calling setTimeout() will schedule the javascript to run on the javascript thread and solve this EVIL problem. */ setTimeout(function() {sp.sockets[e.id][f](e);}, 0); } }; } else { sp.handler = function(e) { if(e.id in sp.sockets) { // get handler function var f; switch(e.type) { case 'connect': f = 'connected'; break; case 'close': f = 'closed'; break; case 'socketData': f = 'data'; break; default: f = 'error'; break; } sp.sockets[e.id][f](e); } }; } var handler = 'forge.net.socketPools[\'' + spId + '\'].handler'; api.subscribe('connect', handler); api.subscribe('close', handler); api.subscribe('socketData', handler); api.subscribe('ioError', handler); api.subscribe('securityError', handler); /** * Destroys a socket pool. The socket pool still needs to be cleaned * up via net.cleanup(). */ sp.destroy = function() { delete net.socketPools[options.flashId]; for(var id in sp.sockets) { sp.sockets[id].destroy(); } sp.sockets = {}; api.cleanup(); }; /** * Creates a new socket. * * @param options: * connected: function(event) called when the socket connects. * closed: function(event) called when the socket closes. * data: function(event) called when socket data has arrived, * it can be read from the socket using receive(). * error: function(event) called when a socket error occurs. */ sp.createSocket = function(options) { // default to empty options options = options || {}; // create flash socket var id = api.create(); // create javascript socket wrapper var socket = { id: id, // set handlers connected: options.connected || function(e) {}, closed: options.closed || function(e) {}, data: options.data || function(e) {}, error: options.error || function(e) {} }; /** * Destroys this socket. */ socket.destroy = function() { api.destroy(id); delete sp.sockets[id]; }; /** * Connects this socket. * * @param options: * host: the host to connect to. * port: the port to connect to. * policyPort: the policy port to use (if non-default), 0 to * use the flash default. * policyUrl: the policy file URL to use (instead of port). */ socket.connect = function(options) { // give precedence to policy URL over policy port // if no policy URL and passed port isn't 0, use default port, // otherwise use 0 for the port var policyUrl = options.policyUrl || null; var policyPort = 0; if(policyUrl === null && options.policyPort !== 0) { policyPort = options.policyPort || sp.policyPort; } api.connect(id, options.host, options.port, policyPort, policyUrl); }; /** * Closes this socket. */ socket.close = function() { api.close(id); socket.closed({ id: socket.id, type: 'close', bytesAvailable: 0 }); }; /** * Determines if the socket is connected or not. * * @return true if connected, false if not. */ socket.isConnected = function() { return api.isConnected(id); }; /** * Writes bytes to this socket. * * @param bytes the bytes (as a string) to write. * * @return true on success, false on failure. */ socket.send = function(bytes) { return api.send(id, forge.util.encode64(bytes)); }; /** * Reads bytes from this socket (non-blocking). Fewer than the number * of bytes requested may be read if enough bytes are not available. * * This method should be called from the data handler if there are * enough bytes available. To see how many bytes are available, check * the 'bytesAvailable' property on the event in the data handler or * call the bytesAvailable() function on the socket. If the browser is * msie, then the bytesAvailable() function should be used to avoid * race conditions. Otherwise, using the property on the data handler's * event may be quicker. * * @param count the maximum number of bytes to read. * * @return the bytes read (as a string) or null on error. */ socket.receive = function(count) { var rval = api.receive(id, count).rval; return (rval === null) ? null : forge.util.decode64(rval); }; /** * Gets the number of bytes available for receiving on the socket. * * @return the number of bytes available for receiving. */ socket.bytesAvailable = function() { return api.getBytesAvailable(id); }; // store and return socket sp.sockets[id] = socket; return socket; }; return sp; }; /** * Destroys a flash socket pool. * * @param options: * flashId: the dom ID for the flash object element. */ net.destroySocketPool = function(options) { if(options.flashId in net.socketPools) { var sp = net.socketPools[options.flashId]; sp.destroy(); } }; /** * Creates a new socket. * * @param options: * flashId: the dom ID for the flash object element. * connected: function(event) called when the socket connects. * closed: function(event) called when the socket closes. * data: function(event) called when socket data has arrived, it * can be read from the socket using receive(). * error: function(event) called when a socket error occurs. * * @return the created socket. */ net.createSocket = function(options) { var socket = null; if(options.flashId in net.socketPools) { // get related socket pool var sp = net.socketPools[options.flashId]; socket = sp.createSocket(options); } return socket; };
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/hmac.js
aws/lti-middleware/node_modules/node-forge/lib/hmac.js
/** * Hash-based Message Authentication Code implementation. Requires a message * digest object that can be obtained, for example, from forge.md.sha1 or * forge.md.md5. * * @author Dave Longley * * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. */ var forge = require('./forge'); require('./md'); require('./util'); /* HMAC API */ var hmac = module.exports = forge.hmac = forge.hmac || {}; /** * Creates an HMAC object that uses the given message digest object. * * @return an HMAC object. */ hmac.create = function() { // the hmac key to use var _key = null; // the message digest to use var _md = null; // the inner padding var _ipadding = null; // the outer padding var _opadding = null; // hmac context var ctx = {}; /** * Starts or restarts the HMAC with the given key and message digest. * * @param md the message digest to use, null to reuse the previous one, * a string to use builtin 'sha1', 'md5', 'sha256'. * @param key the key to use as a string, array of bytes, byte buffer, * or null to reuse the previous key. */ ctx.start = function(md, key) { if(md !== null) { if(typeof md === 'string') { // create builtin message digest md = md.toLowerCase(); if(md in forge.md.algorithms) { _md = forge.md.algorithms[md].create(); } else { throw new Error('Unknown hash algorithm "' + md + '"'); } } else { // store message digest _md = md; } } if(key === null) { // reuse previous key key = _key; } else { if(typeof key === 'string') { // convert string into byte buffer key = forge.util.createBuffer(key); } else if(forge.util.isArray(key)) { // convert byte array into byte buffer var tmp = key; key = forge.util.createBuffer(); for(var i = 0; i < tmp.length; ++i) { key.putByte(tmp[i]); } } // if key is longer than blocksize, hash it var keylen = key.length(); if(keylen > _md.blockLength) { _md.start(); _md.update(key.bytes()); key = _md.digest(); } // mix key into inner and outer padding // ipadding = [0x36 * blocksize] ^ key // opadding = [0x5C * blocksize] ^ key _ipadding = forge.util.createBuffer(); _opadding = forge.util.createBuffer(); keylen = key.length(); for(var i = 0; i < keylen; ++i) { var tmp = key.at(i); _ipadding.putByte(0x36 ^ tmp); _opadding.putByte(0x5C ^ tmp); } // if key is shorter than blocksize, add additional padding if(keylen < _md.blockLength) { var tmp = _md.blockLength - keylen; for(var i = 0; i < tmp; ++i) { _ipadding.putByte(0x36); _opadding.putByte(0x5C); } } _key = key; _ipadding = _ipadding.bytes(); _opadding = _opadding.bytes(); } // digest is done like so: hash(opadding | hash(ipadding | message)) // prepare to do inner hash // hash(ipadding | message) _md.start(); _md.update(_ipadding); }; /** * Updates the HMAC with the given message bytes. * * @param bytes the bytes to update with. */ ctx.update = function(bytes) { _md.update(bytes); }; /** * Produces the Message Authentication Code (MAC). * * @return a byte buffer containing the digest value. */ ctx.getMac = function() { // digest is done like so: hash(opadding | hash(ipadding | message)) // here we do the outer hashing var inner = _md.digest().bytes(); _md.start(); _md.update(_opadding); _md.update(inner); return _md.digest(); }; // alias for getMac ctx.digest = ctx.getMac; return ctx; };
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/kem.js
aws/lti-middleware/node_modules/node-forge/lib/kem.js
/** * Javascript implementation of RSA-KEM. * * @author Lautaro Cozzani Rodriguez * @author Dave Longley * * Copyright (c) 2014 Lautaro Cozzani <[email protected]> * Copyright (c) 2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); require('./random'); require('./jsbn'); module.exports = forge.kem = forge.kem || {}; var BigInteger = forge.jsbn.BigInteger; /** * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. */ forge.kem.rsa = {}; /** * Creates an RSA KEM API object for generating a secret asymmetric key. * * The symmetric key may be generated via a call to 'encrypt', which will * produce a ciphertext to be transmitted to the recipient and a key to be * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which * will produce the same secret key for the recipient to use to decrypt a * message that was encrypted with the secret key. * * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). * @param options the options to use. * [prng] a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". */ forge.kem.rsa.create = function(kdf, options) { options = options || {}; var prng = options.prng || forge.random; var kem = {}; /** * Generates a secret key and its encapsulation. * * @param publicKey the RSA public key to encrypt with. * @param keyLength the length, in bytes, of the secret key to generate. * * @return an object with: * encapsulation: the ciphertext for generating the secret key, as a * binary-encoded string of bytes. * key: the secret key to use for encrypting a message. */ kem.encrypt = function(publicKey, keyLength) { // generate a random r where 1 < r < n var byteLength = Math.ceil(publicKey.n.bitLength() / 8); var r; do { r = new BigInteger( forge.util.bytesToHex(prng.getBytesSync(byteLength)), 16).mod(publicKey.n); } while(r.compareTo(BigInteger.ONE) <= 0); // prepend r with zeros r = forge.util.hexToBytes(r.toString(16)); var zeros = byteLength - r.length; if(zeros > 0) { r = forge.util.fillString(String.fromCharCode(0), zeros) + r; } // encrypt the random var encapsulation = publicKey.encrypt(r, 'NONE'); // generate the secret key var key = kdf.generate(r, keyLength); return {encapsulation: encapsulation, key: key}; }; /** * Decrypts an encapsulated secret key. * * @param privateKey the RSA private key to decrypt with. * @param encapsulation the ciphertext for generating the secret key, as * a binary-encoded string of bytes. * @param keyLength the length, in bytes, of the secret key to generate. * * @return the secret key as a binary-encoded string of bytes. */ kem.decrypt = function(privateKey, encapsulation, keyLength) { // decrypt the encapsulation and generate the secret key var r = privateKey.decrypt(encapsulation, 'NONE'); return kdf.generate(r, keyLength); }; return kem; }; // TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? /** * Creates a key derivation API object that implements KDF1 per ISO 18033-2. * * @param md the hash API to use. * @param [digestLength] an optional digest length that must be positive and * less than or equal to md.digestLength. * * @return a KDF1 API object. */ forge.kem.kdf1 = function(md, digestLength) { _createKDF(this, md, 0, digestLength || md.digestLength); }; /** * Creates a key derivation API object that implements KDF2 per ISO 18033-2. * * @param md the hash API to use. * @param [digestLength] an optional digest length that must be positive and * less than or equal to md.digestLength. * * @return a KDF2 API object. */ forge.kem.kdf2 = function(md, digestLength) { _createKDF(this, md, 1, digestLength || md.digestLength); }; /** * Creates a KDF1 or KDF2 API object. * * @param md the hash API to use. * @param counterStart the starting index for the counter. * @param digestLength the digest length to use. * * @return the KDF API object. */ function _createKDF(kdf, md, counterStart, digestLength) { /** * Generate a key of the specified length. * * @param x the binary-encoded byte string to generate a key from. * @param length the number of bytes to generate (the size of the key). * * @return the key as a binary-encoded string. */ kdf.generate = function(x, length) { var key = new forge.util.ByteBuffer(); // run counter from counterStart to ceil(length / Hash.len) var k = Math.ceil(length / digestLength) + counterStart; var c = new forge.util.ByteBuffer(); for(var i = counterStart; i < k; ++i) { // I2OSP(i, 4): convert counter to an octet string of 4 octets c.putInt32(i); // digest 'x' and the counter and add the result to the key md.start(); md.update(x + c.getBytes()); var hash = md.digest(); key.putBytes(hash.getBytes(digestLength)); } // truncate to the correct key length key.truncate(key.length() - length); return key.getBytes(); }; }
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/util.js
aws/lti-middleware/node_modules/node-forge/lib/util.js
/** * Utility functions for web applications. * * @author Dave Longley * * Copyright (c) 2010-2018 Digital Bazaar, Inc. */ var forge = require('./forge'); var baseN = require('./baseN'); /* Utilities API */ var util = module.exports = forge.util = forge.util || {}; // define setImmediate and nextTick (function() { // use native nextTick (unless we're in webpack) // webpack (or better node-libs-browser polyfill) sets process.browser. // this way we can detect webpack properly if(typeof process !== 'undefined' && process.nextTick && !process.browser) { util.nextTick = process.nextTick; if(typeof setImmediate === 'function') { util.setImmediate = setImmediate; } else { // polyfill setImmediate with nextTick, older versions of node // (those w/o setImmediate) won't totally starve IO util.setImmediate = util.nextTick; } return; } // polyfill nextTick with native setImmediate if(typeof setImmediate === 'function') { util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; util.nextTick = function(callback) { return setImmediate(callback); }; return; } /* Note: A polyfill upgrade pattern is used here to allow combining polyfills. For example, MutationObserver is fast, but blocks UI updates, so it needs to allow UI updates periodically, so it falls back on postMessage or setTimeout. */ // polyfill with setTimeout util.setImmediate = function(callback) { setTimeout(callback, 0); }; // upgrade polyfill to use postMessage if(typeof window !== 'undefined' && typeof window.postMessage === 'function') { var msg = 'forge.setImmediate'; var callbacks = []; util.setImmediate = function(callback) { callbacks.push(callback); // only send message when one hasn't been sent in // the current turn of the event loop if(callbacks.length === 1) { window.postMessage(msg, '*'); } }; function handler(event) { if(event.source === window && event.data === msg) { event.stopPropagation(); var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); } } window.addEventListener('message', handler, true); } // upgrade polyfill to use MutationObserver if(typeof MutationObserver !== 'undefined') { // polyfill with MutationObserver var now = Date.now(); var attr = true; var div = document.createElement('div'); var callbacks = []; new MutationObserver(function() { var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); }).observe(div, {attributes: true}); var oldSetImmediate = util.setImmediate; util.setImmediate = function(callback) { if(Date.now() - now > 15) { now = Date.now(); oldSetImmediate(callback); } else { callbacks.push(callback); // only trigger observer when it hasn't been triggered in // the current turn of the event loop if(callbacks.length === 1) { div.setAttribute('a', attr = !attr); } } }; } util.nextTick = util.setImmediate; })(); // check if running under Node.js util.isNodejs = typeof process !== 'undefined' && process.versions && process.versions.node; // 'self' will also work in Web Workers (instance of WorkerGlobalScope) while // it will point to `window` in the main thread. // To remain compatible with older browsers, we fall back to 'window' if 'self' // is not available. util.globalScope = (function() { if(util.isNodejs) { return global; } return typeof self === 'undefined' ? window : self; })(); // define isArray util.isArray = Array.isArray || function(x) { return Object.prototype.toString.call(x) === '[object Array]'; }; // define isArrayBuffer util.isArrayBuffer = function(x) { return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; }; // define isArrayBufferView util.isArrayBufferView = function(x) { return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; }; /** * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for * algorithms where bit manipulation, JavaScript limitations, and/or algorithm * design only allow for byte operations of a limited size. * * @param n number of bits. * * Throw Error if n invalid. */ function _checkBitsParam(n) { if(!(n === 8 || n === 16 || n === 24 || n === 32)) { throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); } } // TODO: set ByteBuffer to best available backing util.ByteBuffer = ByteStringBuffer; /** Buffer w/BinaryString backing */ /** * Constructor for a binary string backed byte buffer. * * @param [b] the bytes to wrap (either encoded as string, one byte per * character, or as an ArrayBuffer or Typed Array). */ function ByteStringBuffer(b) { // TODO: update to match DataBuffer API // the data in this buffer this.data = ''; // the pointer for reading from this buffer this.read = 0; if(typeof b === 'string') { this.data = b; } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { if(typeof Buffer !== 'undefined' && b instanceof Buffer) { this.data = b.toString('binary'); } else { // convert native buffer to forge buffer // FIXME: support native buffers internally instead var arr = new Uint8Array(b); try { this.data = String.fromCharCode.apply(null, arr); } catch(e) { for(var i = 0; i < arr.length; ++i) { this.putByte(arr[i]); } } } } else if(b instanceof ByteStringBuffer || (typeof b === 'object' && typeof b.data === 'string' && typeof b.read === 'number')) { // copy existing buffer this.data = b.data; this.read = b.read; } // used for v8 optimization this._constructedStringLength = 0; } util.ByteStringBuffer = ByteStringBuffer; /* Note: This is an optimization for V8-based browsers. When V8 concatenates a string, the strings are only joined logically using a "cons string" or "constructed/concatenated string". These containers keep references to one another and can result in very large memory usage. For example, if a 2MB string is constructed by concatenating 4 bytes together at a time, the memory usage will be ~44MB; so ~22x increase. The strings are only joined together when an operation requiring their joining takes place, such as substr(). This function is called when adding data to this buffer to ensure these types of strings are periodically joined to reduce the memory footprint. */ var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { this._constructedStringLength += x; if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { // this substr() should cause the constructed string to join this.data.substr(0, 1); this._constructedStringLength = 0; } }; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.ByteStringBuffer.prototype.length = function() { return this.data.length - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.ByteStringBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putByte = function(b) { return this.putBytes(String.fromCharCode(b)); }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { b = String.fromCharCode(b); var d = this.data; while(n > 0) { if(n & 1) { d += b; } n >>>= 1; if(n > 0) { b += b; } } this.data = d; this._optimizeConstructedString(n); return this; }; /** * Puts bytes in this buffer. * * @param bytes the bytes (as a binary encoded string) to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBytes = function(bytes) { this.data += bytes; this._optimizeConstructedString(bytes.length); return this; }; /** * Puts a UTF-16 encoded string into this buffer. * * @param str the string to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putString = function(str) { return this.putBytes(util.encodeUtf8(str)); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16 = function(i) { return this.putBytes( String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24 = function(i) { return this.putBytes( String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32 = function(i) { return this.putBytes( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 24 & 0xFF)); }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); var bytes = ''; do { n -= 8; bytes += String.fromCharCode((i >> n) & 0xFF); } while(n > 0); return this.putBytes(bytes); }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { // putInt checks n if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBuffer = function(buffer) { return this.putBytes(buffer.getBytes()); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.ByteStringBuffer.prototype.getByte = function() { return this.data.charCodeAt(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16 = function() { var rval = ( this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1)); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24 = function() { var rval = ( this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32 = function() { var rval = ( this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3)); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by ceil(n/8). * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.charCodeAt(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out as a binary encoded string and clears them from the * buffer. Note that the resulting string is binary encoded (in node.js this * encoding is referred to as `binary`, it is *not* `utf8`). * * @param count the number of bytes to read, undefined or null for all. * * @return a binary encoded string of bytes. */ util.ByteStringBuffer.prototype.getBytes = function(count) { var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a binary encoded string of the bytes from this buffer without * modifying the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of binary encoded characters. */ util.ByteStringBuffer.prototype.bytes = function(count) { return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.ByteStringBuffer.prototype.at = function(i) { return this.data.charCodeAt(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.setAt = function(i, b) { this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.ByteStringBuffer.prototype.last = function() { return this.data.charCodeAt(this.data.length - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.ByteStringBuffer.prototype.copy = function() { var c = util.createBuffer(this.data); c.read = this.read; return c; }; /** * Compacts this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.compact = function() { if(this.read > 0) { this.data = this.data.slice(this.read); this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.clear = function() { this.data = ''; this.read = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.ByteStringBuffer.prototype.truncate = function(count) { var len = Math.max(0, this.length() - count); this.data = this.data.substr(this.read, len); this.read = 0; return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.ByteStringBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.length; ++i) { var b = this.data.charCodeAt(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a UTF-16 string (standard JavaScript string). * * @return a UTF-16 string. */ util.ByteStringBuffer.prototype.toString = function() { return util.decodeUtf8(this.bytes()); }; /** End Buffer w/BinaryString backing */ /** Buffer w/UInt8Array backing */ /** * FIXME: Experimental. Do not use yet. * * Constructor for an ArrayBuffer-backed byte buffer. * * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a * TypedArray. * * If a string is given, its encoding should be provided as an option, * otherwise it will default to 'binary'. A 'binary' string is encoded such * that each character is one byte in length and size. * * If an ArrayBuffer, DataView, or TypedArray is given, it will be used * *directly* without any copying. Note that, if a write to the buffer requires * more space, the buffer will allocate a new backing ArrayBuffer to * accommodate. The starting read and write offsets for the buffer may be * given as options. * * @param [b] the initial bytes for this buffer. * @param options the options to use: * [readOffset] the starting read offset to use (default: 0). * [writeOffset] the starting write offset to use (default: the * length of the first parameter). * [growSize] the minimum amount, in bytes, to grow the buffer by to * accommodate writes (default: 1024). * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the * first parameter, if it is a string (default: 'binary'). */ function DataBuffer(b, options) { // default options options = options || {}; // pointers for read from/write to buffer this.read = options.readOffset || 0; this.growSize = options.growSize || 1024; var isArrayBuffer = util.isArrayBuffer(b); var isArrayBufferView = util.isArrayBufferView(b); if(isArrayBuffer || isArrayBufferView) { // use ArrayBuffer directly if(isArrayBuffer) { this.data = new DataView(b); } else { // TODO: adjust read/write offset based on the type of view // or specify that this must be done in the options ... that the // offsets are byte-based this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); } this.write = ('writeOffset' in options ? options.writeOffset : this.data.byteLength); return; } // initialize to empty array buffer and add any given bytes using putBytes this.data = new DataView(new ArrayBuffer(0)); this.write = 0; if(b !== null && b !== undefined) { this.putBytes(b); } if('writeOffset' in options) { this.write = options.writeOffset; } } util.DataBuffer = DataBuffer; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.DataBuffer.prototype.length = function() { return this.write - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.DataBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Ensures this buffer has enough empty space to accommodate the given number * of bytes. An optional parameter may be given that indicates a minimum * amount to grow the buffer if necessary. If the parameter is not given, * the buffer will be grown by some previously-specified default amount * or heuristic. * * @param amount the number of bytes to accommodate. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if * necessary. */ util.DataBuffer.prototype.accommodate = function(amount, growSize) { if(this.length() >= amount) { return this; } growSize = Math.max(growSize || this.growSize, amount); // grow buffer var src = new Uint8Array( this.data.buffer, this.data.byteOffset, this.data.byteLength); var dst = new Uint8Array(this.length() + growSize); dst.set(src); this.data = new DataView(dst.buffer); return this; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.putByte = function(b) { this.accommodate(1); this.data.setUint8(this.write++, b); return this; }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.DataBuffer.prototype.fillWithByte = function(b, n) { this.accommodate(n); for(var i = 0; i < n; ++i) { this.data.setUint8(b); } return this; }; /** * Puts bytes in this buffer. The bytes may be given as a string, an * ArrayBuffer, a DataView, or a TypedArray. * * @param bytes the bytes to put. * @param [encoding] the encoding for the first parameter ('binary', 'utf8', * 'utf16', 'hex'), if it is a string (default: 'binary'). * * @return this buffer. */ util.DataBuffer.prototype.putBytes = function(bytes, encoding) { if(util.isArrayBufferView(bytes)) { var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); var len = src.byteLength - src.byteOffset; this.accommodate(len); var dst = new Uint8Array(this.data.buffer, this.write); dst.set(src); this.write += len; return this; } if(util.isArrayBuffer(bytes)) { var src = new Uint8Array(bytes); this.accommodate(src.byteLength); var dst = new Uint8Array(this.data.buffer); dst.set(src, this.write); this.write += src.byteLength; return this; } // bytes is a util.DataBuffer or equivalent if(bytes instanceof util.DataBuffer || (typeof bytes === 'object' && typeof bytes.read === 'number' && typeof bytes.write === 'number' && util.isArrayBufferView(bytes.data))) { var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); this.accommodate(src.byteLength); var dst = new Uint8Array(bytes.data.byteLength, this.write); dst.set(src); this.write += src.byteLength; return this; } if(bytes instanceof util.ByteStringBuffer) { // copy binary string and process as the same as a string parameter below bytes = bytes.data; encoding = 'binary'; } // string conversion encoding = encoding || 'binary'; if(typeof bytes === 'string') { var view; // decode from string if(encoding === 'hex') { this.accommodate(Math.ceil(bytes.length / 2)); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.hex.decode(bytes, view, this.write); return this; } if(encoding === 'base64') { this.accommodate(Math.ceil(bytes.length / 4) * 3); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.base64.decode(bytes, view, this.write); return this; } // encode text as UTF-8 bytes if(encoding === 'utf8') { // encode as UTF-8 then decode string as raw binary bytes = util.encodeUtf8(bytes); encoding = 'binary'; } // decode string as raw binary if(encoding === 'binary' || encoding === 'raw') { // one byte per character this.accommodate(bytes.length); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.raw.decode(view); return this; } // encode text as UTF-16 bytes if(encoding === 'utf16') { // two bytes per character this.accommodate(bytes.length * 2); view = new Uint16Array(this.data.buffer, this.write); this.write += util.text.utf16.encode(view); return this; } throw new Error('Invalid encoding: ' + encoding); } throw Error('Invalid parameter: ' + bytes); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.DataBuffer.prototype.putBuffer = function(buffer) { this.putBytes(buffer); buffer.clear(); return this; }; /** * Puts a string into this buffer. * * @param str the string to put. * @param [encoding] the encoding for the string (default: 'utf16'). * * @return this buffer. */ util.DataBuffer.prototype.putString = function(str) { return this.putBytes(str, 'utf16'); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16 = function(i) { this.accommodate(2); this.data.setInt16(this.write, i); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24 = function(i) { this.accommodate(3); this.data.setInt16(this.write, i >> 8 & 0xFFFF); this.data.setInt8(this.write, i >> 16 & 0xFF); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32 = function(i) { this.accommodate(4); this.data.setInt32(this.write, i); this.write += 4; return this; }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16Le = function(i) { this.accommodate(2); this.data.setInt16(this.write, i, true); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24Le = function(i) { this.accommodate(3); this.data.setInt8(this.write, i >> 16 & 0xFF); this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32Le = function(i) { this.accommodate(4); this.data.setInt32(this.write, i, true); this.write += 4; return this; }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.DataBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); do { n -= 8; this.data.setInt8(this.write++, (i >> n) & 0xFF); } while(n > 0); return this; }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer. * * @return this buffer. */ util.DataBuffer.prototype.putSignedInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.DataBuffer.prototype.getByte = function() { return this.data.getInt8(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16 = function() { var rval = this.data.getInt16(this.read); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24 = function() { var rval = ( this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32 = function() { var rval = this.data.getInt32(this.read); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16Le = function() { var rval = this.data.getInt16(this.read, true); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24Le = function() { var rval = ( this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32Le = function() { var rval = this.data.getInt32(this.read, true); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.getInt8(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out as a binary encoded string and clears them from the * buffer. * * @param count the number of bytes to read, undefined or null for all. * * @return a binary encoded string of bytes. */ util.DataBuffer.prototype.getBytes = function(count) { // TODO: deprecate this method, it is poorly named and // this.toString('binary') replaces it // add a toTypedArray()/toArrayBuffer() function var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed
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/pkcs12.js
aws/lti-middleware/node_modules/node-forge/lib/pkcs12.js
/** * Javascript implementation of PKCS#12. * * @author Dave Longley * @author Stefan Siegl <[email protected]> * * Copyright (c) 2010-2014 Digital Bazaar, Inc. * Copyright (c) 2012 Stefan Siegl <[email protected]> * * The ASN.1 representation of PKCS#12 is as follows * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) * * PFX ::= SEQUENCE { * version INTEGER {v3(3)}(v3,...), * authSafe ContentInfo, * macData MacData OPTIONAL * } * * MacData ::= SEQUENCE { * mac DigestInfo, * macSalt OCTET STRING, * iterations INTEGER DEFAULT 1 * } * Note: The iterations default is for historical reasons and its use is * deprecated. A higher value, like 1024, is recommended. * * DigestInfo is defined in PKCS#7 as follows: * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters * for the algorithm, if any. In the case of SHA1 there is none. * * AlgorithmIdentifer ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * Digest ::= OCTET STRING * * * ContentInfo ::= SEQUENCE { * contentType ContentType, * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL * } * * ContentType ::= OBJECT IDENTIFIER * * AuthenticatedSafe ::= SEQUENCE OF ContentInfo * -- Data if unencrypted * -- EncryptedData if password-encrypted * -- EnvelopedData if public key-encrypted * * * SafeContents ::= SEQUENCE OF SafeBag * * SafeBag ::= SEQUENCE { * bagId BAG-TYPE.&id ({PKCS12BagSet}) * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), * bagAttributes SET OF PKCS12Attribute OPTIONAL * } * * PKCS12Attribute ::= SEQUENCE { * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) * } -- This type is compatible with the X.500 type 'Attribute' * * PKCS12AttrSet ATTRIBUTE ::= { * friendlyName | -- from PKCS #9 * localKeyId, -- from PKCS #9 * ... -- Other attributes are allowed * } * * CertBag ::= SEQUENCE { * certId BAG-TYPE.&id ({CertTypes}), * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) * } * * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} * -- DER-encoded X.509 certificate stored in OCTET STRING * * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} * -- Base64-encoded SDSI certificate stored in IA5String * * CertTypes BAG-TYPE ::= { * x509Certificate | * sdsiCertificate, * ... -- For future extensions * } */ var forge = require('./forge'); require('./asn1'); require('./hmac'); require('./oids'); require('./pkcs7asn1'); require('./pbe'); require('./random'); require('./rsa'); require('./sha1'); require('./util'); require('./x509'); // shortcut for asn.1 & PKI API var asn1 = forge.asn1; var pki = forge.pki; // shortcut for PKCS#12 API var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {}; var contentInfoValidator = { name: 'ContentInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, // a ContentInfo 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, constructed: true, captureAsn1: 'content' }] }; var pfxValidator = { name: 'PFX', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'PFX.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'version' }, contentInfoValidator, { name: 'PFX.macData', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, optional: true, captureAsn1: 'mac', value: [{ name: 'PFX.macData.mac', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, // DigestInfo constructed: true, value: [{ name: 'PFX.macData.mac.digestAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier constructed: true, value: [{ name: 'PFX.macData.mac.digestAlgorithm.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'macAlgorithm' }, { name: 'PFX.macData.mac.digestAlgorithm.parameters', tagClass: asn1.Class.UNIVERSAL, captureAsn1: 'macAlgorithmParameters' }] }, { name: 'PFX.macData.mac.digest', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'macDigest' }] }, { name: 'PFX.macData.macSalt', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'macSalt' }, { name: 'PFX.macData.iterations', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, optional: true, capture: 'macIterations' }] }] }; var safeBagValidator = { name: 'SafeBag', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'SafeBag.bagId', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'bagId' }, { name: 'SafeBag.bagValue', tagClass: asn1.Class.CONTEXT_SPECIFIC, constructed: true, captureAsn1: 'bagValue' }, { name: 'SafeBag.bagAttributes', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SET, constructed: true, optional: true, capture: 'bagAttributes' }] }; var attributeValidator = { name: 'Attribute', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'Attribute.attrId', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'oid' }, { name: 'Attribute.attrValues', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SET, constructed: true, capture: 'values' }] }; var certBagValidator = { name: 'CertBag', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'CertBag.certId', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'certId' }, { name: 'CertBag.certValue', tagClass: asn1.Class.CONTEXT_SPECIFIC, constructed: true, /* So far we only support X.509 certificates (which are wrapped in an OCTET STRING, hence hard code that here). */ value: [{ name: 'CertBag.certValue[0]', tagClass: asn1.Class.UNIVERSAL, type: asn1.Class.OCTETSTRING, constructed: false, capture: 'cert' }] }] }; /** * Search SafeContents structure for bags with matching attributes. * * The search can optionally be narrowed by a certain bag type. * * @param safeContents the SafeContents structure to search in. * @param attrName the name of the attribute to compare against. * @param attrValue the attribute value to search for. * @param [bagType] bag type to narrow search by. * * @return an array of matching bags. */ function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { var result = []; for(var i = 0; i < safeContents.length; i++) { for(var j = 0; j < safeContents[i].safeBags.length; j++) { var bag = safeContents[i].safeBags[j]; if(bagType !== undefined && bag.type !== bagType) { continue; } // only filter by bag type, no attribute specified if(attrName === null) { result.push(bag); continue; } if(bag.attributes[attrName] !== undefined && bag.attributes[attrName].indexOf(attrValue) >= 0) { result.push(bag); } } } return result; } /** * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. * * @param obj The PKCS#12 PFX in ASN.1 notation. * @param strict true to use strict DER decoding, false not to (default: true). * @param {String} password Password to decrypt with (optional). * * @return PKCS#12 PFX object. */ p12.pkcs12FromAsn1 = function(obj, strict, password) { // handle args if(typeof strict === 'string') { password = strict; strict = true; } else if(strict === undefined) { strict = true; } // validate PFX and capture data var capture = {}; var errors = []; if(!asn1.validate(obj, pfxValidator, capture, errors)) { var error = new Error('Cannot read PKCS#12 PFX. ' + 'ASN.1 object is not an PKCS#12 PFX.'); error.errors = error; throw error; } var pfx = { version: capture.version.charCodeAt(0), safeContents: [], /** * Gets bags with matching attributes. * * @param filter the attributes to filter by: * [localKeyId] the localKeyId to search for. * [localKeyIdHex] the localKeyId in hex to search for. * [friendlyName] the friendly name to search for. * [bagType] bag type to narrow each attribute search by. * * @return a map of attribute type to an array of matching bags or, if no * attribute was given but a bag type, the map key will be the * bag type. */ getBags: function(filter) { var rval = {}; var localKeyId; if('localKeyId' in filter) { localKeyId = filter.localKeyId; } else if('localKeyIdHex' in filter) { localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); } // filter on bagType only if(localKeyId === undefined && !('friendlyName' in filter) && 'bagType' in filter) { rval[filter.bagType] = _getBagsByAttribute( pfx.safeContents, null, null, filter.bagType); } if(localKeyId !== undefined) { rval.localKeyId = _getBagsByAttribute( pfx.safeContents, 'localKeyId', localKeyId, filter.bagType); } if('friendlyName' in filter) { rval.friendlyName = _getBagsByAttribute( pfx.safeContents, 'friendlyName', filter.friendlyName, filter.bagType); } return rval; }, /** * DEPRECATED: use getBags() instead. * * Get bags with matching friendlyName attribute. * * @param friendlyName the friendly name to search for. * @param [bagType] bag type to narrow search by. * * @return an array of bags with matching friendlyName attribute. */ getBagsByFriendlyName: function(friendlyName, bagType) { return _getBagsByAttribute( pfx.safeContents, 'friendlyName', friendlyName, bagType); }, /** * DEPRECATED: use getBags() instead. * * Get bags with matching localKeyId attribute. * * @param localKeyId the localKeyId to search for. * @param [bagType] bag type to narrow search by. * * @return an array of bags with matching localKeyId attribute. */ getBagsByLocalKeyId: function(localKeyId, bagType) { return _getBagsByAttribute( pfx.safeContents, 'localKeyId', localKeyId, bagType); } }; if(capture.version.charCodeAt(0) !== 3) { var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); error.version = capture.version.charCodeAt(0); throw error; } if(asn1.derToOid(capture.contentType) !== pki.oids.data) { var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); error.oid = asn1.derToOid(capture.contentType); throw error; } var data = capture.content.value[0]; if(data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); } data = _decodePkcs7Data(data); // check for MAC if(capture.mac) { var md = null; var macKeyBytes = 0; var macAlgorithm = asn1.derToOid(capture.macAlgorithm); switch(macAlgorithm) { case pki.oids.sha1: md = forge.md.sha1.create(); macKeyBytes = 20; break; case pki.oids.sha256: md = forge.md.sha256.create(); macKeyBytes = 32; break; case pki.oids.sha384: md = forge.md.sha384.create(); macKeyBytes = 48; break; case pki.oids.sha512: md = forge.md.sha512.create(); macKeyBytes = 64; break; case pki.oids.md5: md = forge.md.md5.create(); macKeyBytes = 16; break; } if(md === null) { throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); } // verify MAC (iterations default to 1) var macSalt = new forge.util.ByteBuffer(capture.macSalt); var macIterations = (('macIterations' in capture) ? parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1); var macKey = p12.generateKey( password, macSalt, 3, macIterations, macKeyBytes, md); var mac = forge.hmac.create(); mac.start(md, macKey); mac.update(data.value); var macValue = mac.getMac(); if(macValue.getBytes() !== capture.macDigest) { throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); } } _decodeAuthenticatedSafe(pfx, data.value, strict, password); return pfx; }; /** * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, * but it is sometimes an OCTET STRING that is composed/constructed of chunks, * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This * function transforms this corner-case into the usual simple, * non-composed/constructed OCTET STRING. * * This function may be moved to ASN.1 at some point to better deal with * more BER-encoding issues, should they arise. * * @param data the ASN.1 Data object to transform. */ function _decodePkcs7Data(data) { // handle special case of "chunked" data content: an octet string composed // of other octet strings if(data.composed || data.constructed) { var value = forge.util.createBuffer(); for(var i = 0; i < data.value.length; ++i) { value.putBytes(data.value[i].value); } data.composed = data.constructed = false; data.value = value.getBytes(); } return data; } /** * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. * * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. * * @param pfx The PKCS#12 PFX object to fill. * @param {String} authSafe BER-encoded AuthenticatedSafe. * @param strict true to use strict DER decoding, false not to. * @param {String} password Password to decrypt with (optional). */ function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */ if(authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + 'SEQUENCE OF ContentInfo'); } for(var i = 0; i < authSafe.value.length; i++) { var contentInfo = authSafe.value[i]; // validate contentInfo and capture data var capture = {}; var errors = []; if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { var error = new Error('Cannot read ContentInfo.'); error.errors = errors; throw error; } var obj = { encrypted: false }; var safeContents = null; var data = capture.content.value[0]; switch(asn1.derToOid(capture.contentType)) { case pki.oids.data: if(data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); } safeContents = _decodePkcs7Data(data).value; break; case pki.oids.encryptedData: safeContents = _decryptSafeContents(data, password); obj.encrypted = true; break; default: var error = new Error('Unsupported PKCS#12 contentType.'); error.contentType = asn1.derToOid(capture.contentType); throw error; } obj.safeBags = _decodeSafeContents(safeContents, strict, password); pfx.safeContents.push(obj); } } /** * Decrypt PKCS#7 EncryptedData structure. * * @param data ASN.1 encoded EncryptedContentInfo object. * @param password The user-provided password. * * @return The decrypted SafeContents (ASN.1 object). */ function _decryptSafeContents(data, password) { var capture = {}; var errors = []; if(!asn1.validate( data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) { var error = new Error('Cannot read EncryptedContentInfo.'); error.errors = errors; throw error; } var oid = asn1.derToOid(capture.contentType); if(oid !== pki.oids.data) { var error = new Error( 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); error.oid = oid; throw error; } // get cipher oid = asn1.derToOid(capture.encAlgorithm); var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); // get encrypted data var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); cipher.update(encrypted); if(!cipher.finish()) { throw new Error('Failed to decrypt PKCS#12 SafeContents.'); } return cipher.output.getBytes(); } /** * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. * * The safeContents is a BER-encoded SEQUENCE OF SafeBag. * * @param {String} safeContents BER-encoded safeContents. * @param strict true to use strict DER decoding, false not to. * @param {String} password Password to decrypt with (optional). * * @return {Array} Array of Bag objects. */ function _decodeSafeContents(safeContents, strict, password) { // if strict and no safe contents, return empty safes if(!strict && safeContents.length === 0) { return []; } // actually it's BER-encoded safeContents = asn1.fromDer(safeContents, strict); if(safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { throw new Error( 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); } var res = []; for(var i = 0; i < safeContents.value.length; i++) { var safeBag = safeContents.value[i]; // validate SafeBag and capture data var capture = {}; var errors = []; if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) { var error = new Error('Cannot read SafeBag.'); error.errors = errors; throw error; } /* Create bag object and push to result array. */ var bag = { type: asn1.derToOid(capture.bagId), attributes: _decodeBagAttributes(capture.bagAttributes) }; res.push(bag); var validator, decoder; var bagAsn1 = capture.bagValue.value[0]; switch(bag.type) { case pki.oids.pkcs8ShroudedKeyBag: /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. Afterwards we can handle it like a keyBag, which is a PrivateKeyInfo. */ bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); if(bagAsn1 === null) { throw new Error( 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); } /* fall through */ case pki.oids.keyBag: /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our PKI module, hence we don't have to do validation/capturing here, just pass what we already got. */ try { bag.key = pki.privateKeyFromAsn1(bagAsn1); } catch(e) { // ignore unknown key type, pass asn1 value bag.key = null; bag.asn1 = bagAsn1; } continue; /* Nothing more to do. */ case pki.oids.certBag: /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. Therefore put the SafeBag content through another validator to capture the fields. Afterwards check & store the results. */ validator = certBagValidator; decoder = function() { if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { var error = new Error( 'Unsupported certificate type, only X.509 supported.'); error.oid = asn1.derToOid(capture.certId); throw error; } // true=produce cert hash var certAsn1 = asn1.fromDer(capture.cert, strict); try { bag.cert = pki.certificateFromAsn1(certAsn1, true); } catch(e) { // ignore unknown cert type, pass asn1 value bag.cert = null; bag.asn1 = certAsn1; } }; break; default: var error = new Error('Unsupported PKCS#12 SafeBag type.'); error.oid = bag.type; throw error; } /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ if(validator !== undefined && !asn1.validate(bagAsn1, validator, capture, errors)) { var error = new Error('Cannot read PKCS#12 ' + validator.name); error.errors = errors; throw error; } /* Call decoder function from above to store the results. */ decoder(); } return res; } /** * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. * * @param attributes SET OF PKCS12Attribute (ASN.1 object). * * @return the decoded attributes. */ function _decodeBagAttributes(attributes) { var decodedAttrs = {}; if(attributes !== undefined) { for(var i = 0; i < attributes.length; ++i) { var capture = {}; var errors = []; if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) { var error = new Error('Cannot read PKCS#12 BagAttribute.'); error.errors = errors; throw error; } var oid = asn1.derToOid(capture.oid); if(pki.oids[oid] === undefined) { // unsupported attribute type, ignore. continue; } decodedAttrs[pki.oids[oid]] = []; for(var j = 0; j < capture.values.length; ++j) { decodedAttrs[pki.oids[oid]].push(capture.values[j].value); } } } return decodedAttrs; } /** * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a * password is provided then the private key will be encrypted. * * An entire certificate chain may also be included. To do this, pass * an array for the "cert" parameter where the first certificate is * the one that is paired with the private key and each subsequent one * verifies the previous one. The certificates may be in PEM format or * have been already parsed by Forge. * * @todo implement password-based-encryption for the whole package * * @param key the private key. * @param cert the certificate (may be an array of certificates in order * to specify a certificate chain). * @param password the password to use, null for none. * @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. * useMac true to include a MAC, false not to, defaults to true. * localKeyId the local key ID to use, in hex. * friendlyName the friendly name to use. * generateLocalKeyId true to generate a random local key ID, * false not to, defaults to true. * * @return the PKCS#12 PFX ASN.1 object. */ p12.toPkcs12Asn1 = function(key, cert, password, options) { // set default options options = options || {}; options.saltSize = options.saltSize || 8; options.count = options.count || 2048; options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; if(!('useMac' in options)) { options.useMac = true; } if(!('localKeyId' in options)) { options.localKeyId = null; } if(!('generateLocalKeyId' in options)) { options.generateLocalKeyId = true; } var localKeyId = options.localKeyId; var bagAttrs; if(localKeyId !== null) { localKeyId = forge.util.hexToBytes(localKeyId); } else if(options.generateLocalKeyId) { // use SHA-1 of paired cert, if available if(cert) { var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; if(typeof pairedCert === 'string') { pairedCert = pki.certificateFromPem(pairedCert); } var sha1 = forge.md.sha1.create(); sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); localKeyId = sha1.digest().getBytes(); } else { // FIXME: consider using SHA-1 of public key (which can be generated // from private key components), see: cert.generateSubjectKeyIdentifier // generate random bytes localKeyId = forge.random.getBytes(20); } } var attrs = []; if(localKeyId !== null) { attrs.push( // localKeyID asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // attrId asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.localKeyId).getBytes()), // attrValues asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, localKeyId) ]) ])); } if('friendlyName' in options) { attrs.push( // friendlyName asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // attrId asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.friendlyName).getBytes()), // attrValues asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, options.friendlyName) ]) ])); } if(attrs.length > 0) { bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); } // collect contents for AuthenticatedSafe var contents = []; // create safe bag(s) for certificate chain var chain = []; if(cert !== null) { if(forge.util.isArray(cert)) { chain = cert; } else { chain = [cert]; } } var certSafeBags = []; for(var i = 0; i < chain.length; ++i) { // convert cert from PEM as necessary cert = chain[i]; if(typeof cert === 'string') { cert = pki.certificateFromPem(cert); } // SafeBag var certBagAttrs = (i === 0) ? bagAttrs : undefined; var certAsn1 = pki.certificateToAsn1(cert); var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // bagId asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.certBag).getBytes()), // bagValue asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ // CertBag asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // certId asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.x509Certificate).getBytes()), // certValue (x509Certificate) asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(certAsn1).getBytes()) ])])]), // bagAttributes (OPTIONAL) certBagAttrs ]); certSafeBags.push(certSafeBag); } if(certSafeBags.length > 0) { // SafeContents var certSafeContents = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags); // ContentInfo var certCI = // PKCS#7 ContentInfo asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // contentType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, // OID for the content type is 'data' asn1.oidToDer(pki.oids.data).getBytes()), // content asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(certSafeContents).getBytes()) ]) ]); contents.push(certCI); } // create safe contents for private key var keyBag = null; if(key !== null) { // SafeBag var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); if(password === null) { // no encryption keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // bagId asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.keyBag).getBytes()), // bagValue asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ // PrivateKeyInfo pkAsn1 ]), // bagAttributes (OPTIONAL) bagAttrs ]); } else { // encrypted PrivateKeyInfo keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // bagId asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()), // bagValue asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ // EncryptedPrivateKeyInfo pki.encryptPrivateKeyInfo(pkAsn1, password, options) ]), // bagAttributes (OPTIONAL) bagAttrs ]); } // SafeContents var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); // ContentInfo var keyCI = // PKCS#7 ContentInfo asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // contentType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, // OID for the content type is 'data' asn1.oidToDer(pki.oids.data).getBytes()), // content asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(keySafeContents).getBytes()) ]) ]); contents.push(keyCI); } // create AuthenticatedSafe by stringing together the contents var safe = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents); var macData; if(options.useMac) { // MacData var sha1 = forge.md.sha1.create(); var macSalt = new forge.util.ByteBuffer( forge.random.getBytes(options.saltSize)); var count = options.count; // 160-bit key var key = p12.generateKey(password, macSalt, 3, count, 20); var mac = forge.hmac.create(); mac.start(sha1, key); mac.update(asn1.toDer(safe).getBytes()); var macValue = mac.getMac(); macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // mac DigestInfo asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // digestAlgorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm = SHA-1 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.sha1).getBytes()), // parameters = Null asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // digest asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macValue.getBytes()) ]), // macSalt OCTET STRING asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()), // iterations INTEGER (XXX: Only support count < 65536) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(count).getBytes() ) ]); } // PFX return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version (3) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(3).getBytes()), // PKCS#7 ContentInfo asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // contentType asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, // OID for the content type is 'data' asn1.oidToDer(pki.oids.data).getBytes()), // content asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
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.all.js
aws/lti-middleware/node_modules/node-forge/lib/md.all.js
/** * Node.js module for all known Forge message digests. * * @author Dave Longley * * Copyright 2011-2017 Digital Bazaar, Inc. */ module.exports = require('./md'); require('./md5'); require('./sha1'); require('./sha256'); require('./sha512');
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/random.js
aws/lti-middleware/node_modules/node-forge/lib/random.js
/** * An API for getting cryptographically-secure random bytes. The bytes are * generated using the Fortuna algorithm devised by Bruce Schneier and * Niels Ferguson. * * Getting strong random bytes is not yet easy to do in javascript. The only * truish random entropy that can be collected is from the mouse, keyboard, or * from timing with respect to page loads, etc. This generator makes a poor * attempt at providing random bytes when those sources haven't yet provided * enough entropy to initially seed or to reseed the PRNG. * * @author Dave Longley * * Copyright (c) 2009-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./aes'); require('./sha256'); require('./prng'); require('./util'); (function() { // forge.random already defined if(forge.random && forge.random.getBytes) { module.exports = forge.random; return; } (function(jQuery) { // the default prng plugin, uses AES-128 var prng_aes = {}; var _prng_aes_output = new Array(4); var _prng_aes_buffer = forge.util.createBuffer(); prng_aes.formatKey = function(key) { // convert the key into 32-bit integers var tmp = forge.util.createBuffer(key); key = new Array(4); key[0] = tmp.getInt32(); key[1] = tmp.getInt32(); key[2] = tmp.getInt32(); key[3] = tmp.getInt32(); // return the expanded key return forge.aes._expandKey(key, false); }; prng_aes.formatSeed = function(seed) { // convert seed into 32-bit integers var tmp = forge.util.createBuffer(seed); seed = new Array(4); seed[0] = tmp.getInt32(); seed[1] = tmp.getInt32(); seed[2] = tmp.getInt32(); seed[3] = tmp.getInt32(); return seed; }; prng_aes.cipher = function(key, seed) { forge.aes._updateBlock(key, seed, _prng_aes_output, false); _prng_aes_buffer.putInt32(_prng_aes_output[0]); _prng_aes_buffer.putInt32(_prng_aes_output[1]); _prng_aes_buffer.putInt32(_prng_aes_output[2]); _prng_aes_buffer.putInt32(_prng_aes_output[3]); return _prng_aes_buffer.getBytes(); }; prng_aes.increment = function(seed) { // FIXME: do we care about carry or signed issues? ++seed[3]; return seed; }; prng_aes.md = forge.md.sha256; /** * Creates a new PRNG. */ function spawnPrng() { var ctx = forge.prng.create(prng_aes); /** * Gets random bytes. If a native secure crypto API is unavailable, this * method tries to make the bytes more unpredictable by drawing from data that * can be collected from the user of the browser, eg: mouse movement. * * If a callback is given, this method will be called asynchronously. * * @param count the number of random bytes to get. * @param [callback(err, bytes)] called once the operation completes. * * @return the random bytes in a string. */ ctx.getBytes = function(count, callback) { return ctx.generate(count, callback); }; /** * Gets random bytes asynchronously. If a native secure crypto API is * unavailable, this method tries to make the bytes more unpredictable by * drawing from data that can be collected from the user of the browser, * eg: mouse movement. * * @param count the number of random bytes to get. * * @return the random bytes in a string. */ ctx.getBytesSync = function(count) { return ctx.generate(count); }; return ctx; } // create default prng context var _ctx = spawnPrng(); // add other sources of entropy only if window.crypto.getRandomValues is not // available -- otherwise this source will be automatically used by the prng var getRandomValues = null; var globalScope = forge.util.globalScope; var _crypto = globalScope.crypto || globalScope.msCrypto; if(_crypto && _crypto.getRandomValues) { getRandomValues = function(arr) { return _crypto.getRandomValues(arr); }; } if(forge.options.usePureJavaScript || (!forge.util.isNodejs && !getRandomValues)) { // if this is a web worker, do not use weak entropy, instead register to // receive strong entropy asynchronously from the main thread if(typeof window === 'undefined' || window.document === undefined) { // FIXME: } // get load time entropy _ctx.collectInt(+new Date(), 32); // add some entropy from navigator object if(typeof(navigator) !== 'undefined') { var _navBytes = ''; for(var key in navigator) { try { if(typeof(navigator[key]) == 'string') { _navBytes += navigator[key]; } } catch(e) { /* Some navigator keys might not be accessible, e.g. the geolocation attribute throws an exception if touched in Mozilla chrome:// context. Silently ignore this and just don't use this as a source of entropy. */ } } _ctx.collect(_navBytes); _navBytes = null; } // add mouse and keyboard collectors if jquery is available if(jQuery) { // set up mouse entropy capture jQuery().mousemove(function(e) { // add mouse coords _ctx.collectInt(e.clientX, 16); _ctx.collectInt(e.clientY, 16); }); // set up keyboard entropy capture jQuery().keypress(function(e) { _ctx.collectInt(e.charCode, 8); }); } } /* Random API */ if(!forge.random) { forge.random = _ctx; } else { // extend forge.random with _ctx for(var key in _ctx) { forge.random[key] = _ctx[key]; } } // expose spawn PRNG forge.random.createInstance = spawnPrng; module.exports = forge.random; })(typeof(jQuery) !== 'undefined' ? jQuery : 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/node-forge/lib/asn1-validator.js
aws/lti-middleware/node_modules/node-forge/lib/asn1-validator.js
/** * Copyright (c) 2019 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./asn1'); var asn1 = forge.asn1; exports.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' }] }; exports.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' }] }, // capture group for ed25519PublicKey { tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, composed: true, captureBitStringValue: 'ed25519PublicKey' } // FIXME: this is capture group for rsaPublicKey, use it in this API or // discard? /* { // 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' }] } */ ] };
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/cipherModes.js
aws/lti-middleware/node_modules/node-forge/lib/cipherModes.js
/** * Supported cipher modes. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./util'); forge.cipher = forge.cipher || {}; // supported cipher modes var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {}; /** Electronic codebook (ECB) (Don't use this; it's not secure) **/ modes.ecb = function(options) { options = options || {}; this.name = 'ECB'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); }; modes.ecb.prototype.start = function(options) {}; modes.ecb.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // write output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i]); } }; modes.ecb.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); } // decrypt block this.cipher.decrypt(this._inBlock, this._outBlock); // write output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i]); } }; modes.ecb.prototype.pad = function(input, options) { // add PKCS#7 padding to block (each pad byte is the // value of the number of pad bytes) var padding = (input.length() === this.blockSize ? this.blockSize : (this.blockSize - input.length())); input.fillWithByte(padding, padding); return true; }; modes.ecb.prototype.unpad = function(output, options) { // check for error: input data not a multiple of blockSize if(options.overflow > 0) { return false; } // ensure padding byte count is valid var len = output.length(); var count = output.at(len - 1); if(count > (this.blockSize << 2)) { return false; } // trim off padding bytes output.truncate(count); return true; }; /** Cipher-block Chaining (CBC) **/ modes.cbc = function(options) { options = options || {}; this.name = 'CBC'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); }; modes.cbc.prototype.start = function(options) { // Note: legacy support for using IV residue (has security flaws) // if IV is null, reuse block from previous processing if(options.iv === null) { // must have a previous block if(!this._prev) { throw new Error('Invalid IV parameter.'); } this._iv = this._prev.slice(0); } else if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } else { // save IV as "previous" block this._iv = transformIV(options.iv, this.blockSize); this._prev = this._iv.slice(0); } }; modes.cbc.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block // CBC XOR's IV (or previous block) with plaintext for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._prev[i] ^ input.getInt32(); } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // write output, save previous block for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i]); } this._prev = this._outBlock; }; modes.cbc.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt if(input.length() < this.blockSize && !(finish && input.length() > 0)) { return true; } // get next block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); } // decrypt block this.cipher.decrypt(this._inBlock, this._outBlock); // write output, save previous ciphered block // CBC XOR's IV (or previous block) with ciphertext for(var i = 0; i < this._ints; ++i) { output.putInt32(this._prev[i] ^ this._outBlock[i]); } this._prev = this._inBlock.slice(0); }; modes.cbc.prototype.pad = function(input, options) { // add PKCS#7 padding to block (each pad byte is the // value of the number of pad bytes) var padding = (input.length() === this.blockSize ? this.blockSize : (this.blockSize - input.length())); input.fillWithByte(padding, padding); return true; }; modes.cbc.prototype.unpad = function(output, options) { // check for error: input data not a multiple of blockSize if(options.overflow > 0) { return false; } // ensure padding byte count is valid var len = output.length(); var count = output.at(len - 1); if(count > (this.blockSize << 2)) { return false; } // trim off padding bytes output.truncate(count); return true; }; /** Cipher feedback (CFB) **/ modes.cfb = function(options) { options = options || {}; this.name = 'CFB'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = null; this._outBlock = new Array(this._ints); this._partialBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; }; modes.cfb.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // use IV as first input this._iv = transformIV(options.iv, this.blockSize); this._inBlock = this._iv.slice(0); this._partialBytes = 0; }; modes.cfb.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output, write input as output for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; output.putInt32(this._inBlock[i]); } return; } // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output, write input as partial output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; this._partialOutput.putInt32(this._partialBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } else { // block complete, update input block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._partialBlock[i]; } } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; }; modes.cfb.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block (CFB always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output, write input as output for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = input.getInt32(); output.putInt32(this._inBlock[i] ^ this._outBlock[i]); } return; } // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output, write input as partial output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialBlock[i] = input.getInt32(); this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } else { // block complete, update input block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._partialBlock[i]; } } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; }; /** Output feedback (OFB) **/ modes.ofb = function(options) { options = options || {}; this.name = 'OFB'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = null; this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; }; modes.ofb.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // use IV as first input this._iv = transformIV(options.iv, this.blockSize); this._inBlock = this._iv.slice(0); this._partialBytes = 0; }; modes.ofb.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(input.length() === 0) { return true; } // encrypt block (OFB always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output and update next input for(var i = 0; i < this._ints; ++i) { output.putInt32(input.getInt32() ^ this._outBlock[i]); this._inBlock[i] = this._outBlock[i]; } return; } // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } else { // block complete, update input block for(var i = 0; i < this._ints; ++i) { this._inBlock[i] = this._outBlock[i]; } } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; }; modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; /** Counter (CTR) **/ modes.ctr = function(options) { options = options || {}; this.name = 'CTR'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = null; this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; }; modes.ctr.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // use IV as first input this._iv = transformIV(options.iv, this.blockSize); this._inBlock = this._iv.slice(0); this._partialBytes = 0; }; modes.ctr.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block (CTR always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output for(var i = 0; i < this._ints; ++i) { output.putInt32(input.getInt32() ^ this._outBlock[i]); } } else { // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if(partialBytes > 0) { // block still incomplete, restore input buffer input.read -= this.blockSize; } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; } // block complete, increment counter (input block) inc32(this._inBlock); }; modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; /** Galois/Counter Mode (GCM) **/ modes.gcm = function(options) { options = options || {}; this.name = 'GCM'; this.cipher = options.cipher; this.blockSize = options.blockSize || 16; this._ints = this.blockSize / 4; this._inBlock = new Array(this._ints); this._outBlock = new Array(this._ints); this._partialOutput = forge.util.createBuffer(); this._partialBytes = 0; // R is actually this value concatenated with 120 more zero bits, but // we only XOR against R so the other zeros have no effect -- we just // apply this value to the first integer in a block this._R = 0xE1000000; }; modes.gcm.prototype.start = function(options) { if(!('iv' in options)) { throw new Error('Invalid IV parameter.'); } // ensure IV is a byte buffer var iv = forge.util.createBuffer(options.iv); // no ciphered data processed yet this._cipherLength = 0; // default additional data is none var additionalData; if('additionalData' in options) { additionalData = forge.util.createBuffer(options.additionalData); } else { additionalData = forge.util.createBuffer(); } // default tag length is 128 bits if('tagLength' in options) { this._tagLength = options.tagLength; } else { this._tagLength = 128; } // if tag is given, ensure tag matches tag length this._tag = null; if(options.decrypt) { // save tag to check later this._tag = forge.util.createBuffer(options.tag).getBytes(); if(this._tag.length !== (this._tagLength / 8)) { throw new Error('Authentication tag does not match tag length.'); } } // create tmp storage for hash calculation this._hashBlock = new Array(this._ints); // no tag generated yet this.tag = null; // generate hash subkey // (apply block cipher to "zero" block) this._hashSubkey = new Array(this._ints); this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); // generate table M // use 4-bit tables (32 component decomposition of a 16 byte value) // 8-bit tables take more space and are known to have security // vulnerabilities (in native implementations) this.componentBits = 4; this._m = this.generateHashTable(this._hashSubkey, this.componentBits); // Note: support IV length different from 96 bits? (only supporting // 96 bits is recommended by NIST SP-800-38D) // generate J_0 var ivLength = iv.length(); if(ivLength === 12) { // 96-bit IV this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; } else { // IV is NOT 96-bits this._j0 = [0, 0, 0, 0]; while(iv.length() > 0) { this._j0 = this.ghash( this._hashSubkey, this._j0, [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); } this._j0 = this.ghash( this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); } // generate ICB (initial counter block) this._inBlock = this._j0.slice(0); inc32(this._inBlock); this._partialBytes = 0; // consume authentication data additionalData = forge.util.createBuffer(additionalData); // save additional data length as a BE 64-bit number this._aDataLength = from64To32(additionalData.length() * 8); // pad additional data to 128 bit (16 byte) block size var overflow = additionalData.length() % this.blockSize; if(overflow) { additionalData.fillWithByte(0, this.blockSize - overflow); } this._s = [0, 0, 0, 0]; while(additionalData.length() > 0) { this._s = this.ghash(this._hashSubkey, this._s, [ additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32(), additionalData.getInt32() ]); } }; modes.gcm.prototype.encrypt = function(input, output, finish) { // not enough input to encrypt var inputLength = input.length(); if(inputLength === 0) { return true; } // encrypt block this.cipher.encrypt(this._inBlock, this._outBlock); // handle full block if(this._partialBytes === 0 && inputLength >= this.blockSize) { // XOR input with output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i] ^= input.getInt32()); } this._cipherLength += this.blockSize; } else { // handle partial block var partialBytes = (this.blockSize - inputLength) % this.blockSize; if(partialBytes > 0) { partialBytes = this.blockSize - partialBytes; } // XOR input with output this._partialOutput.clear(); for(var i = 0; i < this._ints; ++i) { this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); } if(partialBytes <= 0 || finish) { // handle overflow prior to hashing if(finish) { // get block overflow var overflow = inputLength % this.blockSize; this._cipherLength += overflow; // truncate for hash function this._partialOutput.truncate(this.blockSize - overflow); } else { this._cipherLength += this.blockSize; } // get output block for hashing for(var i = 0; i < this._ints; ++i) { this._outBlock[i] = this._partialOutput.getInt32(); } this._partialOutput.read -= this.blockSize; } // skip any previous partial bytes if(this._partialBytes > 0) { this._partialOutput.getBytes(this._partialBytes); } if(partialBytes > 0 && !finish) { // block still incomplete, restore input buffer, get partial output, // and return early input.read -= this.blockSize; output.putBytes(this._partialOutput.getBytes( partialBytes - this._partialBytes)); this._partialBytes = partialBytes; return true; } output.putBytes(this._partialOutput.getBytes( inputLength - this._partialBytes)); this._partialBytes = 0; } // update hash block S this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); // increment counter (input block) inc32(this._inBlock); }; modes.gcm.prototype.decrypt = function(input, output, finish) { // not enough input to decrypt var inputLength = input.length(); if(inputLength < this.blockSize && !(finish && inputLength > 0)) { return true; } // encrypt block (GCM always uses encryption mode) this.cipher.encrypt(this._inBlock, this._outBlock); // increment counter (input block) inc32(this._inBlock); // update hash block S this._hashBlock[0] = input.getInt32(); this._hashBlock[1] = input.getInt32(); this._hashBlock[2] = input.getInt32(); this._hashBlock[3] = input.getInt32(); this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); // XOR hash input with output for(var i = 0; i < this._ints; ++i) { output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); } // increment cipher data length if(inputLength < this.blockSize) { this._cipherLength += inputLength % this.blockSize; } else { this._cipherLength += this.blockSize; } }; modes.gcm.prototype.afterFinish = function(output, options) { var rval = true; // handle overflow if(options.decrypt && options.overflow) { output.truncate(this.blockSize - options.overflow); } // handle authentication tag this.tag = forge.util.createBuffer(); // concatenate additional data length with cipher length var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); // include lengths in hash this._s = this.ghash(this._hashSubkey, this._s, lengths); // do GCTR(J_0, S) var tag = []; this.cipher.encrypt(this._j0, tag); for(var i = 0; i < this._ints; ++i) { this.tag.putInt32(this._s[i] ^ tag[i]); } // trim tag to length this.tag.truncate(this.tag.length() % (this._tagLength / 8)); // check authentication tag if(options.decrypt && this.tag.bytes() !== this._tag) { rval = false; } return rval; }; /** * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois * field multiplication. The field, GF(2^128), is defined by the polynomial: * * x^128 + x^7 + x^2 + x + 1 * * Which is represented in little-endian binary form as: 11100001 (0xe1). When * the value of a coefficient is 1, a bit is set. The value R, is the * concatenation of this value and 120 zero bits, yielding a 128-bit value * which matches the block size. * * This function will multiply two elements (vectors of bytes), X and Y, in * the field GF(2^128). The result is initialized to zero. For each bit of * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) * by the current value of Y. For each bit, the value of Y will be raised by * a power of x (multiplied by the polynomial x). This can be achieved by * shifting Y once to the right. If the current value of Y, prior to being * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. * Otherwise, we must divide by R after shifting to find the remainder. * * @param x the first block to multiply by the second. * @param y the second block to multiply by the first. * * @return the block result of the multiplication. */ modes.gcm.prototype.multiply = function(x, y) { var z_i = [0, 0, 0, 0]; var v_i = y.slice(0); // calculate Z_128 (block has 128 bits) for(var i = 0; i < 128; ++i) { // if x_i is 0, Z_{i+1} = Z_i (unchanged) // else Z_{i+1} = Z_i ^ V_i // get x_i by finding 32-bit int position, then left shift 1 by remainder var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); if(x_i) { z_i[0] ^= v_i[0]; z_i[1] ^= v_i[1]; z_i[2] ^= v_i[2]; z_i[3] ^= v_i[3]; } // if LSB(V_i) is 1, V_i = V_i >> 1 // else V_i = (V_i >> 1) ^ R this.pow(v_i, v_i); } return z_i; }; modes.gcm.prototype.pow = function(x, out) { // if LSB(x) is 1, x = x >>> 1 // else x = (x >>> 1) ^ R var lsb = x[3] & 1; // always do x >>> 1: // starting with the rightmost integer, shift each integer to the right // one bit, pulling in the bit from the integer to the left as its top // most bit (do this for the last 3 integers) for(var i = 3; i > 0; --i) { out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); } // shift the first integer normally out[0] = x[0] >>> 1; // if lsb was not set, then polynomial had a degree of 127 and doesn't // need to divided; otherwise, XOR with R to find the remainder; we only // need to XOR the first integer since R technically ends w/120 zero bits if(lsb) { out[0] ^= this._R; } }; modes.gcm.prototype.tableMultiply = function(x) { // assumes 4-bit tables are used var z = [0, 0, 0, 0]; for(var i = 0; i < 32; ++i) { var idx = (i / 8) | 0; var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; var ah = this._m[i][x_i]; z[0] ^= ah[0]; z[1] ^= ah[1]; z[2] ^= ah[2]; z[3] ^= ah[3]; } return z; }; /** * A continuing version of the GHASH algorithm that operates on a single * block. The hash block, last hash value (Ym) and the new block to hash * are given. * * @param h the hash block. * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. * @param x the block to hash. * * @return the hashed value (Ym). */ modes.gcm.prototype.ghash = function(h, y, x) { y[0] ^= x[0]; y[1] ^= x[1]; y[2] ^= x[2]; y[3] ^= x[3]; return this.tableMultiply(y); //return this.multiply(y, h); }; /** * Precomputes a table for multiplying against the hash subkey. This * mechanism provides a substantial speed increase over multiplication * performed without a table. The table-based multiplication this table is * for solves X * H by multiplying each component of X by H and then * composing the results together using XOR. * * This function can be used to generate tables with different bit sizes * for the components, however, this implementation assumes there are * 32 components of X (which is a 16 byte vector), therefore each component * takes 4-bits (so the table is constructed with bits=4). * * @param h the hash subkey. * @param bits the bit size for a component. */ modes.gcm.prototype.generateHashTable = function(h, bits) { // TODO: There are further optimizations that would use only the // first table M_0 (or some variant) along with a remainder table; // this can be explored in the future var multiplier = 8 / bits; var perInt = 4 * multiplier; var size = 16 * multiplier; var m = new Array(size); for(var i = 0; i < size; ++i) { var tmp = [0, 0, 0, 0]; var idx = (i / perInt) | 0; var shft = ((perInt - 1 - (i % perInt)) * bits); tmp[idx] = (1 << (bits - 1)) << shft; m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); } return m; }; /** * Generates a table for multiplying against the hash subkey for one * particular component (out of all possible component values). * * @param mid the pre-multiplied value for the middle key of the table. * @param bits the bit size for a component. */ modes.gcm.prototype.generateSubHashTable = function(mid, bits) { // compute the table quickly by minimizing the number of // POW operations -- they only need to be performed for powers of 2, // all other entries can be composed from those powers using XOR var size = 1 << bits; var half = size >>> 1; var m = new Array(size); m[half] = mid.slice(0); var i = half >>> 1; while(i > 0) { // raise m0[2 * i] and store in m0[i] this.pow(m[2 * i], m[i] = []); i >>= 1; } i = 2; while(i < half) { for(var j = 1; j < i; ++j) { var m_i = m[i]; var m_j = m[j]; m[i + j] = [ m_i[0] ^ m_j[0], m_i[1] ^ m_j[1], m_i[2] ^ m_j[2], m_i[3] ^ m_j[3] ]; } i *= 2; } m[0] = [0, 0, 0, 0]; /* Note: We could avoid storing these by doing composition during multiply calculate top half using composition by speed is preferred. */ for(i = half + 1; i < size; ++i) { var c = m[i ^ half]; m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; } return m; }; /** Utility functions */ function transformIV(iv, blockSize) { if(typeof iv === 'string') { // convert iv string into byte buffer iv = forge.util.createBuffer(iv); } if(forge.util.isArray(iv) && iv.length > 4) { // convert iv byte array into byte buffer var tmp = iv; iv = forge.util.createBuffer(); for(var i = 0; i < tmp.length; ++i) { iv.putByte(tmp[i]); } } if(iv.length() < blockSize) { throw new Error( 'Invalid IV length; got ' + iv.length() + ' bytes and expected ' + blockSize + ' bytes.'); } if(!forge.util.isArray(iv)) { // convert iv byte buffer into 32-bit integer array var ints = []; var blocks = blockSize / 4; for(var i = 0; i < blocks; ++i) { ints.push(iv.getInt32()); } iv = ints; } return iv; } function inc32(block) { // increment last 32 bits of block only block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; } function from64To32(num) { // convert 64-bit number to two BE Int32s return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; }
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/xhr.js
aws/lti-middleware/node_modules/node-forge/lib/xhr.js
/** * XmlHttpRequest implementation that uses TLS and flash SocketPool. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./socket'); require('./http'); /* XHR API */ var xhrApi = module.exports = forge.xhr = forge.xhr || {}; (function($) { // logging category var cat = 'forge.xhr'; /* XMLHttpRequest interface definition from: http://www.w3.org/TR/XMLHttpRequest interface XMLHttpRequest { // event handler attribute EventListener onreadystatechange; // state const unsigned short UNSENT = 0; const unsigned short OPENED = 1; const unsigned short HEADERS_RECEIVED = 2; const unsigned short LOADING = 3; const unsigned short DONE = 4; readonly attribute unsigned short readyState; // request void open(in DOMString method, in DOMString url); void open(in DOMString method, in DOMString url, in boolean async); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user); void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password); void setRequestHeader(in DOMString header, in DOMString value); void send(); void send(in DOMString data); void send(in Document data); void abort(); // response DOMString getAllResponseHeaders(); DOMString getResponseHeader(in DOMString header); readonly attribute DOMString responseText; readonly attribute Document responseXML; readonly attribute unsigned short status; readonly attribute DOMString statusText; }; */ // readyStates var UNSENT = 0; var OPENED = 1; var HEADERS_RECEIVED = 2; var LOADING = 3; var DONE = 4; // exceptions var INVALID_STATE_ERR = 11; var SYNTAX_ERR = 12; var SECURITY_ERR = 18; var NETWORK_ERR = 19; var ABORT_ERR = 20; // private flash socket pool vars var _sp = null; var _policyPort = 0; var _policyUrl = null; // default client (used if no special URL provided when creating an XHR) var _client = null; // all clients including the default, key'd by full base url // (multiple cross-domain http clients are permitted so there may be more // than one client in this map) // TODO: provide optional clean up API for non-default clients var _clients = {}; // the default maximum number of concurrents connections per client var _maxConnections = 10; var net = forge.net; var http = forge.http; /** * Initializes flash XHR support. * * @param options: * url: the default base URL to connect to if xhr URLs are relative, * ie: https://myserver.com. * flashId: the dom ID of the flash SocketPool. * policyPort: the port that provides the server's flash policy, 0 to use * the flash default. * policyUrl: the policy file URL to use instead of a policy port. * msie: true if browser is internet explorer, false if not. * connections: the maximum number of concurrent connections. * caCerts: a list of PEM-formatted certificates to trust. * cipherSuites: an optional array of cipher suites to use, * see forge.tls.CipherSuites. * verify: optional TLS certificate verify callback to use (see forge.tls * for details). * 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. */ xhrApi.init = function(options) { forge.log.debug(cat, 'initializing', options); // update default policy port and max connections _policyPort = options.policyPort || _policyPort; _policyUrl = options.policyUrl || _policyUrl; _maxConnections = options.connections || _maxConnections; // create the flash socket pool _sp = net.createSocketPool({ flashId: options.flashId, policyPort: _policyPort, policyUrl: _policyUrl, msie: options.msie || false }); // create default http client _client = http.createClient({ url: options.url || ( window.location.protocol + '//' + window.location.host), socketPool: _sp, policyPort: _policyPort, policyUrl: _policyUrl, connections: options.connections || _maxConnections, caCerts: options.caCerts, cipherSuites: options.cipherSuites, persistCookies: options.persistCookies || true, primeTlsSockets: options.primeTlsSockets || false, verify: options.verify, getCertificate: options.getCertificate, getPrivateKey: options.getPrivateKey, getSignature: options.getSignature }); _clients[_client.url.origin] = _client; forge.log.debug(cat, 'ready'); }; /** * Called to clean up the clients and socket pool. */ xhrApi.cleanup = function() { // destroy all clients for(var key in _clients) { _clients[key].destroy(); } _clients = {}; _client = null; // destroy socket pool _sp.destroy(); _sp = null; }; /** * Sets a cookie. * * @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. */ xhrApi.setCookie = function(cookie) { // default cookie expiration to never cookie.maxAge = cookie.maxAge || -1; // if the cookie's domain is set, use the appropriate client if(cookie.domain) { // add the cookies to the applicable domains for(var key in _clients) { var client = _clients[key]; if(http.withinCookieDomain(client.url, cookie) && client.secure === cookie.secure) { client.setCookie(cookie); } } } else { // use the default domain // FIXME: should a null domain cookie be added to all clients? should // this be an option? _client.setCookie(cookie); } }; /** * Gets a cookie. * * @param name the name of the cookie. * @param path an optional path for the cookie (if there are multiple cookies * with the same name but different paths). * @param domain an optional domain for the cookie (if not using the default * domain). * * @return the cookie, cookies (if multiple matches), or null if not found. */ xhrApi.getCookie = function(name, path, domain) { var rval = null; if(domain) { // get the cookies from the applicable domains for(var key in _clients) { var client = _clients[key]; if(http.withinCookieDomain(client.url, domain)) { var cookie = client.getCookie(name, path); if(cookie !== null) { if(rval === null) { rval = cookie; } else if(!forge.util.isArray(rval)) { rval = [rval, cookie]; } else { rval.push(cookie); } } } } } else { // get cookie from default domain rval = _client.getCookie(name, path); } return rval; }; /** * Removes a cookie. * * @param name the name of the cookie. * @param path an optional path for the cookie (if there are multiple cookies * with the same name but different paths). * @param domain an optional domain for the cookie (if not using the default * domain). * * @return true if a cookie was removed, false if not. */ xhrApi.removeCookie = function(name, path, domain) { var rval = false; if(domain) { // remove the cookies from the applicable domains for(var key in _clients) { var client = _clients[key]; if(http.withinCookieDomain(client.url, domain)) { if(client.removeCookie(name, path)) { rval = true; } } } } else { // remove cookie from default domain rval = _client.removeCookie(name, path); } return rval; }; /** * Creates a new XmlHttpRequest. By default the base URL, flash policy port, * etc, will be used. However, an XHR can be created to point at another * cross-domain URL. * * @param options: * logWarningOnError: If true and an HTTP error status code is received then * log a warning, otherwise log a verbose message. * verbose: If true be very verbose in the output including the response * event and response body, otherwise only include status, timing, and * data size. * logError: a multi-var log function for warnings that takes the log * category as the first var. * logWarning: a multi-var log function for warnings that takes the log * category as the first var. * logDebug: a multi-var log function for warnings that takes the log * category as the first var. * logVerbose: a multi-var log function for warnings that takes the log * category as the first var. * url: the default base URL to connect to if xhr URLs are relative, * eg: https://myserver.com, and note that the following options will be * ignored if the URL is absent or the same as the default base URL. * policyPort: the port that provides the server's flash policy, 0 to use * the flash default. * policyUrl: the policy file URL to use instead of a policy port. * connections: the maximum number of concurrent connections. * caCerts: a list of PEM-formatted certificates to trust. * cipherSuites: an optional array of cipher suites to use, see * forge.tls.CipherSuites. * verify: optional TLS certificate verify callback to use (see forge.tls * for details). * getCertificate: an optional callback used to get a client-side * certificate. * getPrivateKey: an optional callback used to get a client-side private key. * getSignature: an optional callback used to get a client-side signature. * 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 XmlHttpRequest. */ xhrApi.create = function(options) { // set option defaults options = $.extend({ logWarningOnError: true, verbose: false, logError: function() {}, logWarning: function() {}, logDebug: function() {}, logVerbose: function() {}, url: null }, options || {}); // private xhr state var _state = { // the http client to use client: null, // request storage request: null, // response storage response: null, // asynchronous, true if doing asynchronous communication asynchronous: true, // sendFlag, true if send has been called sendFlag: false, // errorFlag, true if a network error occurred errorFlag: false }; // private log functions var _log = { error: options.logError || forge.log.error, warning: options.logWarning || forge.log.warning, debug: options.logDebug || forge.log.debug, verbose: options.logVerbose || forge.log.verbose }; // create public xhr interface var xhr = { // an EventListener onreadystatechange: null, // readonly, the current readyState readyState: UNSENT, // a string with the response entity-body responseText: '', // a Document for response entity-bodies that are XML responseXML: null, // readonly, returns the HTTP status code (i.e. 404) status: 0, // readonly, returns the HTTP status message (i.e. 'Not Found') statusText: '' }; // determine which http client to use if(options.url === null) { // use default _state.client = _client; } else { var url; try { url = new URL(options.url); } catch(e) { var error = new Error('Invalid url.'); error.details = { url: options.url }; } // find client if(url.origin in _clients) { // client found _state.client = _clients[url.origin]; } else { // create client _state.client = http.createClient({ url: options.url, socketPool: _sp, policyPort: options.policyPort || _policyPort, policyUrl: options.policyUrl || _policyUrl, connections: options.connections || _maxConnections, caCerts: options.caCerts, cipherSuites: options.cipherSuites, persistCookies: options.persistCookies || true, primeTlsSockets: options.primeTlsSockets || false, verify: options.verify, getCertificate: options.getCertificate, getPrivateKey: options.getPrivateKey, getSignature: options.getSignature }); _clients[url.origin] = _state.client; } } /** * Opens the request. This method will create the HTTP request to send. * * @param method the HTTP method (i.e. 'GET'). * @param url the relative url (the HTTP request path). * @param async always true, ignored. * @param user always null, ignored. * @param password always null, ignored. */ xhr.open = function(method, url, async, user, password) { // 1. validate Document if one is associated // TODO: not implemented (not used yet) // 2. validate method token // 3. change method to uppercase if it matches a known // method (here we just require it to be uppercase, and // we do not allow the standard methods) // 4. disallow CONNECT, TRACE, or TRACK with a security error switch(method) { case 'DELETE': case 'GET': case 'HEAD': case 'OPTIONS': case 'PATCH': case 'POST': case 'PUT': // valid method break; case 'CONNECT': case 'TRACE': case 'TRACK': throw new Error('CONNECT, TRACE and TRACK methods are disallowed'); default: throw new Error('Invalid method: ' + method); } // TODO: other validation steps in algorithm are not implemented // 19. set send flag to false // set response body to null // empty list of request headers // set request method to given method // set request URL // set username, password // set asychronous flag _state.sendFlag = false; xhr.responseText = ''; xhr.responseXML = null; // custom: reset status and statusText xhr.status = 0; xhr.statusText = ''; // create the HTTP request _state.request = http.createRequest({ method: method, path: url }); // 20. set state to OPENED xhr.readyState = OPENED; // 21. dispatch onreadystatechange if(xhr.onreadystatechange) { xhr.onreadystatechange(); } }; /** * Adds an HTTP header field to the request. * * @param header the name of the header field. * @param value the value of the header field. */ xhr.setRequestHeader = function(header, value) { // 1. if state is not OPENED or send flag is true, raise exception if(xhr.readyState != OPENED || _state.sendFlag) { throw new Error('XHR not open or sending'); } // TODO: other validation steps in spec aren't implemented // set header _state.request.setField(header, value); }; /** * Sends the request and any associated data. * * @param data a string or Document object to send, null to send no data. */ xhr.send = function(data) { // 1. if state is not OPENED or 2. send flag is true, raise // an invalid state exception if(xhr.readyState != OPENED || _state.sendFlag) { throw new Error('XHR not open or sending'); } // 3. ignore data if method is GET or HEAD if(data && _state.request.method !== 'GET' && _state.request.method !== 'HEAD') { // handle non-IE case if(typeof(XMLSerializer) !== 'undefined') { if(data instanceof Document) { var xs = new XMLSerializer(); _state.request.body = xs.serializeToString(data); } else { _state.request.body = data; } } else { // poorly implemented IE case if(typeof(data.xml) !== 'undefined') { _state.request.body = data.xml; } else { _state.request.body = data; } } } // 4. release storage mutex (not used) // 5. set error flag to false _state.errorFlag = false; // 6. if asynchronous is true (must be in this implementation) // 6.1 set send flag to true _state.sendFlag = true; // 6.2 dispatch onreadystatechange if(xhr.onreadystatechange) { xhr.onreadystatechange(); } // create send options var options = {}; options.request = _state.request; options.headerReady = function(e) { // make cookies available for ease of use/iteration xhr.cookies = _state.client.cookies; // TODO: update document.cookie with any cookies where the // script's domain matches // headers received xhr.readyState = HEADERS_RECEIVED; xhr.status = e.response.code; xhr.statusText = e.response.message; _state.response = e.response; if(xhr.onreadystatechange) { xhr.onreadystatechange(); } if(!_state.response.aborted) { // now loading body xhr.readyState = LOADING; if(xhr.onreadystatechange) { xhr.onreadystatechange(); } } }; options.bodyReady = function(e) { xhr.readyState = DONE; var ct = e.response.getField('Content-Type'); // Note: this null/undefined check is done outside because IE // dies otherwise on a "'null' is null" error if(ct) { if(ct.indexOf('text/xml') === 0 || ct.indexOf('application/xml') === 0 || ct.indexOf('+xml') !== -1) { try { var doc = new ActiveXObject('MicrosoftXMLDOM'); doc.async = false; doc.loadXML(e.response.body); xhr.responseXML = doc; } catch(ex) { var parser = new DOMParser(); xhr.responseXML = parser.parseFromString(ex.body, 'text/xml'); } } } var length = 0; if(e.response.body !== null) { xhr.responseText = e.response.body; length = e.response.body.length; } // build logging output var req = _state.request; var output = req.method + ' ' + req.path + ' ' + xhr.status + ' ' + xhr.statusText + ' ' + length + 'B ' + (e.request.connectTime + e.request.time + e.response.time) + 'ms'; var lFunc; if(options.verbose) { lFunc = (xhr.status >= 400 && options.logWarningOnError) ? _log.warning : _log.verbose; lFunc(cat, output, e, e.response.body ? '\n' + e.response.body : '\nNo content'); } else { lFunc = (xhr.status >= 400 && options.logWarningOnError) ? _log.warning : _log.debug; lFunc(cat, output); } if(xhr.onreadystatechange) { xhr.onreadystatechange(); } }; options.error = function(e) { var req = _state.request; _log.error(cat, req.method + ' ' + req.path, e); // 1. set response body to null xhr.responseText = ''; xhr.responseXML = null; // 2. set error flag to true (and reset status) _state.errorFlag = true; xhr.status = 0; xhr.statusText = ''; // 3. set state to done xhr.readyState = DONE; // 4. asyc flag is always true, so dispatch onreadystatechange if(xhr.onreadystatechange) { xhr.onreadystatechange(); } }; // 7. send request _state.client.send(options); }; /** * Aborts the request. */ xhr.abort = function() { // 1. abort send // 2. stop network activity _state.request.abort(); // 3. set response to null xhr.responseText = ''; xhr.responseXML = null; // 4. set error flag to true (and reset status) _state.errorFlag = true; xhr.status = 0; xhr.statusText = ''; // 5. clear user headers _state.request = null; _state.response = null; // 6. if state is DONE or UNSENT, or if OPENED and send flag is false if(xhr.readyState === DONE || xhr.readyState === UNSENT || (xhr.readyState === OPENED && !_state.sendFlag)) { // 7. set ready state to unsent xhr.readyState = UNSENT; } else { // 6.1 set state to DONE xhr.readyState = DONE; // 6.2 set send flag to false _state.sendFlag = false; // 6.3 dispatch onreadystatechange if(xhr.onreadystatechange) { xhr.onreadystatechange(); } // 7. set state to UNSENT xhr.readyState = UNSENT; } }; /** * Gets all response headers as a string. * * @return the HTTP-encoded response header fields. */ xhr.getAllResponseHeaders = function() { var rval = ''; if(_state.response !== null) { var fields = _state.response.fields; $.each(fields, function(name, array) { $.each(array, function(i, value) { rval += name + ': ' + value + '\r\n'; }); }); } return rval; }; /** * Gets a single header field value or, if there are multiple * fields with the same name, a comma-separated list of header * values. * * @return the header field value(s) or null. */ xhr.getResponseHeader = function(header) { var rval = null; if(_state.response !== null) { if(header in _state.response.fields) { rval = _state.response.fields[header]; if(forge.util.isArray(rval)) { rval = rval.join(); } } } return rval; }; return xhr; }; })(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/pbkdf2.js
aws/lti-middleware/node_modules/node-forge/lib/pbkdf2.js
/** * Password-Based Key-Derivation Function #2 implementation. * * See RFC 2898 for details. * * @author Dave Longley * * Copyright (c) 2010-2013 Digital Bazaar, Inc. */ var forge = require('./forge'); require('./hmac'); require('./md'); require('./util'); var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; var crypto; if(forge.util.isNodejs && !forge.options.usePureJavaScript) { crypto = require('crypto'); } /** * Derives a key from a password. * * @param p the password as a binary-encoded string of bytes. * @param s the salt as a binary-encoded string of bytes. * @param c the iteration count, a positive integer. * @param dkLen the intended length, in bytes, of the derived key, * (max: 2^32 - 1) * hash length of the PRF. * @param [md] the message digest (or algorithm identifier as a string) to use * in the PRF, defaults to SHA-1. * @param [callback(err, key)] presence triggers asynchronous version, called * once the operation completes. * * @return the derived key, as a binary-encoded string of bytes, for the * synchronous version (if no callback is specified). */ module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( p, s, c, dkLen, md, callback) { if(typeof md === 'function') { callback = md; md = null; } // use native implementation if possible and not disabled, note that // some node versions only support SHA-1, others allow digest to be changed if(forge.util.isNodejs && !forge.options.usePureJavaScript && crypto.pbkdf2 && (md === null || typeof md !== 'object') && (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { if(typeof md !== 'string') { // default prf to SHA-1 md = 'sha1'; } p = Buffer.from(p, 'binary'); s = Buffer.from(s, 'binary'); if(!callback) { if(crypto.pbkdf2Sync.length === 4) { return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); } return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); } if(crypto.pbkdf2Sync.length === 4) { return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { if(err) { return callback(err); } callback(null, key.toString('binary')); }); } return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { if(err) { return callback(err); } callback(null, key.toString('binary')); }); } if(typeof md === 'undefined' || md === null) { // default prf to SHA-1 md = 'sha1'; } if(typeof md === 'string') { if(!(md in forge.md.algorithms)) { throw new Error('Unknown hash algorithm: ' + md); } md = forge.md[md].create(); } var hLen = md.digestLength; /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and stop. */ if(dkLen > (0xFFFFFFFF * hLen)) { var err = new Error('Derived key is too long.'); if(callback) { return callback(err); } throw err; } /* 2. Let len be the number of hLen-octet blocks in the derived key, rounding up, and let r be the number of octets in the last block: len = CEIL(dkLen / hLen), r = dkLen - (len - 1) * hLen. */ var len = Math.ceil(dkLen / hLen); var r = dkLen - (len - 1) * hLen; /* 3. For each block of the derived key apply the function F defined below to the password P, the salt S, the iteration count c, and the block index to compute the block: T_1 = F(P, S, c, 1), T_2 = F(P, S, c, 2), ... T_len = F(P, S, c, len), where the function F is defined as the exclusive-or sum of the first c iterates of the underlying pseudorandom function PRF applied to the password P and the concatenation of the salt S and the block index i: F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c where u_1 = PRF(P, S || INT(i)), u_2 = PRF(P, u_1), ... u_c = PRF(P, u_{c-1}). Here, INT(i) is a four-octet encoding of the integer i, most significant octet first. */ var prf = forge.hmac.create(); prf.start(md, p); var dk = ''; var xor, u_c, u_c1; // sync version if(!callback) { for(var i = 1; i <= len; ++i) { // PRF(P, S || INT(i)) (first iteration) prf.start(null, null); prf.update(s); prf.update(forge.util.int32ToBytes(i)); xor = u_c1 = prf.digest().getBytes(); // PRF(P, u_{c-1}) (other iterations) for(var j = 2; j <= c; ++j) { prf.start(null, null); prf.update(u_c1); u_c = prf.digest().getBytes(); // F(p, s, c, i) xor = forge.util.xorBytes(xor, u_c, hLen); u_c1 = u_c; } /* 4. Concatenate the blocks and extract the first dkLen octets to produce a derived key DK: DK = T_1 || T_2 || ... || T_len<0..r-1> */ dk += (i < len) ? xor : xor.substr(0, r); } /* 5. Output the derived key DK. */ return dk; } // async version var i = 1, j; function outer() { if(i > len) { // done return callback(null, dk); } // PRF(P, S || INT(i)) (first iteration) prf.start(null, null); prf.update(s); prf.update(forge.util.int32ToBytes(i)); xor = u_c1 = prf.digest().getBytes(); // PRF(P, u_{c-1}) (other iterations) j = 2; inner(); } function inner() { if(j <= c) { prf.start(null, null); prf.update(u_c1); u_c = prf.digest().getBytes(); // F(p, s, c, i) xor = forge.util.xorBytes(xor, u_c, hLen); u_c1 = u_c; ++j; return forge.util.setImmediate(inner); } /* 4. Concatenate the blocks and extract the first dkLen octets to produce a derived key DK: DK = T_1 || T_2 || ... || T_len<0..r-1> */ dk += (i < len) ? xor : xor.substr(0, r); ++i; outer(); } outer(); };
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/dist/forge.all.min.js
aws/lti-middleware/node_modules/node-forge/dist/forge.all.min.js
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.forge=t():e.forge=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var a=t[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)r.d(n,a,function(t){return e[t]}.bind(null,a));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=34)}([function(e,t){e.exports={options:{usePureJavaScript:!1}}},function(e,t,r){(function(t){var n=r(0),a=r(38),i=e.exports=n.util=n.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function o(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r<t.length;++r)this.putByte(t[r])}}else(e instanceof o||"object"==typeof e&&"string"==typeof e.data&&"number"==typeof e.read)&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}!function(){if("undefined"!=typeof process&&process.nextTick&&!process.browser)return i.nextTick=process.nextTick,void("function"==typeof setImmediate?i.setImmediate=setImmediate:i.setImmediate=i.nextTick);if("function"==typeof setImmediate)return i.setImmediate=function(){return setImmediate.apply(void 0,arguments)},void(i.nextTick=function(e){return setImmediate(e)});if(i.setImmediate=function(e){setTimeout(e,0)},"undefined"!=typeof window&&"function"==typeof window.postMessage){var e="forge.setImmediate",t=[];i.setImmediate=function(r){t.push(r),1===t.length&&window.postMessage(e,"*")},window.addEventListener("message",(function(r){if(r.source===window&&r.data===e){r.stopPropagation();var n=t.slice();t.length=0,n.forEach((function(e){e()}))}}),!0)}if("undefined"!=typeof MutationObserver){var r=Date.now(),n=!0,a=document.createElement("div");t=[];new MutationObserver((function(){var e=t.slice();t.length=0,e.forEach((function(e){e()}))})).observe(a,{attributes:!0});var s=i.setImmediate;i.setImmediate=function(e){Date.now()-r>15?(r=Date.now(),s(e)):(t.push(e),1===t.length&&a.setAttribute("a",n=!n))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?t:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=o,i.ByteStringBuffer=o;i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},i.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)},i.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())},i.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},i.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e},i.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e},i.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},i.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e},i.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e},i.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e},i.ByteStringBuffer.prototype.getInt=function(e){s(e);var t=0;do{t=(t<<8)+this.data.charCodeAt(this.read++),e-=8}while(e>0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},i.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var r=this.data.charCodeAt(t);r<16&&(e+="0"),e+=r.toString(16)}return e},i.ByteStringBuffer.prototype.toString=function(){return i.decodeUtf8(this.bytes())},i.DataBuffer=function(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var r=i.isArrayBuffer(e),n=i.isArrayBufferView(e);if(r||n)return this.data=r?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),void(this.write="writeOffset"in t?t.writeOffset:this.data.byteLength);this.data=new DataView(new ArrayBuffer(0)),this.write=0,null!=e&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)},i.DataBuffer.prototype.length=function(){return this.write-this.read},i.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},i.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r<t;++r)this.data.setUint8(e);return this},i.DataBuffer.prototype.putBytes=function(e,t){if(i.isArrayBufferView(e)){var r=(n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).byteLength-n.byteOffset;return this.accommodate(r),new Uint8Array(this.data.buffer,this.write).set(n),this.write+=r,this}if(i.isArrayBuffer(e)){var n=new Uint8Array(e);return this.accommodate(n.byteLength),new Uint8Array(this.data.buffer).set(n,this.write),this.write+=n.byteLength,this}if(e instanceof i.DataBuffer||"object"==typeof e&&"number"==typeof e.read&&"number"==typeof e.write&&i.isArrayBufferView(e.data)){n=new Uint8Array(e.data.byteLength,e.read,e.length());return this.accommodate(n.byteLength),new Uint8Array(e.data.byteLength,this.write).set(n),this.write+=n.byteLength,this}if(e instanceof i.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary","string"==typeof e){var a;if("hex"===t)return this.accommodate(Math.ceil(e.length/2)),a=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.hex.decode(e,a,this.write),this;if("base64"===t)return this.accommodate(3*Math.ceil(e.length/4)),a=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.base64.decode(e,a,this.write),this;if("utf8"===t&&(e=i.encodeUtf8(e),t="binary"),"binary"===t||"raw"===t)return this.accommodate(e.length),a=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.raw.decode(a),this;if("utf16"===t)return this.accommodate(2*e.length),a=new Uint16Array(this.data.buffer,this.write),this.write+=i.text.utf16.encode(a),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)},i.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this},i.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")},i.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this},i.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)},i.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},i.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e},i.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e},i.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e},i.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e},i.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e},i.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e},i.DataBuffer.prototype.getInt=function(e){s(e);var t=0;do{t=(t<<8)+this.data.getInt8(this.read++),e-=8}while(e>0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},i.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var r=this.data.getUint8(t);r<16&&(e+="0"),e+=r.toString(16)}return e},i.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if("binary"===(e=e||"utf8")||"raw"===e)return i.binary.raw.encode(t);if("hex"===e)return i.binary.hex.encode(t);if("base64"===e)return i.binary.base64.encode(t);if("utf8"===e)return i.text.utf8.decode(t);if("utf16"===e)return i.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)},i.createBuffer=function(e,t){return t=t||"raw",void 0!==e&&"utf8"===t&&(e=i.encodeUtf8(e)),new i.ByteBuffer(e)},i.fillString=function(e,t){for(var r="";t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var n="",a="",i="",s=0,o=0;r>0;--r,++s)a=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(n+=i,i="",o=0),i+=String.fromCharCode(a),++o;return n+=i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r<e.length;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t},i.bytesToHex=function(e){return i.createBuffer(e).toHex()},i.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,n,a,i="",s="",o=0;o<e.length;)r=e.charCodeAt(o++),n=e.charCodeAt(o++),a=e.charCodeAt(o++),i+=c.charAt(r>>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|a>>6),i+=isNaN(a)?"=":c.charAt(63&a)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,a,i="",s=0;s<e.length;)t=u[e.charCodeAt(s++)-43],r=u[e.charCodeAt(s++)-43],n=u[e.charCodeAt(s++)-43],a=u[e.charCodeAt(s++)-43],i+=String.fromCharCode(t<<2|r>>4),64!==n&&(i+=String.fromCharCode((15&r)<<4|n>>2),64!==a&&(i+=String.fromCharCode((3&n)<<6|a)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:a.encode,decode:a.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var a=r=r||0,i=0;i<e.length;++i)n[a++]=e.charCodeAt(i);return t?a-r:n},i.binary.hex.encode=i.bytesToHex,i.binary.hex.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(Math.ceil(e.length/2)));var a=0,i=r=r||0;for(1&e.length&&(a=1,n[i++]=parseInt(e[0],16));a<e.length;a+=2)n[i++]=parseInt(e.substr(a,2),16);return t?i-r:n},i.binary.base64.encode=function(e,t){for(var r,n,a,i="",s="",o=0;o<e.byteLength;)r=e[o++],n=e[o++],a=e[o++],i+=c.charAt(r>>2),i+=c.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=c.charAt((15&n)<<2|a>>6),i+=isNaN(a)?"=":c.charAt(63&a)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.binary.base64.decode=function(e,t,r){var n,a,i,s,o=t;o||(o=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,l=r=r||0;c<e.length;)n=u[e.charCodeAt(c++)-43],a=u[e.charCodeAt(c++)-43],i=u[e.charCodeAt(c++)-43],s=u[e.charCodeAt(c++)-43],o[l++]=n<<2|a>>4,64!==i&&(o[l++]=(15&a)<<4|i>>2,64!==s&&(o[l++]=(3&i)<<6|s));return t?l-r:o.subarray(0,l)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,l,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,l,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var a=r=r||0,s=0;s<e.length;++s)n[a++]=e.charCodeAt(s);return t?a-r:n},i.text.utf8.decode=function(e){return i.decodeUtf8(String.fromCharCode.apply(null,e))},i.text.utf16.encode=function(e,t,r){var n=t;n||(n=new Uint8Array(2*e.length));for(var a=new Uint16Array(n.buffer),i=r=r||0,s=r,o=0;o<e.length;++o)a[s++]=e.charCodeAt(o),i+=2;return t?i-r:n},i.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))},i.deflate=function(e,t,r){if(t=i.decode64(e.deflate(i.encode64(t)).rval),r){var n=2;32&t.charCodeAt(1)&&(n=6),t=t.substring(n,t.length-4)}return t},i.inflate=function(e,t,r){var n=e.inflate(i.encode64(t)).rval;return null===n?null:i.decode64(n)};var p=function(e,t,r){if(!e)throw new Error("WebStorage not available.");var n;if(null===r?n=e.removeItem(t):(r=i.encode64(JSON.stringify(r)),n=e.setItem(t,r)),void 0!==n&&!0!==n.rval){var a=new Error(n.error.message);throw a.id=n.error.id,a.name=n.error.name,a}},f=function(e,t){if(!e)throw new Error("WebStorage not available.");var r=e.getItem(t);if(e.init)if(null===r.rval){if(r.error){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}r=null}else r=r.rval;return null!==r&&(r=JSON.parse(i.decode64(r))),r},h=function(e,t,r,n){var a=f(e,t);null===a&&(a={}),a[r]=n,p(e,t,a)},d=function(e,t,r){var n=f(e,t);return null!==n&&(n=r in n?n[r]:null),n},y=function(e,t,r){var n=f(e,t);if(null!==n&&r in n){delete n[r];var a=!0;for(var i in n){a=!1;break}a&&(n=null),p(e,t,n)}},g=function(e,t){p(e,t,null)},v=function(e,t,r){var n,a=null;void 0===r&&(r=["web","flash"]);var i=!1,s=null;for(var o in r){n=r[o];try{if("flash"===n||"both"===n){if(null===t[0])throw new Error("Flash local storage not available.");a=e.apply(this,t),i="flash"===n}"web"!==n&&"both"!==n||(t[0]=localStorage,a=e.apply(this,t),i=!0)}catch(e){s=e}if(i)break}if(!i)throw s;return a};i.setItem=function(e,t,r,n,a){v(h,arguments,a)},i.getItem=function(e,t,r,n){return v(d,arguments,n)},i.removeItem=function(e,t,r,n){v(y,arguments,n)},i.clearItems=function(e,t,r){v(g,arguments,r)},i.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},i.format=function(e){for(var t,r,n=/%./g,a=0,i=[],s=0;t=n.exec(e);){(r=e.substring(s,n.lastIndex-2)).length>0&&i.push(r),s=n.lastIndex;var o=t[0][1];switch(o){case"s":case"o":a<arguments.length?i.push(arguments[1+a++]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")},i.formatNumber=function(e,t,r,n){var a=e,i=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,o=void 0===n?".":n,c=a<0?"-":"",u=parseInt(a=Math.abs(+a||0).toFixed(i),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+o:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(a-u).toFixed(i).slice(2):"")},i.formatSize=function(e){return e=e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;r<e.length;++r){var n=parseInt(e[r],10);if(isNaN(n))return null;t.putByte(n)}return t.getBytes()},i.bytesFromIPv6=function(e){for(var t=0,r=2*(8-(e=e.split(":").filter((function(e){return 0===e.length&&++t,!0}))).length+t),n=i.createBuffer(),a=0;a<8;++a)if(e[a]&&0!==e[a].length){var s=i.hexToBytes(e[a]);s.length<2&&n.putByte(0),n.putBytes(s)}else n.fillWithByte(0,r),r=0;return n.getBytes()},i.bytesToIP=function(e){return 4===e.length?i.bytesToIPv4(e):16===e.length?i.bytesToIPv6(e):null},i.bytesToIPv4=function(e){if(4!==e.length)return null;for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t.join(".")},i.bytesToIPv6=function(e){if(16!==e.length)return null;for(var t=[],r=[],n=0,a=0;a<e.length;a+=2){for(var s=i.bytesToHex(e[a]+e[a+1]);"0"===s[0]&&"0"!==s;)s=s.substr(1);if("0"===s){var o=r[r.length-1],c=t.length;o&&c===o.end+1?(o.end=c,o.end-o.start>r[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(s)}if(r.length>0){var u=r[n];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()<r;);self.postMessage({st:t,et:r})}))}.toString(),")()"],{type:"application/javascript"}));!function e(n,a,s){if(0===a){var o=Math.floor(n.reduce((function(e,t){return e+t}),0)/n.length);return i.cores=Math.max(1,o),URL.revokeObjectURL(r),t(null,i.cores)}!function(e,t){for(var n=[],a=[],i=0;i<e;++i){var s=new Worker(r);s.addEventListener("message",(function(r){if(a.push(r.data),a.length===e){for(var i=0;i<e;++i)n[i].terminate();t(null,a)}})),n.push(s)}for(i=0;i<e;++i)n[i].postMessage(i)}(s,(function(t,r){n.push(function(e,t){for(var r=[],n=0;n<e;++n)for(var a=t[n],i=r[n]=[],s=0;s<e;++s)if(n!==s){var o=t[s];(a.st>o.st&&a.st<o.et||o.st>a.st&&o.st<a.et)&&i.push(s)}return r.reduce((function(e,t){return Math.max(e,t.length)}),0)}(s,r)),e(n,a-1,s)}))}([],5,16)}}).call(this,r(37))},function(e,t,r){var n=r(0);r(5),r(23),r(24),r(1),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},a=new Array(4),i=n.util.createBuffer();function s(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,a,!1),i.putInt32(a[0]),i.putInt32(a[1]),i.putInt32(a[2]),i.putInt32(a[3]),i.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var o=s(),c=null,u=n.util.globalScope,l=u.crypto||u.msCrypto;if(l&&l.getRandomValues&&(c=function(e){return l.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"==typeof window||window.document,o.collectInt(+new Date,32),"undefined"!=typeof navigator){var p="";for(var f in navigator)try{"string"==typeof navigator[f]&&(p+=navigator[f])}catch(e){}o.collect(p),p=null}t&&(t().mousemove((function(e){o.collectInt(e.clientX,16),o.collectInt(e.clientY,16)})),t().keypress((function(e){o.collectInt(e.charCode,8)})))}if(n.random)for(var f in o)n.random[f]=o[f];else n.random=o;n.random.createInstance=s,e.exports=n.random}("undefined"!=typeof jQuery?jQuery:null)},function(e,t,r){var n=r(0);r(1),r(6);var a=e.exports=n.asn1=n.asn1||{};function i(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}a.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},a.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},a.create=function(e,t,r,i,s){if(n.util.isArray(i)){for(var o=[],c=0;c<i.length;++c)void 0!==i[c]&&o.push(i[c]);i=o}var u={tagClass:e,type:t,constructed:r,composed:r||n.util.isArray(i),value:i};return s&&"bitStringContents"in s&&(u.bitStringContents=s.bitStringContents,u.original=a.copy(u)),u},a.copy=function(e,t){var r;if(n.util.isArray(e)){r=[];for(var i=0;i<e.length;++i)r.push(a.copy(e[i],t));return r}return"string"==typeof e?e:(r={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:a.copy(e.value,t)},t&&!t.excludeBitStringContents&&(r.bitStringContents=e.bitStringContents),r)},a.equals=function(e,t,r){if(n.util.isArray(e)){if(!n.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(!a.equals(e[i],t[i]))return!1;return!0}if(typeof e!=typeof t)return!1;if("string"==typeof e)return e===t;var s=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&a.equals(e.value,t.value);return r&&r.includeBitStringContents&&(s=s&&e.bitStringContents===t.bitStringContents),s},a.getBerValueLength=function(e){var t=e.getByte();if(128!==t)return 128&t?e.getInt((127&t)<<3):t};a.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"==typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.length(),s=function e(t,r,n,s){var o;i(t,r,2);var c=t.getByte();r--;var u=192&c,l=31&c;o=t.length();var p,f,h=function(e,t){var r=e.getByte();if(t--,128!==r){var n;if(128&r){var a=127&r;i(e,t,a),n=e.getInt(a<<3)}else n=r;if(n<0)throw new Error("Negative length: "+n);return n}}(t,r);if(r-=o-t.length(),void 0!==h&&h>r){if(s.strict){var d=new Error("Too few bytes to read ASN.1 value.");throw d.available=t.length(),d.remaining=r,d.requested=h,d}h=r}var y=32==(32&c);if(y)if(p=[],void 0===h)for(;;){if(i(t,r,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),r-=2;break}o=t.length(),p.push(e(t,r,n+1,s)),r-=o-t.length()}else for(;h>0;)o=t.length(),p.push(e(t,h,n+1,s)),r-=o-t.length(),h-=o-t.length();void 0===p&&u===a.Class.UNIVERSAL&&l===a.Type.BITSTRING&&(f=t.bytes(h));if(void 0===p&&s.decodeBitStrings&&u===a.Class.UNIVERSAL&&l===a.Type.BITSTRING&&h>1){var g=t.read,v=r,m=0;if(l===a.Type.BITSTRING&&(i(t,r,1),m=t.getByte(),r--),0===m)try{o=t.length();var C=e(t,r,n+1,{strict:!0,decodeBitStrings:!0}),E=o-t.length();r-=E,l==a.Type.BITSTRING&&E++;var S=C.tagClass;E!==h||S!==a.Class.UNIVERSAL&&S!==a.Class.CONTEXT_SPECIFIC||(p=[C])}catch(e){}void 0===p&&(t.read=g,r=v)}if(void 0===p){if(void 0===h){if(s.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");h=r}if(l===a.Type.BMPSTRING)for(p="";h>0;h-=2)i(t,r,2),p+=String.fromCharCode(t.getInt16()),r-=2;else p=t.getBytes(h),r-=h}var T=void 0===f?null:{bitStringContents:f};return a.create(u,l,y,p,T)}(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return s},a.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,i=n.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=a.equals(e,e.original))),s)i.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:i.putByte(0);for(var o=0;o<e.value.length;++o)void 0!==e.value[o]&&i.putBuffer(a.toDer(e.value[o]))}else if(e.type===a.Type.BMPSTRING)for(o=0;o<e.value.length;++o)i.putInt16(e.value.charCodeAt(o));else e.type===a.Type.INTEGER&&e.value.length>1&&(0===e.value.charCodeAt(0)&&0==(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128==(128&e.value.charCodeAt(1)))?i.putBytes(e.value.substr(1)):i.putBytes(e.value);if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(o=u.length-1;o>=0;--o)t.putByte(u.charCodeAt(o))}return t.putBuffer(i),t},a.oidToDer=function(e){var t,r,a,i,s=e.split("."),o=n.util.createBuffer();o.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var c=2;c<s.length;++c){t=!0,r=[],a=parseInt(s[c],10);do{i=127&a,a>>>=7,t||(i|=128),r.push(i),t=!1}while(a>0);for(var u=r.length-1;u>=0;--u)o.putByte(r[u])}return o},a.derToOid=function(e){var t;"string"==typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var a=0;e.length()>0;)a<<=7,128&(r=e.getByte())?a+=127&r:(t+="."+(a+r),a=0);return t},a.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,a=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(o=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,n,a),t.setUTCHours(i,s,o,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=60*parseInt(e.substr(u+1,2),10)+parseInt(e.substr(u+4,2),10);l*=6e4,"+"===c?t.setTime(+t-l):t.setTime(+t+l)}return t},a.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,a=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var p=e.length-5,f=e.charAt(p);"+"!==f&&"-"!==f||(u=60*parseInt(e.substr(p+1,2),10)+parseInt(e.substr(p+4,2),10),u*=6e4,"+"===f&&(u*=-1),l=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,n,a),t.setUTCHours(i,s,o,c),t.setTime(+t+u)):(t.setFullYear(r,n,a),t.setHours(i,s,o,c)),t},a.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+="Z"},a.dateToGeneralizedTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push(""+e.getUTCFullYear()),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n<r.length;++n)r[n].length<2&&(t+="0"),t+=r[n];return t+="Z"},a.integerToDer=function(e){var t=n.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putS
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/dist/forge.min.js
aws/lti-middleware/node_modules/node-forge/dist/forge.min.js
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.forge=t():e.forge=t()}(window,(function(){return function(e){var t={};function r(a){if(t[a])return t[a].exports;var n=t[a]={i:a,l:!1,exports:{}};return e[a].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,a){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(r.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(a,n,function(t){return e[t]}.bind(null,n));return a},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=32)}([function(e,t){e.exports={options:{usePureJavaScript:!1}}},function(e,t,r){(function(t){var a=r(0),n=r(35),i=e.exports=a.util=a.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function o(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(i.isArrayBuffer(e)||i.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r<t.length;++r)this.putByte(t[r])}}else(e instanceof o||"object"==typeof e&&"string"==typeof e.data&&"number"==typeof e.read)&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}!function(){if("undefined"!=typeof process&&process.nextTick&&!process.browser)return i.nextTick=process.nextTick,void("function"==typeof setImmediate?i.setImmediate=setImmediate:i.setImmediate=i.nextTick);if("function"==typeof setImmediate)return i.setImmediate=function(){return setImmediate.apply(void 0,arguments)},void(i.nextTick=function(e){return setImmediate(e)});if(i.setImmediate=function(e){setTimeout(e,0)},"undefined"!=typeof window&&"function"==typeof window.postMessage){var e="forge.setImmediate",t=[];i.setImmediate=function(r){t.push(r),1===t.length&&window.postMessage(e,"*")},window.addEventListener("message",(function(r){if(r.source===window&&r.data===e){r.stopPropagation();var a=t.slice();t.length=0,a.forEach((function(e){e()}))}}),!0)}if("undefined"!=typeof MutationObserver){var r=Date.now(),a=!0,n=document.createElement("div");t=[];new MutationObserver((function(){var e=t.slice();t.length=0,e.forEach((function(e){e()}))})).observe(n,{attributes:!0});var s=i.setImmediate;i.setImmediate=function(e){Date.now()-r>15?(r=Date.now(),s(e)):(t.push(e),1===t.length&&n.setAttribute("a",a=!a))}}i.nextTick=i.setImmediate}(),i.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,i.globalScope=i.isNodejs?t:"undefined"==typeof self?window:self,i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},i.isArrayBufferView=function(e){return e&&i.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},i.ByteBuffer=o,i.ByteStringBuffer=o;i.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},i.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},i.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},i.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(i.encodeUtf8(e))},i.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},i.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},i.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},i.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},i.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)},i.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())},i.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},i.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e},i.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e},i.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},i.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e},i.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e},i.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e},i.ByteStringBuffer.prototype.getInt=function(e){s(e);var t=0;do{t=(t<<8)+this.data.charCodeAt(this.read++),e-=8}while(e>0);return t},i.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},i.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},i.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var e=i.createBuffer(this.data);return e.read=this.read,e},i.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},i.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var r=this.data.charCodeAt(t);r<16&&(e+="0"),e+=r.toString(16)}return e},i.ByteStringBuffer.prototype.toString=function(){return i.decodeUtf8(this.bytes())},i.DataBuffer=function(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var r=i.isArrayBuffer(e),a=i.isArrayBufferView(e);if(r||a)return this.data=r?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),void(this.write="writeOffset"in t?t.writeOffset:this.data.byteLength);this.data=new DataView(new ArrayBuffer(0)),this.write=0,null!=e&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)},i.DataBuffer.prototype.length=function(){return this.write-this.read},i.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},i.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),a=new Uint8Array(this.length()+t);return a.set(r),this.data=new DataView(a.buffer),this},i.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},i.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r<t;++r)this.data.setUint8(e);return this},i.DataBuffer.prototype.putBytes=function(e,t){if(i.isArrayBufferView(e)){var r=(a=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).byteLength-a.byteOffset;return this.accommodate(r),new Uint8Array(this.data.buffer,this.write).set(a),this.write+=r,this}if(i.isArrayBuffer(e)){var a=new Uint8Array(e);return this.accommodate(a.byteLength),new Uint8Array(this.data.buffer).set(a,this.write),this.write+=a.byteLength,this}if(e instanceof i.DataBuffer||"object"==typeof e&&"number"==typeof e.read&&"number"==typeof e.write&&i.isArrayBufferView(e.data)){a=new Uint8Array(e.data.byteLength,e.read,e.length());return this.accommodate(a.byteLength),new Uint8Array(e.data.byteLength,this.write).set(a),this.write+=a.byteLength,this}if(e instanceof i.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary","string"==typeof e){var n;if("hex"===t)return this.accommodate(Math.ceil(e.length/2)),n=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.hex.decode(e,n,this.write),this;if("base64"===t)return this.accommodate(3*Math.ceil(e.length/4)),n=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.base64.decode(e,n,this.write),this;if("utf8"===t&&(e=i.encodeUtf8(e),t="binary"),"binary"===t||"raw"===t)return this.accommodate(e.length),n=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.raw.decode(n),this;if("utf16"===t)return this.accommodate(2*e.length),n=new Uint16Array(this.data.buffer,this.write),this.write+=i.text.utf16.encode(n),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)},i.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this},i.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")},i.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this},i.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},i.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},i.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},i.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)},i.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},i.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e},i.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e},i.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e},i.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e},i.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e},i.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e},i.DataBuffer.prototype.getInt=function(e){s(e);var t=0;do{t=(t<<8)+this.data.getInt8(this.read++),e-=8}while(e>0);return t},i.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<<e-2;return t>=r&&(t-=r<<1),t},i.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},i.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},i.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},i.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var r=this.data.getUint8(t);r<16&&(e+="0"),e+=r.toString(16)}return e},i.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if("binary"===(e=e||"utf8")||"raw"===e)return i.binary.raw.encode(t);if("hex"===e)return i.binary.hex.encode(t);if("base64"===e)return i.binary.base64.encode(t);if("utf8"===e)return i.text.utf8.decode(t);if("utf16"===e)return i.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)},i.createBuffer=function(e,t){return t=t||"raw",void 0!==e&&"utf8"===t&&(e=i.encodeUtf8(e)),new i.ByteBuffer(e)},i.fillString=function(e,t){for(var r="";t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},i.xorBytes=function(e,t,r){for(var a="",n="",i="",s=0,o=0;r>0;--r,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(a+=i,i="",o=0),i+=String.fromCharCode(n),++o;return a+=i},i.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r<e.length;r+=2)t+=String.fromCharCode(parseInt(e.substr(r,2),16));return t},i.bytesToHex=function(e){return i.createBuffer(e).toHex()},i.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(e,t){for(var r,a,n,i="",s="",o=0;o<e.length;)r=e.charCodeAt(o++),a=e.charCodeAt(o++),n=e.charCodeAt(o++),i+=c.charAt(r>>2),i+=c.charAt((3&r)<<4|a>>4),isNaN(a)?i+="==":(i+=c.charAt((15&a)<<2|n>>6),i+=isNaN(n)?"=":c.charAt(63&n)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,a,n,i="",s=0;s<e.length;)t=u[e.charCodeAt(s++)-43],r=u[e.charCodeAt(s++)-43],a=u[e.charCodeAt(s++)-43],n=u[e.charCodeAt(s++)-43],i+=String.fromCharCode(t<<2|r>>4),64!==a&&(i+=String.fromCharCode((15&r)<<4|a>>2),64!==n&&(i+=String.fromCharCode((3&a)<<6|n)));return i},i.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},i.decodeUtf8=function(e){return decodeURIComponent(escape(e))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:n.encode,decode:n.decode}},i.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},i.binary.raw.decode=function(e,t,r){var a=t;a||(a=new Uint8Array(e.length));for(var n=r=r||0,i=0;i<e.length;++i)a[n++]=e.charCodeAt(i);return t?n-r:a},i.binary.hex.encode=i.bytesToHex,i.binary.hex.decode=function(e,t,r){var a=t;a||(a=new Uint8Array(Math.ceil(e.length/2)));var n=0,i=r=r||0;for(1&e.length&&(n=1,a[i++]=parseInt(e[0],16));n<e.length;n+=2)a[i++]=parseInt(e.substr(n,2),16);return t?i-r:a},i.binary.base64.encode=function(e,t){for(var r,a,n,i="",s="",o=0;o<e.byteLength;)r=e[o++],a=e[o++],n=e[o++],i+=c.charAt(r>>2),i+=c.charAt((3&r)<<4|a>>4),isNaN(a)?i+="==":(i+=c.charAt((15&a)<<2|n>>6),i+=isNaN(n)?"=":c.charAt(63&n)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},i.binary.base64.decode=function(e,t,r){var a,n,i,s,o=t;o||(o=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,l=r=r||0;c<e.length;)a=u[e.charCodeAt(c++)-43],n=u[e.charCodeAt(c++)-43],i=u[e.charCodeAt(c++)-43],s=u[e.charCodeAt(c++)-43],o[l++]=a<<2|n>>4,64!==i&&(o[l++]=(15&n)<<4|i>>2,64!==s&&(o[l++]=(3&i)<<6|s));return t?l-r:o.subarray(0,l)},i.binary.base58.encode=function(e,t){return i.binary.baseN.encode(e,l,t)},i.binary.base58.decode=function(e,t){return i.binary.baseN.decode(e,l,t)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(e,t,r){e=i.encodeUtf8(e);var a=t;a||(a=new Uint8Array(e.length));for(var n=r=r||0,s=0;s<e.length;++s)a[n++]=e.charCodeAt(s);return t?n-r:a},i.text.utf8.decode=function(e){return i.decodeUtf8(String.fromCharCode.apply(null,e))},i.text.utf16.encode=function(e,t,r){var a=t;a||(a=new Uint8Array(2*e.length));for(var n=new Uint16Array(a.buffer),i=r=r||0,s=r,o=0;o<e.length;++o)n[s++]=e.charCodeAt(o),i+=2;return t?i-r:a},i.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))},i.deflate=function(e,t,r){if(t=i.decode64(e.deflate(i.encode64(t)).rval),r){var a=2;32&t.charCodeAt(1)&&(a=6),t=t.substring(a,t.length-4)}return t},i.inflate=function(e,t,r){var a=e.inflate(i.encode64(t)).rval;return null===a?null:i.decode64(a)};var p=function(e,t,r){if(!e)throw new Error("WebStorage not available.");var a;if(null===r?a=e.removeItem(t):(r=i.encode64(JSON.stringify(r)),a=e.setItem(t,r)),void 0!==a&&!0!==a.rval){var n=new Error(a.error.message);throw n.id=a.error.id,n.name=a.error.name,n}},f=function(e,t){if(!e)throw new Error("WebStorage not available.");var r=e.getItem(t);if(e.init)if(null===r.rval){if(r.error){var a=new Error(r.error.message);throw a.id=r.error.id,a.name=r.error.name,a}r=null}else r=r.rval;return null!==r&&(r=JSON.parse(i.decode64(r))),r},h=function(e,t,r,a){var n=f(e,t);null===n&&(n={}),n[r]=a,p(e,t,n)},d=function(e,t,r){var a=f(e,t);return null!==a&&(a=r in a?a[r]:null),a},y=function(e,t,r){var a=f(e,t);if(null!==a&&r in a){delete a[r];var n=!0;for(var i in a){n=!1;break}n&&(a=null),p(e,t,a)}},g=function(e,t){p(e,t,null)},v=function(e,t,r){var a,n=null;void 0===r&&(r=["web","flash"]);var i=!1,s=null;for(var o in r){a=r[o];try{if("flash"===a||"both"===a){if(null===t[0])throw new Error("Flash local storage not available.");n=e.apply(this,t),i="flash"===a}"web"!==a&&"both"!==a||(t[0]=localStorage,n=e.apply(this,t),i=!0)}catch(e){s=e}if(i)break}if(!i)throw s;return n};i.setItem=function(e,t,r,a,n){v(h,arguments,n)},i.getItem=function(e,t,r,a){return v(d,arguments,a)},i.removeItem=function(e,t,r,a){v(y,arguments,a)},i.clearItems=function(e,t,r){v(g,arguments,r)},i.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},i.format=function(e){for(var t,r,a=/%./g,n=0,i=[],s=0;t=a.exec(e);){(r=e.substring(s,a.lastIndex-2)).length>0&&i.push(r),s=a.lastIndex;var o=t[0][1];switch(o){case"s":case"o":n<arguments.length?i.push(arguments[1+n++]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")},i.formatNumber=function(e,t,r,a){var n=e,i=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,o=void 0===a?".":a,c=n<0?"-":"",u=parseInt(n=Math.abs(+n||0).toFixed(i),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+o:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(n-u).toFixed(i).slice(2):"")},i.formatSize=function(e){return e=e>=1073741824?i.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?i.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?i.formatNumber(e/1024,0)+" KiB":i.formatNumber(e,0)+" bytes"},i.bytesFromIP=function(e){return-1!==e.indexOf(".")?i.bytesFromIPv4(e):-1!==e.indexOf(":")?i.bytesFromIPv6(e):null},i.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=i.createBuffer(),r=0;r<e.length;++r){var a=parseInt(e[r],10);if(isNaN(a))return null;t.putByte(a)}return t.getBytes()},i.bytesFromIPv6=function(e){for(var t=0,r=2*(8-(e=e.split(":").filter((function(e){return 0===e.length&&++t,!0}))).length+t),a=i.createBuffer(),n=0;n<8;++n)if(e[n]&&0!==e[n].length){var s=i.hexToBytes(e[n]);s.length<2&&a.putByte(0),a.putBytes(s)}else a.fillWithByte(0,r),r=0;return a.getBytes()},i.bytesToIP=function(e){return 4===e.length?i.bytesToIPv4(e):16===e.length?i.bytesToIPv6(e):null},i.bytesToIPv4=function(e){if(4!==e.length)return null;for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t.join(".")},i.bytesToIPv6=function(e){if(16!==e.length)return null;for(var t=[],r=[],a=0,n=0;n<e.length;n+=2){for(var s=i.bytesToHex(e[n]+e[n+1]);"0"===s[0]&&"0"!==s;)s=s.substr(1);if("0"===s){var o=r[r.length-1],c=t.length;o&&c===o.end+1?(o.end=c,o.end-o.start>r[a].end-r[a].start&&(a=r.length-1)):r.push({start:c,end:c})}t.push(s)}if(r.length>0){var u=r[a];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},i.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in i&&!e.update)return t(null,i.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,t(null,i.cores);if("undefined"==typeof Worker)return i.cores=1,t(null,i.cores);if("undefined"==typeof Blob)return i.cores=2,t(null,i.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()<r;);self.postMessage({st:t,et:r})}))}.toString(),")()"],{type:"application/javascript"}));!function e(a,n,s){if(0===n){var o=Math.floor(a.reduce((function(e,t){return e+t}),0)/a.length);return i.cores=Math.max(1,o),URL.revokeObjectURL(r),t(null,i.cores)}!function(e,t){for(var a=[],n=[],i=0;i<e;++i){var s=new Worker(r);s.addEventListener("message",(function(r){if(n.push(r.data),n.length===e){for(var i=0;i<e;++i)a[i].terminate();t(null,n)}})),a.push(s)}for(i=0;i<e;++i)a[i].postMessage(i)}(s,(function(t,r){a.push(function(e,t){for(var r=[],a=0;a<e;++a)for(var n=t[a],i=r[a]=[],s=0;s<e;++s)if(a!==s){var o=t[s];(n.st>o.st&&n.st<o.et||o.st>n.st&&o.st<n.et)&&i.push(s)}return r.reduce((function(e,t){return Math.max(e,t.length)}),0)}(s,r)),e(a,n-1,s)}))}([],5,16)}}).call(this,r(34))},function(e,t,r){var a=r(0);r(5),r(23),r(24),r(1),a.random&&a.random.getBytes?e.exports=a.random:function(t){var r={},n=new Array(4),i=a.util.createBuffer();function s(){var e=a.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=a.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),a.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=a.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return a.aes._updateBlock(e,t,n,!1),i.putInt32(n[0]),i.putInt32(n[1]),i.putInt32(n[2]),i.putInt32(n[3]),i.getBytes()},r.increment=function(e){return++e[3],e},r.md=a.md.sha256;var o=s(),c=null,u=a.util.globalScope,l=u.crypto||u.msCrypto;if(l&&l.getRandomValues&&(c=function(e){return l.getRandomValues(e)}),a.options.usePureJavaScript||!a.util.isNodejs&&!c){if("undefined"==typeof window||window.document,o.collectInt(+new Date,32),"undefined"!=typeof navigator){var p="";for(var f in navigator)try{"string"==typeof navigator[f]&&(p+=navigator[f])}catch(e){}o.collect(p),p=null}t&&(t().mousemove((function(e){o.collectInt(e.clientX,16),o.collectInt(e.clientY,16)})),t().keypress((function(e){o.collectInt(e.charCode,8)})))}if(a.random)for(var f in o)a.random[f]=o[f];else a.random=o;a.random.createInstance=s,e.exports=a.random}("undefined"!=typeof jQuery?jQuery:null)},function(e,t,r){var a=r(0);r(1),r(6);var n=e.exports=a.asn1=a.asn1||{};function i(e,t,r){if(r>t){var a=new Error("Too few bytes to parse DER.");throw a.available=e.length(),a.remaining=t,a.requested=r,a}}n.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},n.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},n.create=function(e,t,r,i,s){if(a.util.isArray(i)){for(var o=[],c=0;c<i.length;++c)void 0!==i[c]&&o.push(i[c]);i=o}var u={tagClass:e,type:t,constructed:r,composed:r||a.util.isArray(i),value:i};return s&&"bitStringContents"in s&&(u.bitStringContents=s.bitStringContents,u.original=n.copy(u)),u},n.copy=function(e,t){var r;if(a.util.isArray(e)){r=[];for(var i=0;i<e.length;++i)r.push(n.copy(e[i],t));return r}return"string"==typeof e?e:(r={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:n.copy(e.value,t)},t&&!t.excludeBitStringContents&&(r.bitStringContents=e.bitStringContents),r)},n.equals=function(e,t,r){if(a.util.isArray(e)){if(!a.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(!n.equals(e[i],t[i]))return!1;return!0}if(typeof e!=typeof t)return!1;if("string"==typeof e)return e===t;var s=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&n.equals(e.value,t.value);return r&&r.includeBitStringContents&&(s=s&&e.bitStringContents===t.bitStringContents),s},n.getBerValueLength=function(e){var t=e.getByte();if(128!==t)return 128&t?e.getInt((127&t)<<3):t};n.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"==typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"==typeof e&&(e=a.util.createBuffer(e));var r=e.length(),s=function e(t,r,a,s){var o;i(t,r,2);var c=t.getByte();r--;var u=192&c,l=31&c;o=t.length();var p,f,h=function(e,t){var r=e.getByte();if(t--,128!==r){var a;if(128&r){var n=127&r;i(e,t,n),a=e.getInt(n<<3)}else a=r;if(a<0)throw new Error("Negative length: "+a);return a}}(t,r);if(r-=o-t.length(),void 0!==h&&h>r){if(s.strict){var d=new Error("Too few bytes to read ASN.1 value.");throw d.available=t.length(),d.remaining=r,d.requested=h,d}h=r}var y=32==(32&c);if(y)if(p=[],void 0===h)for(;;){if(i(t,r,2),t.bytes(2)===String.fromCharCode(0,0)){t.getBytes(2),r-=2;break}o=t.length(),p.push(e(t,r,a+1,s)),r-=o-t.length()}else for(;h>0;)o=t.length(),p.push(e(t,h,a+1,s)),r-=o-t.length(),h-=o-t.length();void 0===p&&u===n.Class.UNIVERSAL&&l===n.Type.BITSTRING&&(f=t.bytes(h));if(void 0===p&&s.decodeBitStrings&&u===n.Class.UNIVERSAL&&l===n.Type.BITSTRING&&h>1){var g=t.read,v=r,m=0;if(l===n.Type.BITSTRING&&(i(t,r,1),m=t.getByte(),r--),0===m)try{o=t.length();var C=e(t,r,a+1,{strict:!0,decodeBitStrings:!0}),E=o-t.length();r-=E,l==n.Type.BITSTRING&&E++;var S=C.tagClass;E!==h||S!==n.Class.UNIVERSAL&&S!==n.Class.CONTEXT_SPECIFIC||(p=[C])}catch(e){}void 0===p&&(t.read=g,r=v)}if(void 0===p){if(void 0===h){if(s.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");h=r}if(l===n.Type.BMPSTRING)for(p="";h>0;h-=2)i(t,r,2),p+=String.fromCharCode(t.getInt16()),r-=2;else p=t.getBytes(h),r-=h}var T=void 0===f?null:{bitStringContents:f};return n.create(u,l,y,p,T)}(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return s},n.toDer=function(e){var t=a.util.createBuffer(),r=e.tagClass|e.type,i=a.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=n.equals(e,e.original))),s)i.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:i.putByte(0);for(var o=0;o<e.value.length;++o)void 0!==e.value[o]&&i.putBuffer(n.toDer(e.value[o]))}else if(e.type===n.Type.BMPSTRING)for(o=0;o<e.value.length;++o)i.putInt16(e.value.charCodeAt(o));else e.type===n.Type.INTEGER&&e.value.length>1&&(0===e.value.charCodeAt(0)&&0==(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128==(128&e.value.charCodeAt(1)))?i.putBytes(e.value.substr(1)):i.putBytes(e.value);if(t.putByte(r),i.length()<=127)t.putByte(127&i.length());else{var c=i.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(o=u.length-1;o>=0;--o)t.putByte(u.charCodeAt(o))}return t.putBuffer(i),t},n.oidToDer=function(e){var t,r,n,i,s=e.split("."),o=a.util.createBuffer();o.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var c=2;c<s.length;++c){t=!0,r=[],n=parseInt(s[c],10);do{i=127&n,n>>>=7,t||(i|=128),r.push(i),t=!1}while(n>0);for(var u=r.length-1;u>=0;--u)o.putByte(r[u])}return o},n.derToOid=function(e){var t;"string"==typeof e&&(e=a.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var n=0;e.length()>0;)n<<=7,128&(r=e.getByte())?n+=127&r:(t+="."+(n+r),n=0);return t},n.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var a=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(o=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,a,n),t.setUTCHours(i,s,o,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=60*parseInt(e.substr(u+1,2),10)+parseInt(e.substr(u+4,2),10);l*=6e4,"+"===c?t.setTime(+t-l):t.setTime(+t+l)}return t},n.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),a=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var p=e.length-5,f=e.charAt(p);"+"!==f&&"-"!==f||(u=60*parseInt(e.substr(p+1,2),10)+parseInt(e.substr(p+4,2),10),u*=6e4,"+"===f&&(u*=-1),l=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,a,n),t.setUTCHours(i,s,o,c),t.setTime(+t+u)):(t.setFullYear(r,a,n),t.setHours(i,s,o,c)),t},n.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var a=0;a<r.length;++a)r[a].length<2&&(t+="0"),t+=r[a];return t+="Z"},n.dateToGeneralizedTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push(""+e.getUTCFullYear()),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var a=0;a<r.length;++a)r[a].length<2&&(t+="0"),t+=r[a];return t+="Z"},n.integerToDer=function(e){var t=a.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putS
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/dist/prime.worker.min.js
aws/lti-middleware/node_modules/node-forge/dist/prime.worker.min.js
!function(t){var i={};function r(o){if(i[o])return i[o].exports;var s=i[o]={i:o,l:!1,exports:{}};return t[o].call(s.exports,s,s.exports,r),s.l=!0,s.exports}r.m=t,r.c=i,r.d=function(t,i,o){r.o(t,i)||Object.defineProperty(t,i,{enumerable:!0,get:o})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,i){if(1&i&&(t=r(t)),8&i)return t;if(4&i&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(r.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&i&&"string"!=typeof t)for(var s in t)r.d(o,s,function(i){return t[i]}.bind(null,s));return o},r.n=function(t){var i=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(i,"a",i),i},r.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},r.p="",r(r.s=1)}([function(t,i){t.exports={options:{usePureJavaScript:!1}}},function(t,i,r){r(2),t.exports=r(0)},function(t,i,r){var o=r(0);r(3);var s=[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,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],e=(1<<26)/s[s.length-1],a=o.jsbn.BigInteger;new a(null).fromInt(2),self.addEventListener("message",(function(t){var i=function(t){for(var i=new a(t.hex,16),r=0,o=t.workLoad,s=0;s<o;++s){if(h(i))return{found:!0,prime:i.toString(16)};i.dAddOffset(n[r++%8],0)}return{found:!1}}(t.data);self.postMessage(i)})),self.postMessage({found:!1});var n=[6,4,2,4,2,4,6,2];function h(t){for(var i=1;i<s.length;){for(var r=s[i],o=i+1;o<s.length&&r<e;)r*=s[o++];for(r=t.modInt(r);i<o;)if(r%s[i++]==0)return!1}return function(t){var i=t.subtract(a.ONE),r=i.getLowestSetBit();if(r<=0)return!1;for(var o,s=i.shiftRight(r),e=(p=t.bitLength(),p<=100?27:p<=150?18:p<=200?15:p<=250?12:p<=300?9:p<=350?8:p<=400?7:p<=500?6:p<=600?5:p<=800?4:p<=1250?3:2),n={nextBytes:function(t){for(var i=0;i<t.length;++i)t[i]=Math.floor(255*Math.random())}},h=0;h<e;++h){do{o=new a(t.bitLength(),n)}while(o.compareTo(a.ONE)<=0||o.compareTo(i)>=0);var u=o.modPow(s,t);if(0!==u.compareTo(a.ONE)&&0!==u.compareTo(i)){for(var f=r;--f;){if(0===(u=u.modPowInt(2,t)).compareTo(a.ONE))return!1;if(0===u.compareTo(i))break}if(0===f)return!1}}var p;return!0}(t)}},function(t,i,r){var o,s=r(0);t.exports=s.jsbn=s.jsbn||{};function e(t,i,r){this.data=[],null!=t&&("number"==typeof t?this.fromNumber(t,i,r):null==i&&"string"!=typeof t?this.fromString(t,256):this.fromString(t,i))}function a(){return new e(null)}function n(t,i,r,o,s,e){for(var a=16383&i,n=i>>14;--e>=0;){var h=16383&this.data[t],u=this.data[t++]>>14,f=n*h+u*a;s=((h=a*h+((16383&f)<<14)+r.data[o]+s)>>28)+(f>>14)+n*u,r.data[o++]=268435455&h}return s}s.jsbn.BigInteger=e,"undefined"==typeof navigator?(e.prototype.am=n,o=28):"Microsoft Internet Explorer"==navigator.appName?(e.prototype.am=function(t,i,r,o,s,e){for(var a=32767&i,n=i>>15;--e>=0;){var h=32767&this.data[t],u=this.data[t++]>>15,f=n*h+u*a;s=((h=a*h+((32767&f)<<15)+r.data[o]+(1073741823&s))>>>30)+(f>>>15)+n*u+(s>>>30),r.data[o++]=1073741823&h}return s},o=30):"Netscape"!=navigator.appName?(e.prototype.am=function(t,i,r,o,s,e){for(;--e>=0;){var a=i*this.data[t++]+r.data[o]+s;s=Math.floor(a/67108864),r.data[o++]=67108863&a}return s},o=26):(e.prototype.am=n,o=28),e.prototype.DB=o,e.prototype.DM=(1<<o)-1,e.prototype.DV=1<<o;e.prototype.FV=Math.pow(2,52),e.prototype.F1=52-o,e.prototype.F2=2*o-52;var h,u,f=new Array;for(h="0".charCodeAt(0),u=0;u<=9;++u)f[h++]=u;for(h="a".charCodeAt(0),u=10;u<36;++u)f[h++]=u;for(h="A".charCodeAt(0),u=10;u<36;++u)f[h++]=u;function p(t){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(t)}function d(t,i){var r=f[t.charCodeAt(i)];return null==r?-1:r}function c(t){var i=a();return i.fromInt(t),i}function m(t){var i,r=1;return 0!=(i=t>>>16)&&(t=i,r+=16),0!=(i=t>>8)&&(t=i,r+=8),0!=(i=t>>4)&&(t=i,r+=4),0!=(i=t>>2)&&(t=i,r+=2),0!=(i=t>>1)&&(t=i,r+=1),r}function l(t){this.m=t}function v(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t}function T(t,i){return t&i}function y(t,i){return t|i}function b(t,i){return t^i}function g(t,i){return t&~i}function D(t){if(0==t)return-1;var i=0;return 0==(65535&t)&&(t>>=16,i+=16),0==(255&t)&&(t>>=8,i+=8),0==(15&t)&&(t>>=4,i+=4),0==(3&t)&&(t>>=2,i+=2),0==(1&t)&&++i,i}function B(t){for(var i=0;0!=t;)t&=t-1,++i;return i}function S(){}function M(t){return t}function w(t){this.r2=a(),this.q3=a(),e.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}l.prototype.convert=function(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t},l.prototype.revert=function(t){return t},l.prototype.reduce=function(t){t.divRemTo(this.m,null,t)},l.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r),this.reduce(r)},l.prototype.sqrTo=function(t,i){t.squareTo(i),this.reduce(i)},v.prototype.convert=function(t){var i=a();return t.abs().dlShiftTo(this.m.t,i),i.divRemTo(this.m,null,i),t.s<0&&i.compareTo(e.ZERO)>0&&this.m.subTo(i,i),i},v.prototype.revert=function(t){var i=a();return t.copyTo(i),this.reduce(i),i},v.prototype.reduce=function(t){for(;t.t<=this.mt2;)t.data[t.t++]=0;for(var i=0;i<this.m.t;++i){var r=32767&t.data[i],o=r*this.mpl+((r*this.mph+(t.data[i]>>15)*this.mpl&this.um)<<15)&t.DM;for(r=i+this.m.t,t.data[r]+=this.m.am(0,o,t,i,0,this.m.t);t.data[r]>=t.DV;)t.data[r]-=t.DV,t.data[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)},v.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r),this.reduce(r)},v.prototype.sqrTo=function(t,i){t.squareTo(i),this.reduce(i)},e.prototype.copyTo=function(t){for(var i=this.t-1;i>=0;--i)t.data[i]=this.data[i];t.t=this.t,t.s=this.s},e.prototype.fromInt=function(t){this.t=1,this.s=t<0?-1:0,t>0?this.data[0]=t:t<-1?this.data[0]=t+this.DV:this.t=0},e.prototype.fromString=function(t,i){var r;if(16==i)r=4;else if(8==i)r=3;else if(256==i)r=8;else if(2==i)r=1;else if(32==i)r=5;else{if(4!=i)return void this.fromRadix(t,i);r=2}this.t=0,this.s=0;for(var o=t.length,s=!1,a=0;--o>=0;){var n=8==r?255&t[o]:d(t,o);n<0?"-"==t.charAt(o)&&(s=!0):(s=!1,0==a?this.data[this.t++]=n:a+r>this.DB?(this.data[this.t-1]|=(n&(1<<this.DB-a)-1)<<a,this.data[this.t++]=n>>this.DB-a):this.data[this.t-1]|=n<<a,(a+=r)>=this.DB&&(a-=this.DB))}8==r&&0!=(128&t[0])&&(this.s=-1,a>0&&(this.data[this.t-1]|=(1<<this.DB-a)-1<<a)),this.clamp(),s&&e.ZERO.subTo(this,this)},e.prototype.clamp=function(){for(var t=this.s&this.DM;this.t>0&&this.data[this.t-1]==t;)--this.t},e.prototype.dlShiftTo=function(t,i){var r;for(r=this.t-1;r>=0;--r)i.data[r+t]=this.data[r];for(r=t-1;r>=0;--r)i.data[r]=0;i.t=this.t+t,i.s=this.s},e.prototype.drShiftTo=function(t,i){for(var r=t;r<this.t;++r)i.data[r-t]=this.data[r];i.t=Math.max(this.t-t,0),i.s=this.s},e.prototype.lShiftTo=function(t,i){var r,o=t%this.DB,s=this.DB-o,e=(1<<s)-1,a=Math.floor(t/this.DB),n=this.s<<o&this.DM;for(r=this.t-1;r>=0;--r)i.data[r+a+1]=this.data[r]>>s|n,n=(this.data[r]&e)<<o;for(r=a-1;r>=0;--r)i.data[r]=0;i.data[a]=n,i.t=this.t+a+1,i.s=this.s,i.clamp()},e.prototype.rShiftTo=function(t,i){i.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t)i.t=0;else{var o=t%this.DB,s=this.DB-o,e=(1<<o)-1;i.data[0]=this.data[r]>>o;for(var a=r+1;a<this.t;++a)i.data[a-r-1]|=(this.data[a]&e)<<s,i.data[a-r]=this.data[a]>>o;o>0&&(i.data[this.t-r-1]|=(this.s&e)<<s),i.t=this.t-r,i.clamp()}},e.prototype.subTo=function(t,i){for(var r=0,o=0,s=Math.min(t.t,this.t);r<s;)o+=this.data[r]-t.data[r],i.data[r++]=o&this.DM,o>>=this.DB;if(t.t<this.t){for(o-=t.s;r<this.t;)o+=this.data[r],i.data[r++]=o&this.DM,o>>=this.DB;o+=this.s}else{for(o+=this.s;r<t.t;)o-=t.data[r],i.data[r++]=o&this.DM,o>>=this.DB;o-=t.s}i.s=o<0?-1:0,o<-1?i.data[r++]=this.DV+o:o>0&&(i.data[r++]=o),i.t=r,i.clamp()},e.prototype.multiplyTo=function(t,i){var r=this.abs(),o=t.abs(),s=r.t;for(i.t=s+o.t;--s>=0;)i.data[s]=0;for(s=0;s<o.t;++s)i.data[s+r.t]=r.am(0,o.data[s],i,s,0,r.t);i.s=0,i.clamp(),this.s!=t.s&&e.ZERO.subTo(i,i)},e.prototype.squareTo=function(t){for(var i=this.abs(),r=t.t=2*i.t;--r>=0;)t.data[r]=0;for(r=0;r<i.t-1;++r){var o=i.am(r,i.data[r],t,2*r,0,1);(t.data[r+i.t]+=i.am(r+1,2*i.data[r],t,2*r+1,o,i.t-r-1))>=i.DV&&(t.data[r+i.t]-=i.DV,t.data[r+i.t+1]=1)}t.t>0&&(t.data[t.t-1]+=i.am(r,i.data[r],t,2*r,0,1)),t.s=0,t.clamp()},e.prototype.divRemTo=function(t,i,r){var o=t.abs();if(!(o.t<=0)){var s=this.abs();if(s.t<o.t)return null!=i&&i.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=a());var n=a(),h=this.s,u=t.s,f=this.DB-m(o.data[o.t-1]);f>0?(o.lShiftTo(f,n),s.lShiftTo(f,r)):(o.copyTo(n),s.copyTo(r));var p=n.t,d=n.data[p-1];if(0!=d){var c=d*(1<<this.F1)+(p>1?n.data[p-2]>>this.F2:0),l=this.FV/c,v=(1<<this.F1)/c,T=1<<this.F2,y=r.t,b=y-p,g=null==i?a():i;for(n.dlShiftTo(b,g),r.compareTo(g)>=0&&(r.data[r.t++]=1,r.subTo(g,r)),e.ONE.dlShiftTo(p,g),g.subTo(n,n);n.t<p;)n.data[n.t++]=0;for(;--b>=0;){var D=r.data[--y]==d?this.DM:Math.floor(r.data[y]*l+(r.data[y-1]+T)*v);if((r.data[y]+=n.am(0,D,r,b,0,p))<D)for(n.dlShiftTo(b,g),r.subTo(g,r);r.data[y]<--D;)r.subTo(g,r)}null!=i&&(r.drShiftTo(p,i),h!=u&&e.ZERO.subTo(i,i)),r.t=p,r.clamp(),f>0&&r.rShiftTo(f,r),h<0&&e.ZERO.subTo(r,r)}}},e.prototype.invDigit=function(){if(this.t<1)return 0;var t=this.data[0];if(0==(1&t))return 0;var i=3&t;return(i=(i=(i=(i=i*(2-(15&t)*i)&15)*(2-(255&t)*i)&255)*(2-((65535&t)*i&65535))&65535)*(2-t*i%this.DV)%this.DV)>0?this.DV-i:-i},e.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},e.prototype.exp=function(t,i){if(t>4294967295||t<1)return e.ONE;var r=a(),o=a(),s=i.convert(this),n=m(t)-1;for(s.copyTo(r);--n>=0;)if(i.sqrTo(r,o),(t&1<<n)>0)i.mulTo(o,s,r);else{var h=r;r=o,o=h}return i.revert(r)},e.prototype.toString=function(t){if(this.s<0)return"-"+this.negate().toString(t);var i;if(16==t)i=4;else if(8==t)i=3;else if(2==t)i=1;else if(32==t)i=5;else{if(4!=t)return this.toRadix(t);i=2}var r,o=(1<<i)-1,s=!1,e="",a=this.t,n=this.DB-a*this.DB%i;if(a-- >0)for(n<this.DB&&(r=this.data[a]>>n)>0&&(s=!0,e=p(r));a>=0;)n<i?(r=(this.data[a]&(1<<n)-1)<<i-n,r|=this.data[--a]>>(n+=this.DB-i)):(r=this.data[a]>>(n-=i)&o,n<=0&&(n+=this.DB,--a)),r>0&&(s=!0),s&&(e+=p(r));return s?e:"0"},e.prototype.negate=function(){var t=a();return e.ZERO.subTo(this,t),t},e.prototype.abs=function(){return this.s<0?this.negate():this},e.prototype.compareTo=function(t){var i=this.s-t.s;if(0!=i)return i;var r=this.t;if(0!=(i=r-t.t))return this.s<0?-i:i;for(;--r>=0;)if(0!=(i=this.data[r]-t.data[r]))return i;return 0},e.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+m(this.data[this.t-1]^this.s&this.DM)},e.prototype.mod=function(t){var i=a();return this.abs().divRemTo(t,null,i),this.s<0&&i.compareTo(e.ZERO)>0&&t.subTo(i,i),i},e.prototype.modPowInt=function(t,i){var r;return r=t<256||i.isEven()?new l(i):new v(i),this.exp(t,r)},e.ZERO=c(0),e.ONE=c(1),S.prototype.convert=M,S.prototype.revert=M,S.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r)},S.prototype.sqrTo=function(t,i){t.squareTo(i)},w.prototype.convert=function(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var i=a();return t.copyTo(i),this.reduce(i),i},w.prototype.revert=function(t){return t},w.prototype.reduce=function(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)},w.prototype.mulTo=function(t,i,r){t.multiplyTo(i,r),this.reduce(r)},w.prototype.sqrTo=function(t,i){t.squareTo(i),this.reduce(i)};var E=[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],O=(1<<26)/E[E.length-1];e.prototype.chunkSize=function(t){return Math.floor(Math.LN2*this.DB/Math.log(t))},e.prototype.toRadix=function(t){if(null==t&&(t=10),0==this.signum()||t<2||t>36)return"0";var i=this.chunkSize(t),r=Math.pow(t,i),o=c(r),s=a(),e=a(),n="";for(this.divRemTo(o,s,e);s.signum()>0;)n=(r+e.intValue()).toString(t).substr(1)+n,s.divRemTo(o,s,e);return e.intValue().toString(t)+n},e.prototype.fromRadix=function(t,i){this.fromInt(0),null==i&&(i=10);for(var r=this.chunkSize(i),o=Math.pow(i,r),s=!1,a=0,n=0,h=0;h<t.length;++h){var u=d(t,h);u<0?"-"==t.charAt(h)&&0==this.signum()&&(s=!0):(n=i*n+u,++a>=r&&(this.dMultiply(o),this.dAddOffset(n,0),a=0,n=0))}a>0&&(this.dMultiply(Math.pow(i,a)),this.dAddOffset(n,0)),s&&e.ZERO.subTo(this,this)},e.prototype.fromNumber=function(t,i,r){if("number"==typeof i)if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(e.ONE.shiftLeft(t-1),y,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(i);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(e.ONE.shiftLeft(t-1),this);else{var o=new Array,s=7&t;o.length=1+(t>>3),i.nextBytes(o),s>0?o[0]&=(1<<s)-1:o[0]=0,this.fromString(o,256)}},e.prototype.bitwiseTo=function(t,i,r){var o,s,e=Math.min(t.t,this.t);for(o=0;o<e;++o)r.data[o]=i(this.data[o],t.data[o]);if(t.t<this.t){for(s=t.s&this.DM,o=e;o<this.t;++o)r.data[o]=i(this.data[o],s);r.t=this.t}else{for(s=this.s&this.DM,o=e;o<t.t;++o)r.data[o]=i(s,t.data[o]);r.t=t.t}r.s=i(this.s,t.s),r.clamp()},e.prototype.changeBit=function(t,i){var r=e.ONE.shiftLeft(t);return this.bitwiseTo(r,i,r),r},e.prototype.addTo=function(t,i){for(var r=0,o=0,s=Math.min(t.t,this.t);r<s;)o+=this.data[r]+t.data[r],i.data[r++]=o&this.DM,o>>=this.DB;if(t.t<this.t){for(o+=t.s;r<this.t;)o+=this.data[r],i.data[r++]=o&this.DM,o>>=this.DB;o+=this.s}else{for(o+=this.s;r<t.t;)o+=t.data[r],i.data[r++]=o&this.DM,o>>=this.DB;o+=t.s}i.s=o<0?-1:0,o>0?i.data[r++]=o:o<-1&&(i.data[r++]=this.DV+o),i.t=r,i.clamp()},e.prototype.dMultiply=function(t){this.data[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()},e.prototype.dAddOffset=function(t,i){if(0!=t){for(;this.t<=i;)this.data[this.t++]=0;for(this.data[i]+=t;this.data[i]>=this.DV;)this.data[i]-=this.DV,++i>=this.t&&(this.data[this.t++]=0),++this.data[i]}},e.prototype.multiplyLowerTo=function(t,i,r){var o,s=Math.min(this.t+t.t,i);for(r.s=0,r.t=s;s>0;)r.data[--s]=0;for(o=r.t-this.t;s<o;++s)r.data[s+this.t]=this.am(0,t.data[s],r,s,0,this.t);for(o=Math.min(t.t,i);s<o;++s)this.am(0,t.data[s],r,s,0,i-s);r.clamp()},e.prototype.multiplyUpperTo=function(t,i,r){--i;var o=r.t=this.t+t.t-i;for(r.s=0;--o>=0;)r.data[o]=0;for(o=Math.max(i-this.t,0);o<t.t;++o)r.data[this.t+o-i]=this.am(i-o,t.data[o],r,0,0,this.t+o-i);r.clamp(),r.drShiftTo(1,r)},e.prototype.modInt=function(t){if(t<=0)return 0;var i=this.DV%t,r=this.s<0?t-1:0;if(this.t>0)if(0==i)r=this.data[0]%t;else for(var o=this.t-1;o>=0;--o)r=(i*r+this.data[o])%t;return r},e.prototype.millerRabin=function(t){var i=this.subtract(e.ONE),r=i.getLowestSetBit();if(r<=0)return!1;for(var o,s=i.shiftRight(r),a={nextBytes:function(t){for(var i=0;i<t.length;++i)t[i]=Math.floor(256*Math.random())}},n=0;n<t;++n){do{o=new e(this.bitLength(),a)}while(o.compareTo(e.ONE)<=0||o.compareTo(i)>=0);var h=o.modPow(s,this);if(0!=h.compareTo(e.ONE)&&0!=h.compareTo(i)){for(var u=1;u++<r&&0!=h.compareTo(i);)if(0==(h=h.modPowInt(2,this)).compareTo(e.ONE))return!1;if(0!=h.compareTo(i))return!1}}return!0},e.prototype.clone=function(){var t=a();return this.copyTo(t),t},e.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this.data[0];if(0==this.t)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]},e.prototype.byteValue=function(){return 0==this.t?this.s:this.data[0]<<24>>24},e.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},e.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},e.prototype.toByteArray=function(){var t=this.t,i=new Array;i[0]=this.s;var r,o=this.DB-t*this.DB%8,s=0;if(t-- >0)for(o<this.DB&&(r=this.data[t]>>o)!=(this.s&this.DM)>>o&&(i[s++]=r|this.s<<this.DB-o);t>=0;)o<8?(r=(this.data[t]&(1<<o)-1)<<8-o,r|=this.data[--t]>>(o+=this.DB-8)):(r=this.data[t]>>(o-=8)&255,o<=0&&(o+=this.DB,--t)),0!=(128&r)&&(r|=-256),0==s&&(128&this.s)!=(128&r)&&++s,(s>0||r!=this.s)&&(i[s++]=r);return i},e.prototype.equals=function(t){return 0==this.compareTo(t)},e.prototype.min=function(t){return this.compareTo(t)<0?this:t},e.prototype.max=function(t){return this.compareTo(t)>0?this:t},e.prototype.and=function(t){var i=a();return this.bitwiseTo(t,T,i),i},e.prototype.or=function(t){var i=a();return this.bitwiseTo(t,y,i),i},e.prototype.xor=function(t){var i=a();return this.bitwiseTo(t,b,i),i},e.prototype.andNot=function(t){var i=a();return this.bitwiseTo(t,g,i),i},e.prototype.not=function(){for(var t=a(),i=0;i<this.t;++i)t.data[i]=this.DM&~this.data[i];return t.t=this.t,t.s=~this.s,t},e.prototype.shiftLeft=function(t){var i=a();return t<0?this.rShiftTo(-t,i):this.lShiftTo(t,i),i},e.prototype.shiftRight=function(t){var i=a();return t<0?this.lShiftTo(-t,i):this.rShiftTo(t,i),i},e.prototype.getLowestSetBit=function(){for(var t=0;t<this.t;++t)if(0!=this.data[t])return t*this.DB+D(this.data[t]);return this.s<0?this.t*this.DB:-1},e.prototype.bitCount=function(){for(var t=0,i=this.s&this.DM,r=0;r<this.t;++r)t+=B(this.data[r]^i);return t},e.prototype.testBit=function(t){var i=Math.floor(t/this.DB);return i>=this.t?0!=this.s:0!=(this.data[i]&1<<t%this.DB)},e.prototype.setBit=function(t){return this.changeBit(t,y)},e.prototype.clearBit=function(t){return this.changeBit(t,g)},e.prototype.flipBit=function(t){return this.changeBit(t,b)},e.prototype.add=function(t){var i=a();return this.addTo(t,i),i},e.prototype.subtract=function(t){var i=a();return this.subTo(t,i),i},e.prototype.multiply=function(t){var i=a();return this.multiplyTo(t,i),i},e.prototype.divide=function(t){var i=a();return this.divRemTo(t,i,null),i},e.prototype.remainder=function(t){var i=a();return this.divRemTo(t,null,i),i},e.prototype.divideAndRemainder=function(t){var i=a(),r=a();return this.divRemTo(t,i,r),new Array(i,r)},e.prototype.modPow=function(t,i){var r,o,s=t.bitLength(),e=c(1);if(s<=0)return e;r=s<18?1:s<48?3:s<144?4:s<768?5:6,o=s<8?new l(i):i.isEven()?new w(i):new v(i);var n=new Array,h=3,u=r-1,f=(1<<r)-1;if(n[1]=o.convert(this),r>1){var p=a();for(o.sqrTo(n[1],p);h<=f;)n[h]=a(),o.mulTo(p,n[h-2],n[h]),h+=2}var d,T,y=t.t-1,b=!0,g=a();for(s=m(t.data[y])-1;y>=0;){for(s>=u?d=t.data[y]>>s-u&f:(d=(t.data[y]&(1<<s+1)-1)<<u-s,y>0&&(d|=t.data[y-1]>>this.DB+s-u)),h=r;0==(1&d);)d>>=1,--h;if((s-=h)<0&&(s+=this.DB,--y),b)n[d].copyTo(e),b=!1;else{for(;h>1;)o.sqrTo(e,g),o.sqrTo(g,e),h-=2;h>0?o.sqrTo(e,g):(T=e,e=g,g=T),o.mulTo(g,n[d],e)}for(;y>=0&&0==(t.data[y]&1<<s);)o.sqrTo(e,g),T=e,e=g,g=T,--s<0&&(s=this.DB-1,--y)}return o.revert(e)},e.prototype.modInverse=function(t){var i=t.isEven();if(this.isEven()&&i||0==t.signum())return e.ZERO;for(var r=t.clone(),o=this.clone(),s=c(1),a=c(0),n=c(0),h=c(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),i?(s.isEven()&&a.isEven()||(s.addTo(this,s),a.subTo(t,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(t,a),a.rShiftTo(1,a);for(;o.isEven();)o.rShiftTo(1,o),i?(n.isEven()&&h.isEven()||(n.addTo(this,n),h.subTo(t,h)),n.rShiftTo(1,n)):h.isEven()||h.subTo(t,h),h.rShiftTo(1,h);r.compareTo(o)>=0?(r.subTo(o,r),i&&s.subTo(n,s),a.subTo(h,a)):(o.subTo(r,o),i&&n.subTo(s,n),h.subTo(a,h))}return 0!=o.compareTo(e.ONE)?e.ZERO:h.compareTo(t)>=0?h.subtract(t):h.signum()<0?(h.addTo(t,h),h.signum()<0?h.add(t):h):h},e.prototype.pow=function(t){return this.exp(t,new S)},e.prototype.gcd=function(t){var i=this.s<0?this.negate():this.clone(),r=t.s<0?t.negate():t.clone();if(i.compareTo(r)<0){var o=i;i=r,r=o}var s=i.getLowestSetBit(),e=r.getLowestSetBit();if(e<0)return i;for(s<e&&(e=s),e>0&&(i.rShiftTo(e,i),r.rShiftTo(e,r));i.signum()>0;)(s=i.getLowestSetBit())>0&&i.rShiftTo(s,i),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),i.compareTo(r)>=0?(i.subTo(r,i),i.rShiftTo(1,i)):(r.subTo(i,r),r.rShiftTo(1,r));return e>0&&r.lShiftTo(e,r),r},e.prototype.isProbablePrime=function(t){var i,r=this.abs();if(1==r.t&&r.data[0]<=E[E.length-1]){for(i=0;i<E.length;++i)if(r.data[0]==E[i])return!0;return!1}if(r.isEven())return!1;for(i=1;i<E.length;){for(var o=E[i],s=i+1;s<E.length&&o<O;)o*=E[s++];for(o=r.modInt(o);i<s;)if(o%E[i++]==0)return!1}return r.millerRabin(t)}}]); //# sourceMappingURL=prime.worker.min.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/express-jwt/test/multitenancy.test.js
aws/lti-middleware/node_modules/express-jwt/test/multitenancy.test.js
var jwt = require('jsonwebtoken'); var assert = require('assert'); var expressjwt = require('../lib'); var UnauthorizedError = require('../lib/errors/UnauthorizedError'); describe('multitenancy', function(){ var req = {}; var res = {}; var tenants = { 'a': { secret: 'secret-a' } }; var secretCallback = function(req, payload, cb){ var issuer = payload.iss; if (tenants[issuer]){ return cb(null, tenants[issuer].secret); } return cb(new UnauthorizedError('missing_secret', { message: 'Could not find secret for issuer.' })); }; var middleware = expressjwt({ secret: secretCallback, algorithms: ['HS256'] }); it ('should retrieve secret using callback', function(){ var token = jwt.sign({ iss: 'a', foo: 'bar'}, tenants.a.secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; middleware(req, res, function() { assert.equal('bar', req.user.foo); }); }); it ('should throw if an error ocurred when retrieving the token', function(){ var secret = 'shhhhhh'; var token = jwt.sign({ iss: 'inexistent', foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; middleware(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'missing_secret'); assert.equal(err.message, 'Could not find secret for issuer.'); }); }); it ('should fail if token is revoked', function(){ var token = jwt.sign({ iss: 'a', foo: 'bar'}, tenants.a.secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({ secret: secretCallback, algorithms: ['HS256'], isRevoked: function(req, payload, done){ done(null, true); } })(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'revoked_token'); assert.equal(err.message, 'The token has been revoked.'); }); }); });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express-jwt/test/string_token.test.js
aws/lti-middleware/node_modules/express-jwt/test/string_token.test.js
var jwt = require('jsonwebtoken'); var assert = require('assert'); var expressjwt = require('../lib'); var UnauthorizedError = require('../lib/errors/UnauthorizedError'); describe('string tokens', function () { var req = {}; var res = {}; it('should work with a valid string token', function() { var secret = 'shhhhhh'; var token = jwt.sign('foo', secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256']})(req, res, function() { assert.equal('foo', req.user); }); }); });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express-jwt/test/jwt.test.js
aws/lti-middleware/node_modules/express-jwt/test/jwt.test.js
var jwt = require('jsonwebtoken'); var assert = require('assert'); var expressjwt = require('../lib'); var UnauthorizedError = require('../lib/errors/UnauthorizedError'); describe('failure tests', function () { var req = {}; var res = {}; it('should throw if options not sent', function() { try { expressjwt(); } catch(e) { assert.ok(e); assert.equal(e.message, 'secret should be set'); } }); it('should throw if algorithms is not sent', function() { try { expressjwt({ secret: 'shhhh' }); } catch(e) { assert.ok(e); assert.equal(e.message, 'algorithms should be set'); } }); it('should throw if algorithms is not an array', function() { try { expressjwt({ secret: 'shhhh', algorithms: 'foo' }); } catch(e) { assert.ok(e); assert.equal(e.message, 'algorithms must be an array'); } }); it('should throw if no authorization header and credentials are required', function() { expressjwt({secret: 'shhhh', credentialsRequired: true, algorithms: ['HS256']})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'credentials_required'); }); }); it('support unless skip', function() { req.originalUrl = '/index.html'; expressjwt({secret: 'shhhh', algorithms: ['HS256'], algorithms: ['HS256']}).unless({path: '/index.html'})(req, res, function(err) { assert.ok(!err); }); }); it('should skip on CORS preflight', function() { var corsReq = {}; corsReq.method = 'OPTIONS'; corsReq.headers = { 'access-control-request-headers': 'sasa, sras, authorization' }; expressjwt({secret: 'shhhh', algorithms: ['HS256']})(corsReq, res, function(err) { assert.ok(!err); }); }); it('should throw if authorization header is malformed', function() { req.headers = {}; req.headers.authorization = 'wrong'; expressjwt({secret: 'shhhh', algorithms: ['HS256']})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'credentials_bad_format'); }); }); it('should throw if authorization header is not Bearer', function() { req.headers = {}; req.headers.authorization = 'Basic foobar'; expressjwt({secret: 'shhhh', algorithms: ['HS256']})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'credentials_bad_scheme'); }); }); it('should next if authorization header is not Bearer and credentialsRequired is false', function() { req.headers = {}; req.headers.authorization = 'Basic foobar'; expressjwt({secret: 'shhhh', algorithms: ['HS256'], credentialsRequired: false})(req, res, function(err) { assert.ok(typeof err === 'undefined'); }); }); it('should throw if authorization header is not well-formatted jwt', function() { req.headers = {}; req.headers.authorization = 'Bearer wrongjwt'; expressjwt({secret: 'shhhh', algorithms: ['HS256']})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); }); }); it('should throw if jwt is an invalid json', function() { req.headers = {}; req.headers.authorization = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.yJ1c2VybmFtZSI6InNhZ3VpYXIiLCJpYXQiOjE0NzEwMTg2MzUsImV4cCI6MTQ3MzYxMDYzNX0.foo'; expressjwt({secret: 'shhhh', algorithms: ['HS256']})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); }); }); it('should throw if authorization header is not valid jwt', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: 'different-shhhh', algorithms: ['HS256'] })(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'invalid signature'); }); }); it('should throw if audience is not expected', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar', aud: 'expected-audience'}, secret, { expiresIn: 500}); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: 'shhhhhh', algorithms: ['HS256'], audience: 'not-expected-audience'})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'jwt audience invalid. expected: not-expected-audience'); }); }); it('should throw if token is expired', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar', exp: 1382412921 }, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: 'shhhhhh', algorithms: ['HS256']})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.inner.name, 'TokenExpiredError'); assert.equal(err.message, 'jwt expired'); }); }); it('should throw if token issuer is wrong', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar', iss: 'http://foo' }, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: 'shhhhhh', algorithms: ['HS256'], issuer: 'http://wrong'})(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'jwt issuer invalid. expected: http://wrong'); }); }); it('should use errors thrown from custom getToken function', function() { var secret = 'shhhhhh'; function getTokenThatThrowsError() { throw new UnauthorizedError('invalid_token', { message: 'Invalid token!' }); } expressjwt({ secret: 'shhhhhh', algorithms: ['HS256'], getToken: getTokenThatThrowsError })(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'Invalid token!'); }); }); it('should throw error when signature is wrong', function() { var secret = "shhh"; var token = jwt.sign({foo: 'bar', iss: 'http://www'}, secret); // manipulate the token var newContent = new Buffer("{foo: 'bar', edg: 'ar'}").toString('base64'); var splitetToken = token.split("."); splitetToken[1] = newContent; var newToken = splitetToken.join("."); // build request req.headers = []; req.headers.authorization = 'Bearer ' + newToken; expressjwt({secret: secret, algorithms: ['HS256']})(req,res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'invalid token'); }); }); it('should throw error if token is expired even with when credentials are not required', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar', exp: 1382412921}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({ secret: secret, credentialsRequired: false, algorithms: ['HS256'] })(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'jwt expired'); }); }); it('should throw error if token is invalid even with when credentials are not required', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar', exp: 1382412921}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({ secret: "not the secret", algorithms: ['HS256'], credentialsRequired: false })(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'invalid_token'); assert.equal(err.message, 'invalid signature'); }); }); }); describe('work tests', function () { var req = {}; var res = {}; it('should work if authorization header is valid jwt', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256']})(req, res, function() { assert.equal('bar', req.user.foo); }); }); it('should work with nested properties', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256'], requestProperty: 'auth.token'})(req, res, function() { assert.equal('bar', req.auth.token.foo); }); }); it('should work if authorization header is valid with a buffer secret', function() { var secret = new Buffer('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'base64'); var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256']})(req, res, function() { assert.equal('bar', req.user.foo); }); }); it('should set userProperty if option provided', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256'], userProperty: 'auth'})(req, res, function() { assert.equal('bar', req.auth.foo); }); }); it('should set resultProperty if option provided', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req = { }; res = { }; req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256'], resultProperty: 'locals.user'})(req, res, function() { assert.equal('bar', res.locals.user.foo); assert.ok(typeof req.user === 'undefined'); }); }); it('should ignore userProperty if resultProperty option provided', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req = { }; res = { }; req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secret, algorithms: ['HS256'], userProperty: 'auth', resultProperty: 'locals.user'})(req, res, function() { assert.equal('bar', res.locals.user.foo); assert.ok(typeof req.auth === 'undefined'); }); }); it('should work if no authorization header and credentials are not required', function() { req = {}; expressjwt({ secret: 'shhhh', algorithms: ['HS256'], credentialsRequired: false })(req, res, function(err) { assert(typeof err === 'undefined'); }); }); it('should not work if no authorization header', function() { req = {}; expressjwt({ secret: 'shhhh', algorithms: ['HS256'] })(req, res, function(err) { assert(typeof err !== 'undefined'); }); }); it('should produce a stack trace that includes the failure reason', function() { var req = {}; var token = jwt.sign({foo: 'bar'}, 'secretA'); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: 'secretB', algorithms: ['HS256']})(req, res, function(err) { var index = err.stack.indexOf('UnauthorizedError: invalid signature') assert.equal(index, 0, "Stack trace didn't include 'invalid signature' message.") }); }); it('should work with a custom getToken function', function() { var secret = 'shhhhhh'; var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.query = {}; req.query.token = token; function getTokenFromQuery(req) { return req.query.token; } expressjwt({ secret: secret, algorithms: ['HS256'], getToken: getTokenFromQuery })(req, res, function() { assert.equal('bar', req.user.foo); }); }); it('should work with a secretCallback function that accepts header argument', function() { var secret = 'shhhhhh'; var secretCallback = function(req, headers, payload, cb) { assert.equal(headers.alg, 'HS256'); assert.equal(payload.foo, 'bar'); process.nextTick(function(){ return cb(null, secret) }); } var token = jwt.sign({foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({secret: secretCallback, algorithms: ['HS256']})(req, res, function() { assert.equal('bar', req.user.foo); }); }); });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express-jwt/test/revocation.test.js
aws/lti-middleware/node_modules/express-jwt/test/revocation.test.js
var jwt = require('jsonwebtoken'); var assert = require('assert'); var expressjwt = require('../lib'); var UnauthorizedError = require('../lib/errors/UnauthorizedError'); describe('revoked jwts', function(){ var secret = 'shhhhhh'; var revoked_id = '1234' var middleware = expressjwt({ secret: secret, algorithms: ['HS256'], isRevoked: function(req, payload, done){ done(null, payload.jti && payload.jti === revoked_id); } }); it('should throw if token is revoked', function(){ var req = {}; var res = {}; var token = jwt.sign({ jti: revoked_id, foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; middleware(req, res, function(err) { assert.ok(err); assert.equal(err.code, 'revoked_token'); assert.equal(err.message, 'The token has been revoked.'); }); }); it('should work if token is not revoked', function(){ var req = {}; var res = {}; var token = jwt.sign({ jti: '1233', foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; middleware(req, res, function() { assert.equal('bar', req.user.foo); }); }); it('should throw if error occurs checking if token is revoked', function(){ var req = {}; var res = {}; var token = jwt.sign({ jti: revoked_id, foo: 'bar'}, secret); req.headers = {}; req.headers.authorization = 'Bearer ' + token; expressjwt({ secret: secret, algorithms: ['HS256'], isRevoked: function(req, payload, done){ done(new Error('An error ocurred')); } })(req, res, function(err) { assert.ok(err); assert.equal(err.message, 'An error ocurred'); }); }); });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express-jwt/lib/index.js
aws/lti-middleware/node_modules/express-jwt/lib/index.js
var jwt = require('jsonwebtoken'); var UnauthorizedError = require('./errors/UnauthorizedError'); var unless = require('express-unless'); var async = require('async'); var set = require('lodash/set'); var DEFAULT_REVOKED_FUNCTION = function(_, __, cb) { return cb(null, false); }; function isFunction(object) { return Object.prototype.toString.call(object) === '[object Function]'; } function wrapStaticSecretInCallback(secret){ return function(_, __, cb){ return cb(null, secret); }; } module.exports = function(options) { if (!options || !options.secret) throw new Error('secret should be set'); if (!options.algorithms) throw new Error('algorithms should be set'); if (!Array.isArray(options.algorithms)) throw new Error('algorithms must be an array'); var secretCallback = options.secret; if (!isFunction(secretCallback)){ secretCallback = wrapStaticSecretInCallback(secretCallback); } var isRevokedCallback = options.isRevoked || DEFAULT_REVOKED_FUNCTION; var _requestProperty = options.userProperty || options.requestProperty || 'user'; var _resultProperty = options.resultProperty; var credentialsRequired = typeof options.credentialsRequired === 'undefined' ? true : options.credentialsRequired; var middleware = function(req, res, next) { var token; if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers')) { var hasAuthInAccessControl = !!~req.headers['access-control-request-headers'] .split(',').map(function (header) { return header.trim(); }).indexOf('authorization'); if (hasAuthInAccessControl) { return next(); } } if (options.getToken && typeof options.getToken === 'function') { try { token = options.getToken(req); } catch (e) { return next(e); } } else if (req.headers && req.headers.authorization) { var parts = req.headers.authorization.split(' '); if (parts.length == 2) { var scheme = parts[0]; var credentials = parts[1]; if (/^Bearer$/i.test(scheme)) { token = credentials; } else { if (credentialsRequired) { return next(new UnauthorizedError('credentials_bad_scheme', { message: 'Format is Authorization: Bearer [token]' })); } else { return next(); } } } else { return next(new UnauthorizedError('credentials_bad_format', { message: 'Format is Authorization: Bearer [token]' })); } } if (!token) { if (credentialsRequired) { return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' })); } else { return next(); } } var dtoken; try { dtoken = jwt.decode(token, { complete: true }) || {}; } catch (err) { return next(new UnauthorizedError('invalid_token', err)); } async.waterfall([ function getSecret(callback){ var arity = secretCallback.length; if (arity == 4) { secretCallback(req, dtoken.header, dtoken.payload, callback); } else { // arity == 3 secretCallback(req, dtoken.payload, callback); } }, function verifyToken(secret, callback) { jwt.verify(token, secret, options, function(err, decoded) { if (err) { callback(new UnauthorizedError('invalid_token', err)); } else { callback(null, decoded); } }); }, function checkRevoked(decoded, callback) { isRevokedCallback(req, dtoken.payload, function (err, revoked) { if (err) { callback(err); } else if (revoked) { callback(new UnauthorizedError('revoked_token', {message: 'The token has been revoked.'})); } else { callback(null, decoded); } }); } ], function (err, result){ if (err) { return next(err); } if (_resultProperty) { set(res, _resultProperty, result); } else { set(req, _requestProperty, result); } next(); }); }; middleware.unless = unless; middleware.UnauthorizedError = UnauthorizedError; return middleware; }; module.exports.UnauthorizedError = UnauthorizedError;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express-jwt/lib/errors/UnauthorizedError.js
aws/lti-middleware/node_modules/express-jwt/lib/errors/UnauthorizedError.js
function UnauthorizedError (code, error) { this.name = "UnauthorizedError"; this.message = error.message; Error.call(this, error.message); Error.captureStackTrace(this, this.constructor); this.code = code; this.status = 401; this.inner = error; } UnauthorizedError.prototype = Object.create(Error.prototype); UnauthorizedError.prototype.constructor = UnauthorizedError; module.exports = UnauthorizedError;
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-concat-iterator/index.js
aws/lti-middleware/node_modules/level-concat-iterator/index.js
'use strict' const { fromCallback } = require('catering') const kPromise = Symbol('promise') module.exports = function (iterator, callback) { callback = fromCallback(callback, kPromise) // Use close() method of abstract-level or end() of abstract-leveldown const close = typeof iterator.close === 'function' ? 'close' : 'end' const entries = [] const onnext = function (err, key, value) { if (err || (key === undefined && value === undefined)) { return iterator[close](function (err2) { callback(err || err2, entries) }) } entries.push({ key, value }) iterator.next(onnext) } iterator.next(onnext) return callback[kPromise] }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/jwa/index.js
aws/lti-middleware/node_modules/jwa/index.js
var bufferEqual = require('buffer-equal-constant-time'); var Buffer = require('safe-buffer').Buffer; var crypto = require('crypto'); var formatEcdsa = require('ecdsa-sig-formatter'); var util = require('util'); var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' var MSG_INVALID_SECRET = 'secret must be a string or buffer'; var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; if (supportsKeyObjects) { MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; MSG_INVALID_SECRET += 'or a KeyObject'; } function checkIsPublicKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return; } if (!supportsKeyObjects) { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key !== 'object') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.type !== 'string') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.asymmetricKeyType !== 'string') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.export !== 'function') { throw typeError(MSG_INVALID_VERIFIER_KEY); } }; function checkIsPrivateKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return; } if (typeof key === 'object') { return; } throw typeError(MSG_INVALID_SIGNER_KEY); }; function checkIsSecretKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return key; } if (!supportsKeyObjects) { throw typeError(MSG_INVALID_SECRET); } if (typeof key !== 'object') { throw typeError(MSG_INVALID_SECRET); } if (key.type !== 'secret') { throw typeError(MSG_INVALID_SECRET); } if (typeof key.export !== 'function') { throw typeError(MSG_INVALID_SECRET); } } function fromBase64(base64) { return base64 .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } function toBase64(base64url) { base64url = base64url.toString(); var padding = 4 - base64url.length % 4; if (padding !== 4) { for (var i = 0; i < padding; ++i) { base64url += '='; } } return base64url .replace(/\-/g, '+') .replace(/_/g, '/'); } function typeError(template) { var args = [].slice.call(arguments, 1); var errMsg = util.format.bind(util, template).apply(null, args); return new TypeError(errMsg); } function bufferOrString(obj) { return Buffer.isBuffer(obj) || typeof obj === 'string'; } function normalizeInput(thing) { if (!bufferOrString(thing)) thing = JSON.stringify(thing); return thing; } function createHmacSigner(bits) { return function sign(thing, secret) { checkIsSecretKey(secret); thing = normalizeInput(thing); var hmac = crypto.createHmac('sha' + bits, secret); var sig = (hmac.update(thing), hmac.digest('base64')) return fromBase64(sig); } } function createHmacVerifier(bits) { return function verify(thing, signature, secret) { var computedSig = createHmacSigner(bits)(thing, secret); return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); } } function createKeySigner(bits) { return function sign(thing, privateKey) { checkIsPrivateKey(privateKey); thing = normalizeInput(thing); // Even though we are specifying "RSA" here, this works with ECDSA // keys as well. var signer = crypto.createSign('RSA-SHA' + bits); var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); return fromBase64(sig); } } function createKeyVerifier(bits) { return function verify(thing, signature, publicKey) { checkIsPublicKey(publicKey); thing = normalizeInput(thing); signature = toBase64(signature); var verifier = crypto.createVerify('RSA-SHA' + bits); verifier.update(thing); return verifier.verify(publicKey, signature, 'base64'); } } function createPSSKeySigner(bits) { return function sign(thing, privateKey) { checkIsPrivateKey(privateKey); thing = normalizeInput(thing); var signer = crypto.createSign('RSA-SHA' + bits); var sig = (signer.update(thing), signer.sign({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, 'base64')); return fromBase64(sig); } } function createPSSKeyVerifier(bits) { return function verify(thing, signature, publicKey) { checkIsPublicKey(publicKey); thing = normalizeInput(thing); signature = toBase64(signature); var verifier = crypto.createVerify('RSA-SHA' + bits); verifier.update(thing); return verifier.verify({ key: publicKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, signature, 'base64'); } } function createECDSASigner(bits) { var inner = createKeySigner(bits); return function sign() { var signature = inner.apply(null, arguments); signature = formatEcdsa.derToJose(signature, 'ES' + bits); return signature; }; } function createECDSAVerifer(bits) { var inner = createKeyVerifier(bits); return function verify(thing, signature, publicKey) { signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); var result = inner(thing, signature, publicKey); return result; }; } function createNoneSigner() { return function sign() { return ''; } } function createNoneVerifier() { return function verify(thing, signature) { return signature === ''; } } module.exports = function jwa(algorithm) { var signerFactories = { hs: createHmacSigner, rs: createKeySigner, ps: createPSSKeySigner, es: createECDSASigner, none: createNoneSigner, } var verifierFactories = { hs: createHmacVerifier, rs: createKeyVerifier, ps: createPSSKeyVerifier, es: createECDSAVerifer, none: createNoneVerifier, } var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); if (!match) throw typeError(MSG_INVALID_ALGORITHM, algorithm); var algo = (match[1] || match[3]).toLowerCase(); var bits = match[2]; return { sign: signerFactories[algo](bits), verify: verifierFactories[algo](bits), } };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/yallist/iterator.js
aws/lti-middleware/node_modules/yallist/iterator.js
'use strict' module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.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/yallist/yallist.js
aws/lti-middleware/node_modules/yallist/yallist.js
'use strict' module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present require('./iterator.js')(Yallist) } catch (er) {}
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/http-errors/index.js
aws/lti-middleware/node_modules/http-errors/index.js
/*! * http-errors * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var deprecate = require('depd')('http-errors') var setPrototypeOf = require('setprototypeof') var statuses = require('statuses') var inherits = require('inherits') var toIdentifier = require('toidentifier') /** * Module exports. * @public */ module.exports = createError module.exports.HttpError = createHttpErrorConstructor() module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) // Populate exports for all constructors populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) /** * Get the code class of a status code. * @private */ function codeClass (status) { return Number(String(status).charAt(0) + '00') } /** * Create a new HTTP Error. * * @returns {Error} * @public */ function createError () { // so much arity going on ~_~ var err var msg var status = 500 var props = {} for (var i = 0; i < arguments.length; i++) { var arg = arguments[i] if (arg instanceof Error) { err = arg status = err.status || err.statusCode || status continue } switch (typeof arg) { case 'string': msg = arg break case 'number': status = arg if (i !== 0) { deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') } break case 'object': props = arg break } } if (typeof status === 'number' && (status < 400 || status >= 600)) { deprecate('non-error status code; use only 4xx or 5xx status codes') } if (typeof status !== 'number' || (!statuses[status] && (status < 400 || status >= 600))) { status = 500 } // constructor var HttpError = createError[status] || createError[codeClass(status)] if (!err) { // create error err = HttpError ? new HttpError(msg) : new Error(msg || statuses[status]) Error.captureStackTrace(err, createError) } if (!HttpError || !(err instanceof HttpError) || err.status !== status) { // add properties to generic error err.expose = status < 500 err.status = err.statusCode = status } for (var key in props) { if (key !== 'status' && key !== 'statusCode') { err[key] = props[key] } } return err } /** * Create HTTP error abstract base class. * @private */ function createHttpErrorConstructor () { function HttpError () { throw new TypeError('cannot construct abstract class') } inherits(HttpError, Error) return HttpError } /** * Create a constructor for a client error. * @private */ function createClientErrorConstructor (HttpError, name, code) { var className = toClassName(name) function ClientError (message) { // create the error object var msg = message != null ? message : statuses[code] var err = new Error(msg) // capture a stack trace to the construction point Error.captureStackTrace(err, ClientError) // adjust the [[Prototype]] setPrototypeOf(err, ClientError.prototype) // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }) // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }) return err } inherits(ClientError, HttpError) nameFunc(ClientError, className) ClientError.prototype.status = code ClientError.prototype.statusCode = code ClientError.prototype.expose = true return ClientError } /** * Create function to test is a value is a HttpError. * @private */ function createIsHttpErrorFunction (HttpError) { return function isHttpError (val) { if (!val || typeof val !== 'object') { return false } if (val instanceof HttpError) { return true } return val instanceof Error && typeof val.expose === 'boolean' && typeof val.statusCode === 'number' && val.status === val.statusCode } } /** * Create a constructor for a server error. * @private */ function createServerErrorConstructor (HttpError, name, code) { var className = toClassName(name) function ServerError (message) { // create the error object var msg = message != null ? message : statuses[code] var err = new Error(msg) // capture a stack trace to the construction point Error.captureStackTrace(err, ServerError) // adjust the [[Prototype]] setPrototypeOf(err, ServerError.prototype) // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }) // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }) return err } inherits(ServerError, HttpError) nameFunc(ServerError, className) ServerError.prototype.status = code ServerError.prototype.statusCode = code ServerError.prototype.expose = false return ServerError } /** * Set the name of a function, if possible. * @private */ function nameFunc (func, name) { var desc = Object.getOwnPropertyDescriptor(func, 'name') if (desc && desc.configurable) { desc.value = name Object.defineProperty(func, 'name', desc) } } /** * Populate the exports object with constructors for every error class. * @private */ function populateConstructorExports (exports, codes, HttpError) { codes.forEach(function forEachCode (code) { var CodeError var name = toIdentifier(statuses[code]) switch (codeClass(code)) { case 400: CodeError = createClientErrorConstructor(HttpError, name, code) break case 500: CodeError = createServerErrorConstructor(HttpError, name, code) break } if (CodeError) { // export the constructor exports[code] = CodeError exports[name] = CodeError } }) // backwards-compatibility exports["I'mateapot"] = deprecate.function(exports.ImATeapot, '"I\'mateapot"; use "ImATeapot" instead') } /** * Get a class name from a name identifier. * @private */ function toClassName (name) { return name.substr(-5) !== 'Error' ? name + 'Error' : name }
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.once/index.js
aws/lti-middleware/node_modules/lodash.once/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 as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * 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'); } /** * 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 _ * @since 4.0.0 * @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'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = once;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/index.js
aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/index.js
/*global exports*/ var SignStream = require('./lib/sign-stream'); var VerifyStream = require('./lib/verify-stream'); var ALGORITHMS = [ 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512' ]; exports.ALGORITHMS = ALGORITHMS; exports.sign = SignStream.sign; exports.verify = VerifyStream.verify; exports.decode = VerifyStream.decode; exports.isValid = VerifyStream.isValid; exports.createSign = function createSign(opts) { return new SignStream(opts); }; exports.createVerify = function createVerify(opts) { return new VerifyStream(opts); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/tostring.js
aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/tostring.js
/*global module*/ var Buffer = require('buffer').Buffer; module.exports = function toString(obj) { if (typeof obj === 'string') return obj; if (typeof obj === 'number' || Buffer.isBuffer(obj)) return obj.toString(); return JSON.stringify(obj); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/sign-stream.js
aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/sign-stream.js
/*global module*/ var Buffer = require('safe-buffer').Buffer; var DataStream = require('./data-stream'); var jwa = require('jwa'); var Stream = require('stream'); var toString = require('./tostring'); var util = require('util'); function base64url(string, encoding) { return Buffer .from(string, encoding) .toString('base64') .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } function jwsSecuredInput(header, payload, encoding) { encoding = encoding || 'utf8'; var encodedHeader = base64url(toString(header), 'binary'); var encodedPayload = base64url(toString(payload), encoding); return util.format('%s.%s', encodedHeader, encodedPayload); } function jwsSign(opts) { var header = opts.header; var payload = opts.payload; var secretOrKey = opts.secret || opts.privateKey; var encoding = opts.encoding; var algo = jwa(header.alg); var securedInput = jwsSecuredInput(header, payload, encoding); var signature = algo.sign(securedInput, secretOrKey); return util.format('%s.%s', securedInput, signature); } function SignStream(opts) { var secret = opts.secret||opts.privateKey||opts.key; var secretStream = new DataStream(secret); this.readable = true; this.header = opts.header; this.encoding = opts.encoding; this.secret = this.privateKey = this.key = secretStream; this.payload = new DataStream(opts.payload); this.secret.once('close', function () { if (!this.payload.writable && this.readable) this.sign(); }.bind(this)); this.payload.once('close', function () { if (!this.secret.writable && this.readable) this.sign(); }.bind(this)); } util.inherits(SignStream, Stream); SignStream.prototype.sign = function sign() { try { var signature = jwsSign({ header: this.header, payload: this.payload.buffer, secret: this.secret.buffer, encoding: this.encoding }); this.emit('done', signature); this.emit('data', signature); this.emit('end'); this.readable = false; return signature; } catch (e) { this.readable = false; this.emit('error', e); this.emit('close'); } }; SignStream.sign = jwsSign; module.exports = SignStream;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/data-stream.js
aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/data-stream.js
/*global module, process*/ var Buffer = require('safe-buffer').Buffer; var Stream = require('stream'); var util = require('util'); function DataStream(data) { this.buffer = null; this.writable = true; this.readable = true; // No input if (!data) { this.buffer = Buffer.alloc(0); return this; } // Stream if (typeof data.pipe === 'function') { this.buffer = Buffer.alloc(0); data.pipe(this); return this; } // Buffer or String // or Object (assumedly a passworded key) if (data.length || typeof data === 'object') { this.buffer = data; this.writable = false; process.nextTick(function () { this.emit('end', data); this.readable = false; this.emit('close'); }.bind(this)); return this; } throw new TypeError('Unexpected data type ('+ typeof data + ')'); } util.inherits(DataStream, Stream); DataStream.prototype.write = function write(data) { this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); this.emit('data', data); }; DataStream.prototype.end = function end(data) { if (data) this.write(data); this.emit('end', data); this.emit('close'); this.writable = false; this.readable = false; }; module.exports = DataStream;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/verify-stream.js
aws/lti-middleware/node_modules/google-auth-library/node_modules/jws/lib/verify-stream.js
/*global module*/ var Buffer = require('safe-buffer').Buffer; var DataStream = require('./data-stream'); var jwa = require('jwa'); var Stream = require('stream'); var toString = require('./tostring'); var util = require('util'); var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; function isObject(thing) { return Object.prototype.toString.call(thing) === '[object Object]'; } function safeJsonParse(thing) { if (isObject(thing)) return thing; try { return JSON.parse(thing); } catch (e) { return undefined; } } function headerFromJWS(jwsSig) { var encodedHeader = jwsSig.split('.', 1)[0]; return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); } function securedInputFromJWS(jwsSig) { return jwsSig.split('.', 2).join('.'); } function signatureFromJWS(jwsSig) { return jwsSig.split('.')[2]; } function payloadFromJWS(jwsSig, encoding) { encoding = encoding || 'utf8'; var payload = jwsSig.split('.')[1]; return Buffer.from(payload, 'base64').toString(encoding); } function isValidJws(string) { return JWS_REGEX.test(string) && !!headerFromJWS(string); } function jwsVerify(jwsSig, algorithm, secretOrKey) { if (!algorithm) { var err = new Error("Missing algorithm parameter for jws.verify"); err.code = "MISSING_ALGORITHM"; throw err; } jwsSig = toString(jwsSig); var signature = signatureFromJWS(jwsSig); var securedInput = securedInputFromJWS(jwsSig); var algo = jwa(algorithm); return algo.verify(securedInput, signature, secretOrKey); } function jwsDecode(jwsSig, opts) { opts = opts || {}; jwsSig = toString(jwsSig); if (!isValidJws(jwsSig)) return null; var header = headerFromJWS(jwsSig); if (!header) return null; var payload = payloadFromJWS(jwsSig); if (header.typ === 'JWT' || opts.json) payload = JSON.parse(payload, opts.encoding); return { header: header, payload: payload, signature: signatureFromJWS(jwsSig) }; } function VerifyStream(opts) { opts = opts || {}; var secretOrKey = opts.secret||opts.publicKey||opts.key; var secretStream = new DataStream(secretOrKey); this.readable = true; this.algorithm = opts.algorithm; this.encoding = opts.encoding; this.secret = this.publicKey = this.key = secretStream; this.signature = new DataStream(opts.signature); this.secret.once('close', function () { if (!this.signature.writable && this.readable) this.verify(); }.bind(this)); this.signature.once('close', function () { if (!this.secret.writable && this.readable) this.verify(); }.bind(this)); } util.inherits(VerifyStream, Stream); VerifyStream.prototype.verify = function verify() { try { var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); var obj = jwsDecode(this.signature.buffer, this.encoding); this.emit('done', valid, obj); this.emit('data', valid); this.emit('end'); this.readable = false; return valid; } catch (e) { this.readable = false; this.emit('error', e); this.emit('close'); } }; VerifyStream.decode = jwsDecode; VerifyStream.isValid = isValidJws; VerifyStream.verify = jwsVerify; module.exports = VerifyStream;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/node_modules/jwa/index.js
aws/lti-middleware/node_modules/google-auth-library/node_modules/jwa/index.js
var bufferEqual = require('buffer-equal-constant-time'); var Buffer = require('safe-buffer').Buffer; var crypto = require('crypto'); var formatEcdsa = require('ecdsa-sig-formatter'); var util = require('util'); var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' var MSG_INVALID_SECRET = 'secret must be a string or buffer'; var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; if (supportsKeyObjects) { MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; MSG_INVALID_SECRET += 'or a KeyObject'; } function checkIsPublicKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return; } if (!supportsKeyObjects) { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key !== 'object') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.type !== 'string') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.asymmetricKeyType !== 'string') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.export !== 'function') { throw typeError(MSG_INVALID_VERIFIER_KEY); } }; function checkIsPrivateKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return; } if (typeof key === 'object') { return; } throw typeError(MSG_INVALID_SIGNER_KEY); }; function checkIsSecretKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return key; } if (!supportsKeyObjects) { throw typeError(MSG_INVALID_SECRET); } if (typeof key !== 'object') { throw typeError(MSG_INVALID_SECRET); } if (key.type !== 'secret') { throw typeError(MSG_INVALID_SECRET); } if (typeof key.export !== 'function') { throw typeError(MSG_INVALID_SECRET); } } function fromBase64(base64) { return base64 .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } function toBase64(base64url) { base64url = base64url.toString(); var padding = 4 - base64url.length % 4; if (padding !== 4) { for (var i = 0; i < padding; ++i) { base64url += '='; } } return base64url .replace(/\-/g, '+') .replace(/_/g, '/'); } function typeError(template) { var args = [].slice.call(arguments, 1); var errMsg = util.format.bind(util, template).apply(null, args); return new TypeError(errMsg); } function bufferOrString(obj) { return Buffer.isBuffer(obj) || typeof obj === 'string'; } function normalizeInput(thing) { if (!bufferOrString(thing)) thing = JSON.stringify(thing); return thing; } function createHmacSigner(bits) { return function sign(thing, secret) { checkIsSecretKey(secret); thing = normalizeInput(thing); var hmac = crypto.createHmac('sha' + bits, secret); var sig = (hmac.update(thing), hmac.digest('base64')) return fromBase64(sig); } } function createHmacVerifier(bits) { return function verify(thing, signature, secret) { var computedSig = createHmacSigner(bits)(thing, secret); return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); } } function createKeySigner(bits) { return function sign(thing, privateKey) { checkIsPrivateKey(privateKey); thing = normalizeInput(thing); // Even though we are specifying "RSA" here, this works with ECDSA // keys as well. var signer = crypto.createSign('RSA-SHA' + bits); var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); return fromBase64(sig); } } function createKeyVerifier(bits) { return function verify(thing, signature, publicKey) { checkIsPublicKey(publicKey); thing = normalizeInput(thing); signature = toBase64(signature); var verifier = crypto.createVerify('RSA-SHA' + bits); verifier.update(thing); return verifier.verify(publicKey, signature, 'base64'); } } function createPSSKeySigner(bits) { return function sign(thing, privateKey) { checkIsPrivateKey(privateKey); thing = normalizeInput(thing); var signer = crypto.createSign('RSA-SHA' + bits); var sig = (signer.update(thing), signer.sign({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, 'base64')); return fromBase64(sig); } } function createPSSKeyVerifier(bits) { return function verify(thing, signature, publicKey) { checkIsPublicKey(publicKey); thing = normalizeInput(thing); signature = toBase64(signature); var verifier = crypto.createVerify('RSA-SHA' + bits); verifier.update(thing); return verifier.verify({ key: publicKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, signature, 'base64'); } } function createECDSASigner(bits) { var inner = createKeySigner(bits); return function sign() { var signature = inner.apply(null, arguments); signature = formatEcdsa.derToJose(signature, 'ES' + bits); return signature; }; } function createECDSAVerifer(bits) { var inner = createKeyVerifier(bits); return function verify(thing, signature, publicKey) { signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); var result = inner(thing, signature, publicKey); return result; }; } function createNoneSigner() { return function sign() { return ''; } } function createNoneVerifier() { return function verify(thing, signature) { return signature === ''; } } module.exports = function jwa(algorithm) { var signerFactories = { hs: createHmacSigner, rs: createKeySigner, ps: createPSSKeySigner, es: createECDSASigner, none: createNoneSigner, } var verifierFactories = { hs: createHmacVerifier, rs: createKeyVerifier, ps: createPSSKeyVerifier, es: createECDSAVerifer, none: createNoneVerifier, } var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); if (!match) throw typeError(MSG_INVALID_ALGORITHM, algorithm); var algo = (match[1] || match[3]).toLowerCase(); var bits = match[2]; return { sign: signerFactories[algo](bits), verify: verifierFactories[algo](bits), } };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/google-auth-library/build/src/index.js
aws/lti-middleware/node_modules/google-auth-library/build/src/index.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.AuthClient = void 0; // 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 googleauth_1 = require("./auth/googleauth"); Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }); var authclient_1 = require("./auth/authclient"); Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return authclient_1.AuthClient; } }); var computeclient_1 = require("./auth/computeclient"); Object.defineProperty(exports, "Compute", { enumerable: true, get: function () { return computeclient_1.Compute; } }); var envDetect_1 = require("./auth/envDetect"); Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } }); var iam_1 = require("./auth/iam"); Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function () { return iam_1.IAMAuth; } }); var idtokenclient_1 = require("./auth/idtokenclient"); Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }); var jwtaccess_1 = require("./auth/jwtaccess"); Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }); var jwtclient_1 = require("./auth/jwtclient"); Object.defineProperty(exports, "JWT", { enumerable: true, get: function () { return jwtclient_1.JWT; } }); var impersonated_1 = require("./auth/impersonated"); Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function () { return impersonated_1.Impersonated; } }); var oauth2client_1 = require("./auth/oauth2client"); Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }); Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }); var loginticket_1 = require("./auth/loginticket"); Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } }); var refreshclient_1 = require("./auth/refreshclient"); Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }); var awsclient_1 = require("./auth/awsclient"); Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function () { return awsclient_1.AwsClient; } }); var identitypoolclient_1 = require("./auth/identitypoolclient"); Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }); var externalclient_1 = require("./auth/externalclient"); Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }); var baseexternalclient_1 = require("./auth/baseexternalclient"); Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }); var downscopedclient_1 = require("./auth/downscopedclient"); Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }); var transporters_1 = require("./transporters"); Object.defineProperty(exports, "DefaultTransporter", { enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }); const auth = new googleauth_1.GoogleAuth(); exports.auth = auth; //# sourceMappingURL=index.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/google-auth-library/build/src/transporters.js
aws/lti-middleware/node_modules/google-auth-library/build/src/transporters.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.DefaultTransporter = void 0; const gaxios_1 = require("gaxios"); const options_1 = require("./options"); // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../../package.json'); const PRODUCT_NAME = 'google-api-nodejs-client'; class DefaultTransporter { /** * Configures request options before making a request. * @param opts GaxiosOptions options. * @return Configured options. */ configure(opts = {}) { opts.headers = opts.headers || {}; if (typeof window === 'undefined') { // set transporter user agent if not in browser const uaValue = opts.headers['User-Agent']; if (!uaValue) { opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT; } else if (!uaValue.includes(`${PRODUCT_NAME}/`)) { opts.headers['User-Agent'] = `${uaValue} ${DefaultTransporter.USER_AGENT}`; } // track google-auth-library-nodejs version: const authVersion = `auth/${pkg.version}`; if (opts.headers['x-goog-api-client'] && !opts.headers['x-goog-api-client'].includes(authVersion)) { opts.headers['x-goog-api-client'] = `${opts.headers['x-goog-api-client']} ${authVersion}`; } else if (!opts.headers['x-goog-api-client']) { const nodeVersion = process.version.replace(/^v/, ''); opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion} ${authVersion}`; } } return opts; } request(opts, callback) { // ensure the user isn't passing in request-style options opts = this.configure(opts); try { (0, options_1.validate)(opts); } catch (e) { if (callback) { return callback(e); } else { throw e; } } if (callback) { (0, gaxios_1.request)(opts).then(r => { callback(null, r); }, e => { callback(this.processError(e)); }); } else { return (0, gaxios_1.request)(opts).catch(e => { throw this.processError(e); }); } } /** * Changes the error to include details from the body. */ processError(e) { const res = e.response; const err = e; const body = res ? res.data : null; if (res && body && body.error && res.status !== 200) { if (typeof body.error === 'string') { err.message = body.error; err.code = res.status.toString(); } else if (Array.isArray(body.error.errors)) { err.message = body.error.errors .map((err2) => err2.message) .join('\n'); err.code = body.error.code; err.errors = body.error.errors; } else { err.message = body.error.message; err.code = body.error.code || res.status; } } else if (res && res.status >= 400) { // Consider all 4xx and 5xx responses errors. err.message = body; err.code = res.status.toString(); } return err; } } exports.DefaultTransporter = DefaultTransporter; /** * Default user agent. */ DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; //# sourceMappingURL=transporters.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/google-auth-library/build/src/messages.js
aws/lti-middleware/node_modules/google-auth-library/build/src/messages.js
"use strict"; // Copyright 2018 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.warn = exports.WarningTypes = void 0; var WarningTypes; (function (WarningTypes) { WarningTypes["WARNING"] = "Warning"; WarningTypes["DEPRECATION"] = "DeprecationWarning"; })(WarningTypes = exports.WarningTypes || (exports.WarningTypes = {})); function warn(warning) { // Only show a given warning once if (warning.warned) { return; } warning.warned = true; if (typeof process !== 'undefined' && process.emitWarning) { // @types/node doesn't recognize the emitWarning syntax which // accepts a config object, so `as any` it is // https://nodejs.org/docs/latest-v8.x/api/process.html#process_process_emitwarning_warning_options // eslint-disable-next-line @typescript-eslint/no-explicit-any process.emitWarning(warning.message, warning); } else { console.warn(warning.message); } } exports.warn = warn; //# sourceMappingURL=messages.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/google-auth-library/build/src/options.js
aws/lti-middleware/node_modules/google-auth-library/build/src/options.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.validate = void 0; // Accepts an options object passed from the user to the API. In the // previous version of the API, it referred to a `Request` options object. // Now it refers to an Axiox Request Config object. This is here to help // ensure users don't pass invalid options when they upgrade from 0.x to 1.x. // eslint-disable-next-line @typescript-eslint/no-explicit-any function validate(options) { const vpairs = [ { invalid: 'uri', expected: 'url' }, { invalid: 'json', expected: 'data' }, { invalid: 'qs', expected: 'params' }, ]; for (const pair of vpairs) { if (options[pair.invalid]) { const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`; throw new Error(e); } } } exports.validate = validate; //# sourceMappingURL=options.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/google-auth-library/build/src/auth/awsclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/awsclient.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.AwsClient = void 0; const awsrequestsigner_1 = require("./awsrequestsigner"); const baseexternalclient_1 = require("./baseexternalclient"); /** * AWS external account client. This is used for AWS workloads, where * AWS STS GetCallerIdentity serialized signed requests are exchanged for * GCP access token. */ class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { /** * Instantiates an AwsClient instance using the provided JSON * object loaded from an external account credentials file. * An error is thrown if the credential is not a valid AWS credential. * @param options The external account options object typically loaded * from the external account JSON credential file. * @param additionalOptions Optional additional behavior customization * options. These currently customize expiration threshold time and * whether to retry on 401/403 API request errors. */ constructor(options, additionalOptions) { var _a; super(options, additionalOptions); this.environmentId = options.credential_source.environment_id; // This is only required if the AWS region is not available in the // AWS_REGION or AWS_DEFAULT_REGION environment variables. this.regionUrl = options.credential_source.region_url; // This is only required if AWS security credentials are not available in // environment variables. this.securityCredentialsUrl = options.credential_source.url; this.regionalCredVerificationUrl = options.credential_source.regional_cred_verification_url; this.imdsV2SessionTokenUrl = options.credential_source.imdsv2_session_token_url; const match = (_a = this.environmentId) === null || _a === void 0 ? void 0 : _a.match(/^(aws)(\d+)$/); if (!match || !this.regionalCredVerificationUrl) { throw new Error('No valid AWS "credential_source" provided'); } else if (parseInt(match[2], 10) !== 1) { throw new Error(`aws version "${match[2]}" is not supported in the current build.`); } this.awsRequestSigner = null; this.region = ''; } /** * Triggered when an external subject token is needed to be exchanged for a * GCP access token via GCP STS endpoint. * This uses the `options.credential_source` object to figure out how * to retrieve the token using the current environment. In this case, * this uses a serialized AWS signed request to the STS GetCallerIdentity * endpoint. * The logic is summarized as: * 1. If imdsv2_session_token_url is provided in the credential source, then * fetch the aws session token and include it in the headers of the * metadata requests. This is a requirement for IDMSv2 but optional * for IDMSv1. * 2. Retrieve AWS region from availability-zone. * 3a. Check AWS credentials in environment variables. If not found, get * from security-credentials endpoint. * 3b. Get AWS credentials from security-credentials endpoint. In order * to retrieve this, the AWS role needs to be determined by calling * security-credentials endpoint without any argument. Then the * credentials can be retrieved via: security-credentials/role_name * 4. Generate the signed request to AWS STS GetCallerIdentity action. * 5. Inject x-goog-cloud-target-resource into header and serialize the * signed request. This will be the subject-token to pass to GCP STS. * @return A promise that resolves with the external subject token. */ async retrieveSubjectToken() { // Initialize AWS request signer if not already initialized. if (!this.awsRequestSigner) { const metadataHeaders = {}; if (this.imdsV2SessionTokenUrl) { metadataHeaders['x-aws-ec2-metadata-token'] = await this.getImdsV2SessionToken(); } this.region = await this.getAwsRegion(metadataHeaders); this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { // Check environment variables for permanent credentials first. // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html if (process.env['AWS_ACCESS_KEY_ID'] && process.env['AWS_SECRET_ACCESS_KEY']) { return { accessKeyId: process.env['AWS_ACCESS_KEY_ID'], secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], // This is normally not available for permanent credentials. token: process.env['AWS_SESSION_TOKEN'], }; } // Since the role on a VM can change, we don't need to cache it. const roleName = await this.getAwsRoleName(metadataHeaders); // Temporary credentials typically last for several hours. // Expiration is returned in response. // Consider future optimization of this logic to cache AWS tokens // until their natural expiration. const awsCreds = await this.getAwsSecurityCredentials(roleName, metadataHeaders); return { accessKeyId: awsCreds.AccessKeyId, secretAccessKey: awsCreds.SecretAccessKey, token: awsCreds.Token, }; }, this.region); } // Generate signed request to AWS STS GetCallerIdentity API. // Use the required regional endpoint. Otherwise, the request will fail. const options = await this.awsRequestSigner.getRequestOptions({ url: this.regionalCredVerificationUrl.replace('{region}', this.region), method: 'POST', }); // The GCP STS endpoint expects the headers to be formatted as: // [ // {key: 'x-amz-date', value: '...'}, // {key: 'Authorization', value: '...'}, // ... // ] // And then serialized as: // encodeURIComponent(JSON.stringify({ // url: '...', // method: 'POST', // headers: [{key: 'x-amz-date', value: '...'}, ...] // })) const reformattedHeader = []; const extendedHeaders = Object.assign({ // The full, canonical resource name of the workload identity pool // provider, with or without the HTTPS prefix. // Including this header as part of the signature is recommended to // ensure data integrity. 'x-goog-cloud-target-resource': this.audience, }, options.headers); // Reformat header to GCP STS expected format. for (const key in extendedHeaders) { reformattedHeader.push({ key, value: extendedHeaders[key], }); } // Serialize the reformatted signed request. return encodeURIComponent(JSON.stringify({ url: options.url, method: options.method, headers: reformattedHeader, })); } /** * @return A promise that resolves with the IMDSv2 Session Token. */ async getImdsV2SessionToken() { const opts = { url: this.imdsV2SessionTokenUrl, method: 'PUT', responseType: 'text', headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, }; const response = await this.transporter.request(opts); return response.data; } /** * @param headers The headers to be used in the metadata request. * @return A promise that resolves with the current AWS region. */ async getAwsRegion(headers) { // Priority order for region determination: // AWS_REGION > AWS_DEFAULT_REGION > metadata server. if (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']) { return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']); } if (!this.regionUrl) { throw new Error('Unable to determine AWS region due to missing ' + '"options.credential_source.region_url"'); } const opts = { url: this.regionUrl, method: 'GET', responseType: 'text', headers: headers, }; const response = await this.transporter.request(opts); // Remove last character. For example, if us-east-2b is returned, // the region would be us-east-2. return response.data.substr(0, response.data.length - 1); } /** * @param headers The headers to be used in the metadata request. * @return A promise that resolves with the assigned role to the current * AWS VM. This is needed for calling the security-credentials endpoint. */ async getAwsRoleName(headers) { if (!this.securityCredentialsUrl) { throw new Error('Unable to determine AWS role name due to missing ' + '"options.credential_source.url"'); } const opts = { url: this.securityCredentialsUrl, method: 'GET', responseType: 'text', headers: headers, }; const response = await this.transporter.request(opts); return response.data; } /** * Retrieves the temporary AWS credentials by calling the security-credentials * endpoint as specified in the `credential_source` object. * @param roleName The role attached to the current VM. * @param headers The headers to be used in the metadata request. * @return A promise that resolves with the temporary AWS credentials * needed for creating the GetCallerIdentity signed request. */ async getAwsSecurityCredentials(roleName, headers) { const response = await this.transporter.request({ url: `${this.securityCredentialsUrl}/${roleName}`, responseType: 'json', headers: headers, }); return response.data; } } exports.AwsClient = AwsClient; //# sourceMappingURL=awsclient.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/google-auth-library/build/src/auth/envDetect.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/envDetect.js
"use strict"; // Copyright 2018 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.getEnv = exports.clear = exports.GCPEnv = void 0; const gcpMetadata = require("gcp-metadata"); var GCPEnv; (function (GCPEnv) { GCPEnv["APP_ENGINE"] = "APP_ENGINE"; GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; GCPEnv["CLOUD_RUN"] = "CLOUD_RUN"; GCPEnv["NONE"] = "NONE"; })(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {})); let envPromise; function clear() { envPromise = undefined; } exports.clear = clear; async function getEnv() { if (envPromise) { return envPromise; } envPromise = getEnvMemoized(); return envPromise; } exports.getEnv = getEnv; async function getEnvMemoized() { let env = GCPEnv.NONE; if (isAppEngine()) { env = GCPEnv.APP_ENGINE; } else if (isCloudFunction()) { env = GCPEnv.CLOUD_FUNCTIONS; } else if (await isComputeEngine()) { if (await isKubernetesEngine()) { env = GCPEnv.KUBERNETES_ENGINE; } else if (isCloudRun()) { env = GCPEnv.CLOUD_RUN; } else { env = GCPEnv.COMPUTE_ENGINE; } } else { env = GCPEnv.NONE; } return env; } function isAppEngine() { return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); } function isCloudFunction() { return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); } /** * This check only verifies that the environment is running knative. * This must be run *after* checking for Kubernetes, otherwise it will * return a false positive. */ function isCloudRun() { return !!process.env.K_CONFIGURATION; } async function isKubernetesEngine() { try { await gcpMetadata.instance('attributes/cluster-name'); return true; } catch (e) { return false; } } async function isComputeEngine() { return gcpMetadata.isAvailable(); } //# sourceMappingURL=envDetect.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/google-auth-library/build/src/auth/jwtclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/jwtclient.js
"use strict"; // Copyright 2013 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.JWT = void 0; const gtoken_1 = require("gtoken"); const jwtaccess_1 = require("./jwtaccess"); const oauth2client_1 = require("./oauth2client"); class JWT extends oauth2client_1.OAuth2Client { constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) { const opts = optionsOrEmail && typeof optionsOrEmail === 'object' ? optionsOrEmail : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject }; super({ eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis, forceRefreshOnFailure: opts.forceRefreshOnFailure, }); this.email = opts.email; this.keyFile = opts.keyFile; this.key = opts.key; this.keyId = opts.keyId; this.scopes = opts.scopes; this.subject = opts.subject; this.additionalClaims = opts.additionalClaims; this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; } /** * Creates a copy of the credential with the specified scopes. * @param scopes List of requested scopes or a single scope. * @return The cloned instance. */ createScoped(scopes) { return new JWT({ email: this.email, keyFile: this.keyFile, key: this.key, keyId: this.keyId, scopes, subject: this.subject, additionalClaims: this.additionalClaims, }); } /** * Obtains the metadata to be sent with the request. * * @param url the URI being authorized. */ async getRequestMetadataAsync(url) { url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; const useSelfSignedJWT = (!this.hasUserScopes() && url) || (this.useJWTAccessWithScope && this.hasAnyScopes()); if (!this.apiKey && useSelfSignedJWT) { if (this.additionalClaims && this.additionalClaims.target_audience) { const { tokens } = await this.refreshToken(); return { headers: this.addSharedMetadataHeaders({ Authorization: `Bearer ${tokens.id_token}`, }), }; } else { // no scopes have been set, but a uri has been provided. Use JWTAccess // credentials. if (!this.access) { this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); } let scopes; if (this.hasUserScopes()) { scopes = this.scopes; } else if (!url) { scopes = this.defaultScopes; } const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, // Scopes take precedent over audience for signing, // so we only provide them if useJWTAccessWithScope is on this.useJWTAccessWithScope ? scopes : undefined); return { headers: this.addSharedMetadataHeaders(headers) }; } } else if (this.hasAnyScopes() || this.apiKey) { return super.getRequestMetadataAsync(url); } else { // If no audience, apiKey, or scopes are provided, we should not attempt // to populate any headers: return { headers: {} }; } } /** * Fetches an ID token. * @param targetAudience the audience for the fetched ID token. */ async fetchIdToken(targetAudience) { // Create a new gToken for fetching an ID token const gtoken = new gtoken_1.GoogleToken({ iss: this.email, sub: this.subject, scope: this.scopes || this.defaultScopes, keyFile: this.keyFile, key: this.key, additionalClaims: { target_audience: targetAudience }, }); await gtoken.getToken({ forceRefresh: true, }); if (!gtoken.idToken) { throw new Error('Unknown error: Failed to fetch ID token'); } return gtoken.idToken; } /** * Determine if there are currently scopes available. */ hasUserScopes() { if (!this.scopes) { return false; } return this.scopes.length > 0; } /** * Are there any default or user scopes defined. */ hasAnyScopes() { if (this.scopes && this.scopes.length > 0) return true; if (this.defaultScopes && this.defaultScopes.length > 0) return true; return false; } authorize(callback) { if (callback) { this.authorizeAsync().then(r => callback(null, r), callback); } else { return this.authorizeAsync(); } } async authorizeAsync() { const result = await this.refreshToken(); if (!result) { throw new Error('No result returned'); } this.credentials = result.tokens; this.credentials.refresh_token = 'jwt-placeholder'; this.key = this.gtoken.key; this.email = this.gtoken.iss; return result.tokens; } /** * Refreshes the access token. * @param refreshToken ignored * @private */ async refreshTokenNoCache( // eslint-disable-next-line @typescript-eslint/no-unused-vars refreshToken) { const gtoken = this.createGToken(); const token = await gtoken.getToken({ forceRefresh: this.isTokenExpiring(), }); const tokens = { access_token: token.access_token, token_type: 'Bearer', expiry_date: gtoken.expiresAt, id_token: gtoken.idToken, }; this.emit('tokens', tokens); return { res: null, tokens }; } /** * Create a gToken if it doesn't already exist. */ createGToken() { if (!this.gtoken) { this.gtoken = new gtoken_1.GoogleToken({ iss: this.email, sub: this.subject, scope: this.scopes || this.defaultScopes, keyFile: this.keyFile, key: this.key, additionalClaims: this.additionalClaims, }); } return this.gtoken; } /** * Create a JWT credentials instance using the given input options. * @param json The input object. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the service account auth settings.'); } if (!json.client_email) { throw new Error('The incoming JSON object does not contain a client_email field'); } if (!json.private_key) { throw new Error('The incoming JSON object does not contain a private_key field'); } // Extract the relevant information from the json key file. this.email = json.client_email; this.key = json.private_key; this.keyId = json.private_key_id; this.projectId = json.project_id; this.quotaProjectId = json.quota_project_id; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { throw new Error('Must pass in a stream containing the service account auth settings.'); } let s = ''; inputStream .setEncoding('utf8') .on('error', reject) .on('data', chunk => (s += chunk)) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); resolve(); } catch (e) { reject(e); } }); }); } /** * Creates a JWT credentials instance using an API Key for authentication. * @param apiKey The API Key in string form. */ fromAPIKey(apiKey) { if (typeof apiKey !== 'string') { throw new Error('Must provide an API Key string.'); } this.apiKey = apiKey; } /** * Using the key or keyFile on the JWT client, obtain an object that contains * the key and the client email. */ async getCredentials() { if (this.key) { return { private_key: this.key, client_email: this.email }; } else if (this.keyFile) { const gtoken = this.createGToken(); const creds = await gtoken.getCredentials(this.keyFile); return { private_key: creds.privateKey, client_email: creds.clientEmail }; } throw new Error('A key or a keyFile must be provided to getCredentials.'); } } exports.JWT = JWT; //# sourceMappingURL=jwtclient.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/google-auth-library/build/src/auth/baseexternalclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/baseexternalclient.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; const stream = require("stream"); const authclient_1 = require("./authclient"); const sts = require("./stscredentials"); /** * The required token exchange grant_type: rfc8693#section-2.1 */ const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; /** * The requested token exchange requested_token_type: rfc8693#section-2.1 */ const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; /** The default OAuth scope to request when none is provided. */ const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; /** The google apis domain pattern. */ const GOOGLE_APIS_DOMAIN_PATTERN = '\\.googleapis\\.com$'; /** The variable portion pattern in a Google APIs domain. */ const VARIABLE_PORTION_PATTERN = '[^\\.\\s\\/\\\\]+'; /** * Offset to take into account network delays and server clock skews. */ exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; /** * The credentials JSON file type for external account clients. * There are 3 types of JSON configs: * 1. authorized_user => Google end user credential * 2. service_account => Google service account credential * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) */ exports.EXTERNAL_ACCOUNT_TYPE = 'external_account'; /** Cloud resource manager URL used to retrieve project information. */ exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/'; /** The workforce audience pattern. */ const WORKFORCE_AUDIENCE_PATTERN = '//iam.googleapis.com/locations/[^/]+/workforcePools/[^/]+/providers/.+'; /** * Base external account client. This is used to instantiate AuthClients for * exchanging external account credentials for GCP access token and authorizing * requests to GCP APIs. * The base class implements common logic for exchanging various type of * external credentials for GCP access token. The logic of determining and * retrieving the external credential based on the environment and * credential_source will be left for the subclasses. */ class BaseExternalAccountClient extends authclient_1.AuthClient { /** * Instantiate a BaseExternalAccountClient instance using the provided JSON * object loaded from an external account credentials file. * @param options The external account options object typically loaded * from the external account JSON credential file. * @param additionalOptions Optional additional behavior customization * options. These currently customize expiration threshold time and * whether to retry on 401/403 API request errors. */ constructor(options, additionalOptions) { super(); if (options.type !== exports.EXTERNAL_ACCOUNT_TYPE) { throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + `received "${options.type}"`); } this.clientAuth = options.client_id ? { confidentialClientType: 'basic', clientId: options.client_id, clientSecret: options.client_secret, } : undefined; if (!this.validateGoogleAPIsUrl('sts', options.token_url)) { throw new Error(`"${options.token_url}" is not a valid token url.`); } this.stsCredential = new sts.StsCredentials(options.token_url, this.clientAuth); // Default OAuth scope. This could be overridden via public property. this.scopes = [DEFAULT_OAUTH_SCOPE]; this.cachedAccessToken = null; this.audience = options.audience; this.subjectTokenType = options.subject_token_type; this.quotaProjectId = options.quota_project_id; this.workforcePoolUserProject = options.workforce_pool_user_project; const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); if (this.workforcePoolUserProject && !this.audience.match(workforceAudiencePattern)) { throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' + 'credentials.'); } if (typeof options.service_account_impersonation_url !== 'undefined' && !this.validateGoogleAPIsUrl('iamcredentials', options.service_account_impersonation_url)) { throw new Error(`"${options.service_account_impersonation_url}" is ` + 'not a valid service account impersonation url.'); } this.serviceAccountImpersonationUrl = options.service_account_impersonation_url; // As threshold could be zero, // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the // zero value. if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') { this.eagerRefreshThresholdMillis = exports.EXPIRATION_TIME_OFFSET; } else { this.eagerRefreshThresholdMillis = additionalOptions .eagerRefreshThresholdMillis; } this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure); this.projectId = null; this.projectNumber = this.getProjectNumber(this.audience); } /** The service account email to be impersonated, if available. */ getServiceAccountEmail() { var _a; if (this.serviceAccountImpersonationUrl) { // Parse email from URL. The formal looks as follows: // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/[email protected]:generateAccessToken const re = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/; const result = re.exec(this.serviceAccountImpersonationUrl); return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null; } return null; } /** * Provides a mechanism to inject GCP access tokens directly. * When the provided credential expires, a new credential, using the * external account options, is retrieved. * @param credentials The Credentials object to set on the current client. */ setCredentials(credentials) { super.setCredentials(credentials); this.cachedAccessToken = credentials; } /** * @return A promise that resolves with the current GCP access token * response. If the current credential is expired, a new one is retrieved. */ async getAccessToken() { // If cached access token is unavailable or expired, force refresh. if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { await this.refreshAccessTokenAsync(); } // Return GCP access token in GetAccessTokenResponse format. return { token: this.cachedAccessToken.access_token, res: this.cachedAccessToken.res, }; } /** * The main authentication interface. It takes an optional url which when * present is the endpoint being accessed, and returns a Promise which * resolves with authorization header fields. * * The result has the form: * { Authorization: 'Bearer <access_token_value>' } */ async getRequestHeaders() { const accessTokenResponse = await this.getAccessToken(); const headers = { Authorization: `Bearer ${accessTokenResponse.token}`, }; return this.addSharedMetadataHeaders(headers); } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } /** * @return A promise that resolves with the project ID corresponding to the * current workload identity pool or current workforce pool if * determinable. For workforce pool credential, it returns the project ID * corresponding to the workforcePoolUserProject. * This is introduced to match the current pattern of using the Auth * library: * const projectId = await auth.getProjectId(); * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; * const res = await client.request({ url }); * The resource may not have permission * (resourcemanager.projects.get) to call this API or the required * scopes may not be selected: * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes */ async getProjectId() { const projectNumber = this.projectNumber || this.workforcePoolUserProject; if (this.projectId) { // Return previously determined project ID. return this.projectId; } else if (projectNumber) { // Preferable not to use request() to avoid retrial policies. const headers = await this.getRequestHeaders(); const response = await this.transporter.request({ headers, url: `${exports.CLOUD_RESOURCE_MANAGER}${projectNumber}`, responseType: 'json', }); this.projectId = response.data.projectId; return this.projectId; } return null; } /** * Authenticates the provided HTTP request, processes it and resolves with the * returned response. * @param opts The HTTP request options. * @param retry Whether the current attempt is a retry after a failed attempt. * @return A promise that resolves with the successful response. */ async requestAsync(opts, retry = false) { let response; try { const requestHeaders = await this.getRequestHeaders(); opts.headers = opts.headers || {}; if (requestHeaders && requestHeaders['x-goog-user-project']) { opts.headers['x-goog-user-project'] = requestHeaders['x-goog-user-project']; } if (requestHeaders && requestHeaders.Authorization) { opts.headers.Authorization = requestHeaders.Authorization; } response = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - forceRefreshOnFailure is true const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!retry && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { await this.refreshAccessTokenAsync(); return await this.requestAsync(opts, true); } } throw e; } return response; } /** * Forces token refresh, even if unexpired tokens are currently cached. * External credentials are exchanged for GCP access tokens via the token * exchange endpoint and other settings provided in the client options * object. * If the service_account_impersonation_url is provided, an additional * step to exchange the external account GCP access token for a service * account impersonated token is performed. * @return A promise that resolves with the fresh GCP access tokens. */ async refreshAccessTokenAsync() { // Retrieve the external credential. const subjectToken = await this.retrieveSubjectToken(); // Construct the STS credentials options. const stsCredentialsOptions = { grantType: STS_GRANT_TYPE, audience: this.audience, requestedTokenType: STS_REQUEST_TOKEN_TYPE, subjectToken, subjectTokenType: this.subjectTokenType, // generateAccessToken requires the provided access token to have // scopes: // https://www.googleapis.com/auth/iam or // https://www.googleapis.com/auth/cloud-platform // The new service account access token scopes will match the user // provided ones. scope: this.serviceAccountImpersonationUrl ? [DEFAULT_OAUTH_SCOPE] : this.getScopesArray(), }; // Exchange the external credentials for a GCP access token. // Client auth is prioritized over passing the workforcePoolUserProject // parameter for STS token exchange. const additionalOptions = !this.clientAuth && this.workforcePoolUserProject ? { userProject: this.workforcePoolUserProject } : undefined; const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, additionalOptions); if (this.serviceAccountImpersonationUrl) { this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); } else if (stsResponse.expires_in) { // Save response in cached access token. this.cachedAccessToken = { access_token: stsResponse.access_token, expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, res: stsResponse.res, }; } else { // Save response in cached access token. this.cachedAccessToken = { access_token: stsResponse.access_token, res: stsResponse.res, }; } // Save credentials. this.credentials = {}; Object.assign(this.credentials, this.cachedAccessToken); delete this.credentials.res; // Trigger tokens event to notify external listeners. this.emit('tokens', { refresh_token: null, expiry_date: this.cachedAccessToken.expiry_date, access_token: this.cachedAccessToken.access_token, token_type: 'Bearer', id_token: null, }); // Return the cached access token. return this.cachedAccessToken; } /** * Returns the workload identity pool project number if it is determinable * from the audience resource name. * @param audience The STS audience used to determine the project number. * @return The project number associated with the workload identity pool, if * this can be determined from the STS audience field. Otherwise, null is * returned. */ getProjectNumber(audience) { // STS audience pattern: // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/... const match = audience.match(/\/projects\/([^/]+)/); if (!match) { return null; } return match[1]; } /** * Exchanges an external account GCP access token for a service * account impersonated access token using iamcredentials * GenerateAccessToken API. * @param token The access token to exchange for a service account access * token. * @return A promise that resolves with the service account impersonated * credentials response. */ async getImpersonatedAccessToken(token) { const opts = { url: this.serviceAccountImpersonationUrl, method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, data: { scope: this.getScopesArray(), }, responseType: 'json', }; const response = await this.transporter.request(opts); const successResponse = response.data; return { access_token: successResponse.accessToken, // Convert from ISO format to timestamp. expiry_date: new Date(successResponse.expireTime).getTime(), res: response, }; } /** * Returns whether the provided credentials are expired or not. * If there is no expiry time, assumes the token is not expired or expiring. * @param accessToken The credentials to check for expiration. * @return Whether the credentials are expired or not. */ isExpired(accessToken) { const now = new Date().getTime(); return accessToken.expiry_date ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis : false; } /** * @return The list of scopes for the requested GCP access token. */ getScopesArray() { // Since scopes can be provided as string or array, the type should // be normalized. if (typeof this.scopes === 'string') { return [this.scopes]; } else if (typeof this.scopes === 'undefined') { return [DEFAULT_OAUTH_SCOPE]; } else { return this.scopes; } } /** * Checks whether Google APIs URL is valid. * @param apiName The apiName of url. * @param url The Google API URL to validate. * @return Whether the URL is valid or not. */ validateGoogleAPIsUrl(apiName, url) { let parsedUrl; // Return false if error is thrown during parsing URL. try { parsedUrl = new URL(url); } catch (e) { return false; } const urlDomain = parsedUrl.hostname; // Check the protocol is https. if (parsedUrl.protocol !== 'https:') { return false; } const googleAPIsDomainPatterns = [ new RegExp('^' + VARIABLE_PORTION_PATTERN + '\\.' + apiName + GOOGLE_APIS_DOMAIN_PATTERN), new RegExp('^' + apiName + GOOGLE_APIS_DOMAIN_PATTERN), new RegExp('^' + apiName + '\\.' + VARIABLE_PORTION_PATTERN + GOOGLE_APIS_DOMAIN_PATTERN), new RegExp('^' + VARIABLE_PORTION_PATTERN + '\\-' + apiName + GOOGLE_APIS_DOMAIN_PATTERN), ]; for (const googleAPIsDomainPattern of googleAPIsDomainPatterns) { if (urlDomain.match(googleAPIsDomainPattern)) { return true; } } return false; } } exports.BaseExternalAccountClient = BaseExternalAccountClient; //# sourceMappingURL=baseexternalclient.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/google-auth-library/build/src/auth/jwtaccess.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/jwtaccess.js
"use strict"; // Copyright 2015 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.JWTAccess = void 0; const jws = require("jws"); const LRU = require("lru-cache"); const DEFAULT_HEADER = { alg: 'RS256', typ: 'JWT', }; class JWTAccess { /** * JWTAccess service account credentials. * * Create a new access token by using the credential to create a new JWT token * that's recognized as the access token. * * @param email the service account email address. * @param key the private key that will be used to sign the token. * @param keyId the ID of the private key used to sign the token. */ constructor(email, key, keyId, eagerRefreshThresholdMillis) { this.cache = new LRU({ max: 500, maxAge: 60 * 60 * 1000, }); this.email = email; this.key = key; this.keyId = keyId; this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000; } /** * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url * * @param url The URI being authorized. * @param scopes The scope or scopes being authorized * @returns A string that returns the cached key. */ getCachedKey(url, scopes) { let cacheKey = url; if (scopes && Array.isArray(scopes) && scopes.length) { cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`; } else if (typeof scopes === 'string') { cacheKey = url ? `${url}_${scopes}` : scopes; } if (!cacheKey) { throw Error('Scopes or url must be provided'); } return cacheKey; } /** * Get a non-expired access token, after refreshing if necessary. * * @param url The URI being authorized. * @param additionalClaims An object with a set of additional claims to * include in the payload. * @returns An object that includes the authorization header. */ getRequestHeaders(url, additionalClaims, scopes) { // Return cached authorization headers, unless we are within // eagerRefreshThresholdMillis ms of them expiring: const key = this.getCachedKey(url, scopes); const cachedToken = this.cache.get(key); const now = Date.now(); if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { return cachedToken.headers; } const iat = Math.floor(Date.now() / 1000); const exp = JWTAccess.getExpirationTime(iat); let defaultClaims; // Turn scopes into space-separated string if (Array.isArray(scopes)) { scopes = scopes.join(' '); } // If scopes are specified, sign with scopes if (scopes) { defaultClaims = { iss: this.email, sub: this.email, scope: scopes, exp, iat, }; } else { defaultClaims = { iss: this.email, sub: this.email, aud: url, exp, iat, }; } // if additionalClaims are provided, ensure they do not collide with // other required claims. if (additionalClaims) { for (const claim in defaultClaims) { if (additionalClaims[claim]) { throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); } } } const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER; const payload = Object.assign(defaultClaims, additionalClaims); // Sign the jwt and add it to the cache const signedJWT = jws.sign({ header, payload, secret: this.key }); const headers = { Authorization: `Bearer ${signedJWT}` }; this.cache.set(key, { expiration: exp * 1000, headers, }); return headers; } /** * Returns an expiration time for the JWT token. * * @param iat The issued at time for the JWT. * @returns An expiration time for the JWT. */ static getExpirationTime(iat) { const exp = iat + 3600; // 3600 seconds = 1 hour return exp; } /** * Create a JWTAccess credentials instance using the given input options. * @param json The input object. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the service account auth settings.'); } if (!json.client_email) { throw new Error('The incoming JSON object does not contain a client_email field'); } if (!json.private_key) { throw new Error('The incoming JSON object does not contain a private_key field'); } // Extract the relevant information from the json key file. this.email = json.client_email; this.key = json.private_key; this.keyId = json.private_key_id; this.projectId = json.project_id; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { reject(new Error('Must pass in a stream containing the service account auth settings.')); } let s = ''; inputStream .setEncoding('utf8') .on('data', chunk => (s += chunk)) .on('error', reject) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); resolve(); } catch (err) { reject(err); } }); }); } } exports.JWTAccess = JWTAccess; //# sourceMappingURL=jwtaccess.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/google-auth-library/build/src/auth/awsrequestsigner.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.AwsRequestSigner = void 0; const crypto_1 = require("../crypto/crypto"); /** AWS Signature Version 4 signing algorithm identifier. */ const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; /** * The termination string for the AWS credential scope value as defined in * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html */ const AWS_REQUEST_TYPE = 'aws4_request'; /** * Implements an AWS API request signer based on the AWS Signature Version 4 * signing process. * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html */ class AwsRequestSigner { /** * Instantiates an AWS API request signer used to send authenticated signed * requests to AWS APIs based on the AWS Signature Version 4 signing process. * This also provides a mechanism to generate the signed request without * sending it. * @param getCredentials A mechanism to retrieve AWS security credentials * when needed. * @param region The AWS region to use. */ constructor(getCredentials, region) { this.getCredentials = getCredentials; this.region = region; this.crypto = (0, crypto_1.createCrypto)(); } /** * Generates the signed request for the provided HTTP request for calling * an AWS API. This follows the steps described at: * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html * @param amzOptions The AWS request options that need to be signed. * @return A promise that resolves with the GaxiosOptions containing the * signed HTTP request parameters. */ async getRequestOptions(amzOptions) { if (!amzOptions.url) { throw new Error('"url" is required in "amzOptions"'); } // Stringify JSON requests. This will be set in the request body of the // generated signed request. const requestPayloadData = typeof amzOptions.data === 'object' ? JSON.stringify(amzOptions.data) : amzOptions.data; const url = amzOptions.url; const method = amzOptions.method || 'GET'; const requestPayload = amzOptions.body || requestPayloadData; const additionalAmzHeaders = amzOptions.headers; const awsSecurityCredentials = await this.getCredentials(); const uri = new URL(url); const headerMap = await generateAuthenticationHeaderMap({ crypto: this.crypto, host: uri.host, canonicalUri: uri.pathname, canonicalQuerystring: uri.search.substr(1), method, region: this.region, securityCredentials: awsSecurityCredentials, requestPayload, additionalAmzHeaders, }); // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. const headers = Object.assign( // Add x-amz-date if available. headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { Authorization: headerMap.authorizationHeader, host: uri.host, }, additionalAmzHeaders || {}); if (awsSecurityCredentials.token) { Object.assign(headers, { 'x-amz-security-token': awsSecurityCredentials.token, }); } const awsSignedReq = { url, method: method, headers, }; if (typeof requestPayload !== 'undefined') { awsSignedReq.body = requestPayload; } return awsSignedReq; } } exports.AwsRequestSigner = AwsRequestSigner; /** * Creates the HMAC-SHA256 hash of the provided message using the * provided key. * * @param crypto The crypto instance used to facilitate cryptographic * operations. * @param key The HMAC-SHA256 key to use. * @param msg The message to hash. * @return The computed hash bytes. */ async function sign(crypto, key, msg) { return await crypto.signWithHmacSha256(key, msg); } /** * Calculates the signing key used to calculate the signature for * AWS Signature Version 4 based on: * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html * * @param crypto The crypto instance used to facilitate cryptographic * operations. * @param key The AWS secret access key. * @param dateStamp The '%Y%m%d' date format. * @param region The AWS region. * @param serviceName The AWS service name, eg. sts. * @return The signing key bytes. */ async function getSigningKey(crypto, key, dateStamp, region, serviceName) { const kDate = await sign(crypto, `AWS4${key}`, dateStamp); const kRegion = await sign(crypto, kDate, region); const kService = await sign(crypto, kRegion, serviceName); const kSigning = await sign(crypto, kService, 'aws4_request'); return kSigning; } /** * Generates the authentication header map needed for generating the AWS * Signature Version 4 signed request. * * @param option The options needed to compute the authentication header map. * @return The AWS authentication header map which constitutes of the following * components: amz-date, authorization header and canonical query string. */ async function generateAuthenticationHeaderMap(options) { const additionalAmzHeaders = options.additionalAmzHeaders || {}; const requestPayload = options.requestPayload || ''; // iam.amazonaws.com host => iam service. // sts.us-east-2.amazonaws.com => sts service. const serviceName = options.host.split('.')[0]; const now = new Date(); // Format: '%Y%m%dT%H%M%SZ'. const amzDate = now .toISOString() .replace(/[-:]/g, '') .replace(/\.[0-9]+/, ''); // Format: '%Y%m%d'. const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); // Change all additional headers to be lower case. const reformattedAdditionalAmzHeaders = {}; Object.keys(additionalAmzHeaders).forEach(key => { reformattedAdditionalAmzHeaders[key.toLowerCase()] = additionalAmzHeaders[key]; }); // Add AWS token if available. if (options.securityCredentials.token) { reformattedAdditionalAmzHeaders['x-amz-security-token'] = options.securityCredentials.token; } // Header keys need to be sorted alphabetically. const amzHeaders = Object.assign({ host: options.host, }, // Previously the date was not fixed with x-amz- and could be provided manually. // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders); let canonicalHeaders = ''; const signedHeadersList = Object.keys(amzHeaders).sort(); signedHeadersList.forEach(key => { canonicalHeaders += `${key}:${amzHeaders[key]}\n`; }); const signedHeaders = signedHeadersList.join(';'); const payloadHash = await options.crypto.sha256DigestHex(requestPayload); // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html const canonicalRequest = `${options.method}\n` + `${options.canonicalUri}\n` + `${options.canonicalQuerystring}\n` + `${canonicalHeaders}\n` + `${signedHeaders}\n` + `${payloadHash}`; const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html const stringToSign = `${AWS_ALGORITHM}\n` + `${amzDate}\n` + `${credentialScope}\n` + (await options.crypto.sha256DigestHex(canonicalRequest)); // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); const signature = await sign(options.crypto, signingKey, stringToSign); // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; return { // Do not return x-amz-date if date is available. amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate, authorizationHeader, canonicalQuerystring: options.canonicalQuerystring, }; } //# sourceMappingURL=awsrequestsigner.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/google-auth-library/build/src/auth/identitypoolclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/identitypoolclient.js
"use strict"; // 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. var _a, _b, _c; Object.defineProperty(exports, "__esModule", { value: true }); exports.IdentityPoolClient = void 0; const fs = require("fs"); const util_1 = require("util"); const baseexternalclient_1 = require("./baseexternalclient"); // fs.readfile is undefined in browser karma tests causing // `npm run browser-test` to fail as test.oauth2.ts imports this file via // src/index.ts. // Fallback to void function to avoid promisify throwing a TypeError. const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { })); const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { })); const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { })); /** * Defines the Url-sourced and file-sourced external account clients mainly * used for K8s and Azure workloads. */ class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { /** * Instantiate an IdentityPoolClient instance using the provided JSON * object loaded from an external account credentials file. * An error is thrown if the credential is not a valid file-sourced or * url-sourced credential or a workforce pool user project is provided * with a non workforce audience. * @param options The external account options object typically loaded * from the external account JSON credential file. * @param additionalOptions Optional additional behavior customization * options. These currently customize expiration threshold time and * whether to retry on 401/403 API request errors. */ constructor(options, additionalOptions) { var _a, _b; super(options, additionalOptions); this.file = options.credential_source.file; this.url = options.credential_source.url; this.headers = options.credential_source.headers; if (!this.file && !this.url) { throw new Error('No valid Identity Pool "credential_source" provided'); } // Text is the default format type. this.formatType = ((_a = options.credential_source.format) === null || _a === void 0 ? void 0 : _a.type) || 'text'; this.formatSubjectTokenFieldName = (_b = options.credential_source.format) === null || _b === void 0 ? void 0 : _b.subject_token_field_name; if (this.formatType !== 'json' && this.formatType !== 'text') { throw new Error(`Invalid credential_source format "${this.formatType}"`); } if (this.formatType === 'json' && !this.formatSubjectTokenFieldName) { throw new Error('Missing subject_token_field_name for JSON credential_source format'); } } /** * Triggered when a external subject token is needed to be exchanged for a GCP * access token via GCP STS endpoint. * This uses the `options.credential_source` object to figure out how * to retrieve the token using the current environment. In this case, * this either retrieves the local credential from a file location (k8s * workload) or by sending a GET request to a local metadata server (Azure * workloads). * @return A promise that resolves with the external subject token. */ async retrieveSubjectToken() { if (this.file) { return await this.getTokenFromFile(this.file, this.formatType, this.formatSubjectTokenFieldName); } return await this.getTokenFromUrl(this.url, this.formatType, this.formatSubjectTokenFieldName, this.headers); } /** * Looks up the external subject token in the file path provided and * resolves with that token. * @param file The file path where the external credential is located. * @param formatType The token file or URL response type (JSON or text). * @param formatSubjectTokenFieldName For JSON response types, this is the * subject_token field name. For Azure, this is access_token. For text * response types, this is ignored. * @return A promise that resolves with the external subject token. */ async getTokenFromFile(filePath, formatType, formatSubjectTokenFieldName) { // Make sure there is a file at the path. lstatSync will throw if there is // nothing there. try { // Resolve path to actual file in case of symlink. Expect a thrown error // if not resolvable. filePath = await realpath(filePath); if (!(await lstat(filePath)).isFile()) { throw new Error(); } } catch (err) { if (err instanceof Error) { err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; } throw err; } let subjectToken; const rawText = await readFile(filePath, { encoding: 'utf8' }); if (formatType === 'text') { subjectToken = rawText; } else if (formatType === 'json' && formatSubjectTokenFieldName) { const json = JSON.parse(rawText); subjectToken = json[formatSubjectTokenFieldName]; } if (!subjectToken) { throw new Error('Unable to parse the subject_token from the credential_source file'); } return subjectToken; } /** * Sends a GET request to the URL provided and resolves with the returned * external subject token. * @param url The URL to call to retrieve the subject token. This is typically * a local metadata server. * @param formatType The token file or URL response type (JSON or text). * @param formatSubjectTokenFieldName For JSON response types, this is the * subject_token field name. For Azure, this is access_token. For text * response types, this is ignored. * @param headers The optional additional headers to send with the request to * the metadata server url. * @return A promise that resolves with the external subject token. */ async getTokenFromUrl(url, formatType, formatSubjectTokenFieldName, headers) { const opts = { url, method: 'GET', headers, responseType: formatType, }; let subjectToken; if (formatType === 'text') { const response = await this.transporter.request(opts); subjectToken = response.data; } else if (formatType === 'json' && formatSubjectTokenFieldName) { const response = await this.transporter.request(opts); subjectToken = response.data[formatSubjectTokenFieldName]; } if (!subjectToken) { throw new Error('Unable to parse the subject_token from the credential_source URL'); } return subjectToken; } } exports.IdentityPoolClient = IdentityPoolClient; //# sourceMappingURL=identitypoolclient.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/google-auth-library/build/src/auth/externalclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/externalclient.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.ExternalAccountClient = void 0; const baseexternalclient_1 = require("./baseexternalclient"); const identitypoolclient_1 = require("./identitypoolclient"); const awsclient_1 = require("./awsclient"); /** * Dummy class with no constructor. Developers are expected to use fromJSON. */ class ExternalAccountClient { constructor() { throw new Error('ExternalAccountClients should be initialized via: ' + 'ExternalAccountClient.fromJSON(), ' + 'directly via explicit constructors, eg. ' + 'new AwsClient(options), new IdentityPoolClient(options) or via ' + 'new GoogleAuth(options).getClient()'); } /** * This static method will instantiate the * corresponding type of external account credential depending on the * underlying credential source. * @param options The external account options object typically loaded * from the external account JSON credential file. * @param additionalOptions Optional additional behavior customization * options. These currently customize expiration threshold time and * whether to retry on 401/403 API request errors. * @return A BaseExternalAccountClient instance or null if the options * provided do not correspond to an external account credential. */ static fromJSON(options, additionalOptions) { var _a; if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) { return new awsclient_1.AwsClient(options, additionalOptions); } else { return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions); } } else { return null; } } } exports.ExternalAccountClient = ExternalAccountClient; //# sourceMappingURL=externalclient.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/google-auth-library/build/src/auth/oauth2common.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/oauth2common.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.getErrorFromOAuthErrorResponse = exports.OAuthClientAuthHandler = void 0; const querystring = require("querystring"); const crypto_1 = require("../crypto/crypto"); /** List of HTTP methods that accept request bodies. */ const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH']; /** * Abstract class for handling client authentication in OAuth-based * operations. * When request-body client authentication is used, only application/json and * application/x-www-form-urlencoded content types for HTTP methods that support * request bodies are supported. */ class OAuthClientAuthHandler { /** * Instantiates an OAuth client authentication handler. * @param clientAuthentication The client auth credentials. */ constructor(clientAuthentication) { this.clientAuthentication = clientAuthentication; this.crypto = (0, crypto_1.createCrypto)(); } /** * Applies client authentication on the OAuth request's headers or POST * body but does not process the request. * @param opts The GaxiosOptions whose headers or data are to be modified * depending on the client authentication mechanism to be used. * @param bearerToken The optional bearer token to use for authentication. * When this is used, no client authentication credentials are needed. */ applyClientAuthenticationOptions(opts, bearerToken) { // Inject authenticated header. this.injectAuthenticatedHeaders(opts, bearerToken); // Inject authenticated request body. if (!bearerToken) { this.injectAuthenticatedRequestBody(opts); } } /** * Applies client authentication on the request's header if either * basic authentication or bearer token authentication is selected. * * @param opts The GaxiosOptions whose headers or data are to be modified * depending on the client authentication mechanism to be used. * @param bearerToken The optional bearer token to use for authentication. * When this is used, no client authentication credentials are needed. */ injectAuthenticatedHeaders(opts, bearerToken) { var _a; // Bearer token prioritized higher than basic Auth. if (bearerToken) { opts.headers = opts.headers || {}; Object.assign(opts.headers, { Authorization: `Bearer ${bearerToken}}`, }); } else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') { opts.headers = opts.headers || {}; const clientId = this.clientAuthentication.clientId; const clientSecret = this.clientAuthentication.clientSecret || ''; const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); Object.assign(opts.headers, { Authorization: `Basic ${base64EncodedCreds}`, }); } } /** * Applies client authentication on the request's body if request-body * client authentication is selected. * * @param opts The GaxiosOptions whose headers or data are to be modified * depending on the client authentication mechanism to be used. */ injectAuthenticatedRequestBody(opts) { var _a; if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') { const method = (opts.method || 'GET').toUpperCase(); // Inject authenticated request body. if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) { // Get content-type. let contentType; const headers = opts.headers || {}; for (const key in headers) { if (key.toLowerCase() === 'content-type' && headers[key]) { contentType = headers[key].toLowerCase(); break; } } if (contentType === 'application/x-www-form-urlencoded') { opts.data = opts.data || ''; const data = querystring.parse(opts.data); Object.assign(data, { client_id: this.clientAuthentication.clientId, client_secret: this.clientAuthentication.clientSecret || '', }); opts.data = querystring.stringify(data); } else if (contentType === 'application/json') { opts.data = opts.data || {}; Object.assign(opts.data, { client_id: this.clientAuthentication.clientId, client_secret: this.clientAuthentication.clientSecret || '', }); } else { throw new Error(`${contentType} content-types are not supported with ` + `${this.clientAuthentication.confidentialClientType} ` + 'client authentication'); } } else { throw new Error(`${method} HTTP method does not support ` + `${this.clientAuthentication.confidentialClientType} ` + 'client authentication'); } } } } exports.OAuthClientAuthHandler = OAuthClientAuthHandler; /** * Converts an OAuth error response to a native JavaScript Error. * @param resp The OAuth error response to convert to a native Error object. * @param err The optional original error. If provided, the error properties * will be copied to the new error. * @return The converted native Error object. */ function getErrorFromOAuthErrorResponse(resp, err) { // Error response. const errorCode = resp.error; const errorDescription = resp.error_description; const errorUri = resp.error_uri; let message = `Error code ${errorCode}`; if (typeof errorDescription !== 'undefined') { message += `: ${errorDescription}`; } if (typeof errorUri !== 'undefined') { message += ` - ${errorUri}`; } const newError = new Error(message); // Copy properties from original error to newly generated error. if (err) { const keys = Object.keys(err); if (err.stack) { // Copy error.stack if available. keys.push('stack'); } keys.forEach(key => { // Do not overwrite the message field. if (key !== 'message') { Object.defineProperty(newError, key, { // eslint-disable-next-line @typescript-eslint/no-explicit-any value: err[key], writable: false, enumerable: true, }); } }); } return newError; } exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; //# sourceMappingURL=oauth2common.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/google-auth-library/build/src/auth/googleauth.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/googleauth.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.GoogleAuth = exports.CLOUD_SDK_CLIENT_ID = void 0; const child_process_1 = require("child_process"); const fs = require("fs"); const gcpMetadata = require("gcp-metadata"); const os = require("os"); const path = require("path"); const crypto_1 = require("../crypto/crypto"); const transporters_1 = require("../transporters"); const computeclient_1 = require("./computeclient"); const idtokenclient_1 = require("./idtokenclient"); const envDetect_1 = require("./envDetect"); const jwtclient_1 = require("./jwtclient"); const refreshclient_1 = require("./refreshclient"); const externalclient_1 = require("./externalclient"); const baseexternalclient_1 = require("./baseexternalclient"); exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com'; class GoogleAuth { constructor(opts) { /** * Caches a value indicating whether the auth layer is running on Google * Compute Engine. * @private */ this.checkIsGCE = undefined; // To save the contents of the JSON credential file this.jsonContent = null; this.cachedCredential = null; opts = opts || {}; this._cachedProjectId = opts.projectId || null; this.cachedCredential = opts.authClient || null; this.keyFilename = opts.keyFilename || opts.keyFile; this.scopes = opts.scopes; this.jsonContent = opts.credentials || null; this.clientOptions = opts.clientOptions; } // Note: this properly is only public to satisify unit tests. // https://github.com/Microsoft/TypeScript/issues/5228 get isGCE() { return this.checkIsGCE; } // GAPIC client libraries should always use self-signed JWTs. The following // variables are set on the JWT client in order to indicate the type of library, // and sign the JWT with the correct audience and scopes (if not supplied). setGapicJWTValues(client) { client.defaultServicePath = this.defaultServicePath; client.useJWTAccessWithScope = this.useJWTAccessWithScope; client.defaultScopes = this.defaultScopes; } getProjectId(callback) { if (callback) { this.getProjectIdAsync().then(r => callback(null, r), callback); } else { return this.getProjectIdAsync(); } } getProjectIdAsync() { if (this._cachedProjectId) { return Promise.resolve(this._cachedProjectId); } // In implicit case, supports three environments. In order of precedence, // the implicit environments are: // - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable // - GOOGLE_APPLICATION_CREDENTIALS JSON file // - Cloud SDK: `gcloud config config-helper --format json` // - GCE project ID from metadata server) if (!this._getDefaultProjectIdPromise) { // TODO: refactor the below code so that it doesn't mix and match // promises and async/await. this._getDefaultProjectIdPromise = new Promise( // eslint-disable-next-line no-async-promise-executor async (resolve, reject) => { try { const projectId = this.getProductionProjectId() || (await this.getFileProjectId()) || (await this.getDefaultServiceProjectId()) || (await this.getGCEProjectId()) || (await this.getExternalAccountClientProjectId()); this._cachedProjectId = projectId; if (!projectId) { throw new Error('Unable to detect a Project Id in the current environment. \n' + 'To learn more about authentication and Google APIs, visit: \n' + 'https://cloud.google.com/docs/authentication/getting-started'); } resolve(projectId); } catch (e) { reject(e); } }); } return this._getDefaultProjectIdPromise; } /** * @returns Any scopes (user-specified or default scopes specified by the * client library) that need to be set on the current Auth client. */ getAnyScopes() { return this.scopes || this.defaultScopes; } getApplicationDefault(optionsOrCallback = {}, callback) { let options; if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; } else { options = optionsOrCallback; } if (callback) { this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); } else { return this.getApplicationDefaultAsync(options); } } async getApplicationDefaultAsync(options = {}) { // If we've already got a cached credential, just return it. if (this.cachedCredential) { return { credential: this.cachedCredential, projectId: await this.getProjectIdAsync(), }; } let credential; let projectId; // Check for the existence of a local environment variable pointing to the // location of the credential file. This is typically used in local // developer scenarios. credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); if (credential) { if (credential instanceof jwtclient_1.JWT) { credential.scopes = this.scopes; } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { credential.scopes = this.getAnyScopes(); } this.cachedCredential = credential; projectId = await this.getProjectId(); return { credential, projectId }; } // Look in the well-known credential file location. credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options); if (credential) { if (credential instanceof jwtclient_1.JWT) { credential.scopes = this.scopes; } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { credential.scopes = this.getAnyScopes(); } this.cachedCredential = credential; projectId = await this.getProjectId(); return { credential, projectId }; } // Determine if we're running on GCE. let isGCE; try { isGCE = await this._checkIsGCE(); } catch (e) { if (e instanceof Error) { e.message = `Unexpected error determining execution environment: ${e.message}`; } throw e; } if (!isGCE) { // We failed to find the default credentials. Bail out with an error. throw new Error('Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.'); } // For GCE, just return a default ComputeClient. It will take care of // the rest. options.scopes = this.getAnyScopes(); this.cachedCredential = new computeclient_1.Compute(options); projectId = await this.getProjectId(); return { projectId, credential: this.cachedCredential }; } /** * Determines whether the auth layer is running on Google Compute Engine. * @returns A promise that resolves with the boolean. * @api private */ async _checkIsGCE() { if (this.checkIsGCE === undefined) { this.checkIsGCE = await gcpMetadata.isAvailable(); } return this.checkIsGCE; } /** * Attempts to load default credentials from the environment variable path.. * @returns Promise that resolves with the OAuth2Client or null. * @api private */ async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || process.env['google_application_credentials']; if (!credentialsPath || credentialsPath.length === 0) { return null; } try { return this._getApplicationCredentialsFromFilePath(credentialsPath, options); } catch (e) { if (e instanceof Error) { e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; } throw e; } } /** * Attempts to load default credentials from a well-known file location * @return Promise that resolves with the OAuth2Client or null. * @api private */ async _tryGetApplicationCredentialsFromWellKnownFile(options) { // First, figure out the location of the file, depending upon the OS type. let location = null; if (this._isWindows()) { // Windows location = process.env['APPDATA']; } else { // Linux or Mac const home = process.env['HOME']; if (home) { location = path.join(home, '.config'); } } // If we found the root path, expand it. if (location) { location = path.join(location, 'gcloud', 'application_default_credentials.json'); if (!fs.existsSync(location)) { location = null; } } // The file does not exist. if (!location) { return null; } // The file seems to exist. Try to use it. const client = await this._getApplicationCredentialsFromFilePath(location, options); return client; } /** * Attempts to load default credentials from a file at the given path.. * @param filePath The path to the file to read. * @returns Promise that resolves with the OAuth2Client * @api private */ async _getApplicationCredentialsFromFilePath(filePath, options = {}) { // Make sure the path looks like a string. if (!filePath || filePath.length === 0) { throw new Error('The file path is invalid.'); } // Make sure there is a file at the path. lstatSync will throw if there is // nothing there. try { // Resolve path to actual file in case of symlink. Expect a thrown error // if not resolvable. filePath = fs.realpathSync(filePath); if (!fs.lstatSync(filePath).isFile()) { throw new Error(); } } catch (err) { if (err instanceof Error) { err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; } throw err; } // Now open a read stream on the file, and parse it. const readStream = fs.createReadStream(filePath); return this.fromStream(readStream, options); } /** * Create a credentials instance using the given input options. * @param json The input object. * @param options The JWT or UserRefresh options for the client * @returns JWT or UserRefresh Client with data */ fromJSON(json, options) { let client; if (!json) { throw new Error('Must pass in a JSON object containing the Google auth settings.'); } options = options || {}; if (json.type === 'authorized_user') { client = new refreshclient_1.UserRefreshClient(options); client.fromJSON(json); } else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { client = externalclient_1.ExternalAccountClient.fromJSON(json, options); client.scopes = this.getAnyScopes(); } else { options.scopes = this.scopes; client = new jwtclient_1.JWT(options); this.setGapicJWTValues(client); client.fromJSON(json); } return client; } /** * Return a JWT or UserRefreshClient from JavaScript object, caching both the * object used to instantiate and the client. * @param json The input object. * @param options The JWT or UserRefresh options for the client * @returns JWT or UserRefresh Client with data */ _cacheClientFromJSON(json, options) { let client; // create either a UserRefreshClient or JWT client. options = options || {}; if (json.type === 'authorized_user') { client = new refreshclient_1.UserRefreshClient(options); client.fromJSON(json); } else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { client = externalclient_1.ExternalAccountClient.fromJSON(json, options); client.scopes = this.getAnyScopes(); } else { options.scopes = this.scopes; client = new jwtclient_1.JWT(options); this.setGapicJWTValues(client); client.fromJSON(json); } // cache both raw data used to instantiate client and client itself. this.jsonContent = json; this.cachedCredential = client; return client; } fromStream(inputStream, optionsOrCallback = {}, callback) { let options = {}; if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; } else { options = optionsOrCallback; } if (callback) { this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); } else { return this.fromStreamAsync(inputStream, options); } } fromStreamAsync(inputStream, options) { return new Promise((resolve, reject) => { if (!inputStream) { throw new Error('Must pass in a stream containing the Google auth settings.'); } let s = ''; inputStream .setEncoding('utf8') .on('error', reject) .on('data', chunk => (s += chunk)) .on('end', () => { try { try { const data = JSON.parse(s); const r = this._cacheClientFromJSON(data, options); return resolve(r); } catch (err) { // If we failed parsing this.keyFileName, assume that it // is a PEM or p12 certificate: if (!this.keyFilename) throw err; const client = new jwtclient_1.JWT({ ...this.clientOptions, keyFile: this.keyFilename, }); this.cachedCredential = client; this.setGapicJWTValues(client); return resolve(client); } } catch (err) { return reject(err); } }); }); } /** * Create a credentials instance using the given API key string. * @param apiKey The API key string * @param options An optional options object. * @returns A JWT loaded from the key */ fromAPIKey(apiKey, options) { options = options || {}; const client = new jwtclient_1.JWT(options); client.fromAPIKey(apiKey); return client; } /** * Determines whether the current operating system is Windows. * @api private */ _isWindows() { const sys = os.platform(); if (sys && sys.length >= 3) { if (sys.substring(0, 3).toLowerCase() === 'win') { return true; } } return false; } /** * Run the Google Cloud SDK command that prints the default project ID */ async getDefaultServiceProjectId() { return new Promise(resolve => { (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => { if (!err && stdout) { try { const projectId = JSON.parse(stdout).configuration.properties.core.project; resolve(projectId); return; } catch (e) { // ignore errors } } resolve(null); }); }); } /** * Loads the project id from environment variables. * @api private */ getProductionProjectId() { return (process.env['GCLOUD_PROJECT'] || process.env['GOOGLE_CLOUD_PROJECT'] || process.env['gcloud_project'] || process.env['google_cloud_project']); } /** * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. * @api private */ async getFileProjectId() { if (this.cachedCredential) { // Try to read the project ID from the cached credentials file return this.cachedCredential.projectId; } // Ensure the projectId is loaded from the keyFile if available. if (this.keyFilename) { const creds = await this.getClient(); if (creds && creds.projectId) { return creds.projectId; } } // Try to load a credentials file and read its project ID const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); if (r) { return r.projectId; } else { return null; } } /** * Gets the project ID from external account client if available. */ async getExternalAccountClientProjectId() { if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { return null; } const creds = await this.getClient(); // Do not suppress the underlying error, as the error could contain helpful // information for debugging and fixing. This is especially true for // external account creds as in order to get the project ID, the following // operations have to succeed: // 1. Valid credentials file should be supplied. // 2. Ability to retrieve access tokens from STS token exchange API. // 3. Ability to exchange for service account impersonated credentials (if // enabled). // 4. Ability to get project info using the access token from step 2 or 3. // Without surfacing the error, it is harder for developers to determine // which step went wrong. return await creds.getProjectId(); } /** * Gets the Compute Engine project ID if it can be inferred. */ async getGCEProjectId() { try { const r = await gcpMetadata.project('project-id'); return r; } catch (e) { // Ignore any errors return null; } } getCredentials(callback) { if (callback) { this.getCredentialsAsync().then(r => callback(null, r), callback); } else { return this.getCredentialsAsync(); } } async getCredentialsAsync() { const client = await this.getClient(); if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { const serviceAccountEmail = client.getServiceAccountEmail(); if (serviceAccountEmail) { return { client_email: serviceAccountEmail }; } } if (this.jsonContent) { const credential = { client_email: this.jsonContent.client_email, private_key: this.jsonContent.private_key, }; return credential; } const isGCE = await this._checkIsGCE(); if (!isGCE) { throw new Error('Unknown error.'); } // For GCE, return the service account details from the metadata server // NOTE: The trailing '/' at the end of service-accounts/ is very important! // The GCF metadata server doesn't respect querystring params if this / is // not included. const data = await gcpMetadata.instance({ property: 'service-accounts/', params: { recursive: 'true' }, }); if (!data || !data.default || !data.default.email) { throw new Error('Failure from metadata server.'); } return { client_email: data.default.email }; } /** * Automatically obtain a client based on the provided configuration. If no * options were passed, use Application Default Credentials. */ async getClient() { if (!this.cachedCredential) { if (this.jsonContent) { this._cacheClientFromJSON(this.jsonContent, this.clientOptions); } else if (this.keyFilename) { const filePath = path.resolve(this.keyFilename); const stream = fs.createReadStream(filePath); await this.fromStreamAsync(stream, this.clientOptions); } else { await this.getApplicationDefaultAsync(this.clientOptions); } } return this.cachedCredential; } /** * Creates a client which will fetch an ID token for authorization. * @param targetAudience the audience for the fetched ID token. * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. */ async getIdTokenClient(targetAudience) { const client = await this.getClient(); if (!('fetchIdToken' in client)) { throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); } return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); } /** * Automatically obtain application default credentials, and return * an access token for making requests. */ async getAccessToken() { const client = await this.getClient(); return (await client.getAccessToken()).token; } /** * Obtain the HTTP headers that will provide authorization for a given * request. */ async getRequestHeaders(url) { const client = await this.getClient(); return client.getRequestHeaders(url); } /** * Obtain credentials for a request, then attach the appropriate headers to * the request options. * @param opts Axios or Request options on which to attach the headers */ async authorizeRequest(opts) { opts = opts || {}; const url = opts.url || opts.uri; const client = await this.getClient(); const headers = await client.getRequestHeaders(url); opts.headers = Object.assign(opts.headers || {}, headers); return opts; } /** * Automatically obtain application default credentials, and make an * HTTP request using the given options. * @param opts Axios request options for the HTTP request. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any async request(opts) { const client = await this.getClient(); return client.request(opts); } /** * Determine the compute environment in which the code is running. */ getEnv() { return (0, envDetect_1.getEnv)(); } /** * Sign the given data with the current private key, or go out * to the IAM API to sign it. * @param data The data to be signed. */ async sign(data) { const client = await this.getClient(); const crypto = (0, crypto_1.createCrypto)(); if (client instanceof jwtclient_1.JWT && client.key) { const sign = await crypto.sign(client.key, data); return sign; } const projectId = await this.getProjectId(); if (!projectId) { throw new Error('Cannot sign data without a project ID.'); } const creds = await this.getCredentials(); if (!creds.client_email) { throw new Error('Cannot sign data without `client_email`.'); } return this.signBlob(crypto, creds.client_email, data); } async signBlob(crypto, emailOrUniqueId, data) { const url = 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + `${emailOrUniqueId}:signBlob`; const res = await this.request({ method: 'POST', url, data: { payload: crypto.encodeBase64StringUtf8(data), }, }); return res.data.signedBlob; } } exports.GoogleAuth = GoogleAuth; /** * Export DefaultTransporter as a static property of the class. */ GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter; //# sourceMappingURL=googleauth.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/google-auth-library/build/src/auth/computeclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/computeclient.js
"use strict"; // Copyright 2013 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.Compute = void 0; const arrify = require("arrify"); const gaxios_1 = require("gaxios"); const gcpMetadata = require("gcp-metadata"); const oauth2client_1 = require("./oauth2client"); class Compute extends oauth2client_1.OAuth2Client { /** * Google Compute Engine service account credentials. * * Retrieve access token from the metadata server. * See: https://developers.google.com/compute/docs/authentication */ constructor(options = {}) { super(options); // Start with an expired refresh token, which will automatically be // refreshed before the first API call is made. this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; this.serviceAccountEmail = options.serviceAccountEmail || 'default'; this.scopes = arrify(options.scopes); } /** * Refreshes the access token. * @param refreshToken Unused parameter */ async refreshTokenNoCache( // eslint-disable-next-line @typescript-eslint/no-unused-vars refreshToken) { const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; let data; try { const instanceOptions = { property: tokenPath, }; if (this.scopes.length > 0) { instanceOptions.params = { scopes: this.scopes.join(','), }; } data = await gcpMetadata.instance(instanceOptions); } catch (e) { if (e instanceof gaxios_1.GaxiosError) { e.message = `Could not refresh access token: ${e.message}`; this.wrapError(e); } throw e; } const tokens = data; if (data && data.expires_in) { tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; delete tokens.expires_in; } this.emit('tokens', tokens); return { tokens, res: null }; } /** * Fetches an ID token. * @param targetAudience the audience for the fetched ID token. */ async fetchIdToken(targetAudience) { const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + `?format=full&audience=${targetAudience}`; let idToken; try { const instanceOptions = { property: idTokenPath, }; idToken = await gcpMetadata.instance(instanceOptions); } catch (e) { if (e instanceof Error) { e.message = `Could not fetch ID token: ${e.message}`; } throw e; } return idToken; } wrapError(e) { const res = e.response; if (res && res.status) { e.code = res.status.toString(); if (res.status === 403) { e.message = 'A Forbidden error was returned while attempting to retrieve an access ' + 'token for the Compute Engine built-in service account. This may be because the Compute ' + 'Engine instance does not have the correct permission scopes specified: ' + e.message; } else if (res.status === 404) { e.message = 'A Not Found error was returned while attempting to retrieve an access' + 'token for the Compute Engine built-in service account. This may be because the Compute ' + 'Engine instance does not have any permission scopes specified: ' + e.message; } } } } exports.Compute = Compute; //# sourceMappingURL=computeclient.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/google-auth-library/build/src/auth/oauth2client.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/oauth2client.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.OAuth2Client = exports.CertificateFormat = exports.CodeChallengeMethod = void 0; const querystring = require("querystring"); const stream = require("stream"); const formatEcdsa = require("ecdsa-sig-formatter"); const crypto_1 = require("../crypto/crypto"); const authclient_1 = require("./authclient"); const loginticket_1 = require("./loginticket"); var CodeChallengeMethod; (function (CodeChallengeMethod) { CodeChallengeMethod["Plain"] = "plain"; CodeChallengeMethod["S256"] = "S256"; })(CodeChallengeMethod = exports.CodeChallengeMethod || (exports.CodeChallengeMethod = {})); var CertificateFormat; (function (CertificateFormat) { CertificateFormat["PEM"] = "PEM"; CertificateFormat["JWK"] = "JWK"; })(CertificateFormat = exports.CertificateFormat || (exports.CertificateFormat = {})); class OAuth2Client extends authclient_1.AuthClient { constructor(optionsOrClientId, clientSecret, redirectUri) { super(); this.certificateCache = {}; this.certificateExpiry = null; this.certificateCacheFormat = CertificateFormat.PEM; this.refreshTokenPromises = new Map(); const opts = optionsOrClientId && typeof optionsOrClientId === 'object' ? optionsOrClientId : { clientId: optionsOrClientId, clientSecret, redirectUri }; this._clientId = opts.clientId; this._clientSecret = opts.clientSecret; this.redirectUri = opts.redirectUri; this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis || 5 * 60 * 1000; this.forceRefreshOnFailure = !!opts.forceRefreshOnFailure; } /** * Generates URL for consent page landing. * @param opts Options. * @return URL to consent page. */ generateAuthUrl(opts = {}) { if (opts.code_challenge_method && !opts.code_challenge) { throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); } opts.response_type = opts.response_type || 'code'; opts.client_id = opts.client_id || this._clientId; opts.redirect_uri = opts.redirect_uri || this.redirectUri; // Allow scopes to be passed either as array or a string if (opts.scope instanceof Array) { opts.scope = opts.scope.join(' '); } const rootUrl = OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_; return (rootUrl + '?' + querystring.stringify(opts)); } generateCodeVerifier() { // To make the code compatible with browser SubtleCrypto we need to make // this method async. throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); } /** * Convenience method to automatically generate a code_verifier, and its * resulting SHA256. If used, this must be paired with a S256 * code_challenge_method. * * For a full example see: * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js */ async generateCodeVerifierAsync() { // base64 encoding uses 6 bits per character, and we want to generate128 // characters. 6*128/8 = 96. const crypto = (0, crypto_1.createCrypto)(); const randomString = crypto.randomBytesBase64(96); // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just // swapping out a few chars. const codeVerifier = randomString .replace(/\+/g, '~') .replace(/=/g, '_') .replace(/\//g, '-'); // Generate the base64 encoded SHA256 const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); // We need to use base64UrlEncoding instead of standard base64 const codeChallenge = unencodedCodeChallenge .split('=')[0] .replace(/\+/g, '-') .replace(/\//g, '_'); return { codeVerifier, codeChallenge }; } getToken(codeOrOptions, callback) { const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; if (callback) { this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); } else { return this.getTokenAsync(options); } } async getTokenAsync(options) { const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_; const values = { code: options.code, client_id: options.client_id || this._clientId, client_secret: this._clientSecret, redirect_uri: options.redirect_uri || this.redirectUri, grant_type: 'authorization_code', code_verifier: options.codeVerifier, }; const res = await this.transporter.request({ method: 'POST', url, data: querystring.stringify(values), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }); const tokens = res.data; if (res.data && res.data.expires_in) { tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; delete tokens.expires_in; } this.emit('tokens', tokens); return { tokens, res }; } /** * Refreshes the access token. * @param refresh_token Existing refresh token. * @private */ async refreshToken(refreshToken) { if (!refreshToken) { return this.refreshTokenNoCache(refreshToken); } // If a request to refresh using the same token has started, // return the same promise. if (this.refreshTokenPromises.has(refreshToken)) { return this.refreshTokenPromises.get(refreshToken); } const p = this.refreshTokenNoCache(refreshToken).then(r => { this.refreshTokenPromises.delete(refreshToken); return r; }, e => { this.refreshTokenPromises.delete(refreshToken); throw e; }); this.refreshTokenPromises.set(refreshToken, p); return p; } async refreshTokenNoCache(refreshToken) { if (!refreshToken) { throw new Error('No refresh token is set.'); } const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_; const data = { refresh_token: refreshToken, client_id: this._clientId, client_secret: this._clientSecret, grant_type: 'refresh_token', }; // request for new token const res = await this.transporter.request({ method: 'POST', url, data: querystring.stringify(data), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }); const tokens = res.data; // TODO: de-duplicate this code from a few spots if (res.data && res.data.expires_in) { tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; delete tokens.expires_in; } this.emit('tokens', tokens); return { tokens, res }; } refreshAccessToken(callback) { if (callback) { this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); } else { return this.refreshAccessTokenAsync(); } } async refreshAccessTokenAsync() { const r = await this.refreshToken(this.credentials.refresh_token); const tokens = r.tokens; tokens.refresh_token = this.credentials.refresh_token; this.credentials = tokens; return { credentials: this.credentials, res: r.res }; } getAccessToken(callback) { if (callback) { this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); } else { return this.getAccessTokenAsync(); } } async getAccessTokenAsync() { const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); if (shouldRefresh) { if (!this.credentials.refresh_token) { if (this.refreshHandler) { const refreshedAccessToken = await this.processAndValidateRefreshHandler(); if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { this.setCredentials(refreshedAccessToken); return { token: this.credentials.access_token }; } } else { throw new Error('No refresh token or refresh handler callback is set.'); } } const r = await this.refreshAccessTokenAsync(); if (!r.credentials || (r.credentials && !r.credentials.access_token)) { throw new Error('Could not refresh access token.'); } return { token: r.credentials.access_token, res: r.res }; } else { return { token: this.credentials.access_token }; } } /** * The main authentication interface. It takes an optional url which when * present is the endpoint being accessed, and returns a Promise which * resolves with authorization header fields. * * In OAuth2Client, the result has the form: * { Authorization: 'Bearer <access_token_value>' } * @param url The optional url being authorized */ async getRequestHeaders(url) { const headers = (await this.getRequestMetadataAsync(url)).headers; return headers; } async getRequestMetadataAsync( // eslint-disable-next-line @typescript-eslint/no-unused-vars url) { const thisCreds = this.credentials; if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey && !this.refreshHandler) { throw new Error('No access, refresh token, API key or refresh handler callback is set.'); } if (thisCreds.access_token && !this.isTokenExpiring()) { thisCreds.token_type = thisCreds.token_type || 'Bearer'; const headers = { Authorization: thisCreds.token_type + ' ' + thisCreds.access_token, }; return { headers: this.addSharedMetadataHeaders(headers) }; } // If refreshHandler exists, call processAndValidateRefreshHandler(). if (this.refreshHandler) { const refreshedAccessToken = await this.processAndValidateRefreshHandler(); if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { this.setCredentials(refreshedAccessToken); const headers = { Authorization: 'Bearer ' + this.credentials.access_token, }; return { headers: this.addSharedMetadataHeaders(headers) }; } } if (this.apiKey) { return { headers: { 'X-Goog-Api-Key': this.apiKey } }; } let r = null; let tokens = null; try { r = await this.refreshToken(thisCreds.refresh_token); tokens = r.tokens; } catch (err) { const e = err; if (e.response && (e.response.status === 403 || e.response.status === 404)) { e.message = `Could not refresh access token: ${e.message}`; } throw e; } const credentials = this.credentials; credentials.token_type = credentials.token_type || 'Bearer'; tokens.refresh_token = credentials.refresh_token; this.credentials = tokens; const headers = { Authorization: credentials.token_type + ' ' + tokens.access_token, }; return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; } /** * Generates an URL to revoke the given token. * @param token The existing token to be revoked. */ static getRevokeTokenUrl(token) { const parameters = querystring.stringify({ token }); return `${OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_}?${parameters}`; } revokeToken(token, callback) { const opts = { url: OAuth2Client.getRevokeTokenUrl(token), method: 'POST', }; if (callback) { this.transporter .request(opts) .then(r => callback(null, r), callback); } else { return this.transporter.request(opts); } } revokeCredentials(callback) { if (callback) { this.revokeCredentialsAsync().then(res => callback(null, res), callback); } else { return this.revokeCredentialsAsync(); } } async revokeCredentialsAsync() { const token = this.credentials.access_token; this.credentials = {}; if (token) { return this.revokeToken(token); } else { throw new Error('No access token to revoke.'); } } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } async requestAsync(opts, retry = false) { let r2; try { const r = await this.getRequestMetadataAsync(opts.url); opts.headers = opts.headers || {}; if (r.headers && r.headers['x-goog-user-project']) { opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project']; } if (r.headers && r.headers.Authorization) { opts.headers.Authorization = r.headers.Authorization; } if (this.apiKey) { opts.headers['X-Goog-Api-Key'] = this.apiKey; } r2 = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - An access_token and refresh_token were available, but either no // expiry_date was available or the forceRefreshOnFailure flag is set. // The absent expiry_date case can happen when developers stash the // access_token and refresh_token for later use, but the access_token // fails on the first try because it's expired. Some developers may // choose to enable forceRefreshOnFailure to mitigate time-related // errors. // Or the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - No refresh_token was available // - An access_token and a refreshHandler callback were available, but // either no expiry_date was available or the forceRefreshOnFailure // flag is set. The access_token fails on the first try because it's // expired. Some developers may choose to enable forceRefreshOnFailure // to mitigate time-related errors. const mayRequireRefresh = this.credentials && this.credentials.access_token && this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure); const mayRequireRefreshWithNoRefreshToken = this.credentials && this.credentials.access_token && !this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure) && this.refreshHandler; const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!retry && isAuthErr && !isReadableStream && mayRequireRefresh) { await this.refreshAccessTokenAsync(); return this.requestAsync(opts, true); } else if (!retry && isAuthErr && !isReadableStream && mayRequireRefreshWithNoRefreshToken) { const refreshedAccessToken = await this.processAndValidateRefreshHandler(); if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { this.setCredentials(refreshedAccessToken); } return this.requestAsync(opts, true); } } throw e; } return r2; } verifyIdToken(options, callback) { // This function used to accept two arguments instead of an options object. // Check the types to help users upgrade with less pain. // This check can be removed after a 2.0 release. if (callback && typeof callback !== 'function') { throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); } if (callback) { this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); } else { return this.verifyIdTokenAsync(options); } } async verifyIdTokenAsync(options) { if (!options.idToken) { throw new Error('The verifyIdToken method requires an ID Token'); } const response = await this.getFederatedSignonCertsAsync(); const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, OAuth2Client.ISSUERS_, options.maxExpiry); return login; } /** * Obtains information about the provisioned access token. Especially useful * if you want to check the scopes that were provisioned to a given token. * * @param accessToken Required. The Access Token for which you want to get * user info. */ async getTokenInfo(accessToken) { const { data } = await this.transporter.request({ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Bearer ${accessToken}`, }, url: OAuth2Client.GOOGLE_TOKEN_INFO_URL, }); const info = Object.assign({ expiry_date: new Date().getTime() + data.expires_in * 1000, scopes: data.scope.split(' '), }, data); delete info.expires_in; delete info.scope; return info; } getFederatedSignonCerts(callback) { if (callback) { this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); } else { return this.getFederatedSignonCertsAsync(); } } async getFederatedSignonCertsAsync() { const nowTime = new Date().getTime(); const format = (0, crypto_1.hasBrowserCrypto)() ? CertificateFormat.JWK : CertificateFormat.PEM; if (this.certificateExpiry && nowTime < this.certificateExpiry.getTime() && this.certificateCacheFormat === format) { return { certs: this.certificateCache, format }; } let res; let url; switch (format) { case CertificateFormat.PEM: url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_; break; case CertificateFormat.JWK: url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_; break; default: throw new Error(`Unsupported certificate format ${format}`); } try { res = await this.transporter.request({ url }); } catch (e) { if (e instanceof Error) { e.message = `Failed to retrieve verification certificates: ${e.message}`; } throw e; } const cacheControl = res ? res.headers['cache-control'] : undefined; let cacheAge = -1; if (cacheControl) { const pattern = new RegExp('max-age=([0-9]*)'); const regexResult = pattern.exec(cacheControl); if (regexResult && regexResult.length === 2) { // Cache results with max-age (in seconds) cacheAge = Number(regexResult[1]) * 1000; // milliseconds } } let certificates = {}; switch (format) { case CertificateFormat.PEM: certificates = res.data; break; case CertificateFormat.JWK: for (const key of res.data.keys) { certificates[key.kid] = key; } break; default: throw new Error(`Unsupported certificate format ${format}`); } const now = new Date(); this.certificateExpiry = cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); this.certificateCache = certificates; this.certificateCacheFormat = format; return { certs: certificates, format, res }; } getIapPublicKeys(callback) { if (callback) { this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); } else { return this.getIapPublicKeysAsync(); } } async getIapPublicKeysAsync() { let res; const url = OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_; try { res = await this.transporter.request({ url }); } catch (e) { if (e instanceof Error) { e.message = `Failed to retrieve verification certificates: ${e.message}`; } throw e; } return { pubkeys: res.data, res }; } verifySignedJwtWithCerts() { // To make the code compatible with browser SubtleCrypto we need to make // this method async. throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); } /** * Verify the id token is signed with the correct certificate * and is from the correct audience. * @param jwt The jwt to verify (The ID Token in this case). * @param certs The array of certs to test the jwt against. * @param requiredAudience The audience to test the jwt against. * @param issuers The allowed issuers of the jwt (Optional). * @param maxExpiry The max expiry the certificate can be (Optional). * @return Returns a promise resolving to LoginTicket on verification. */ async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { const crypto = (0, crypto_1.createCrypto)(); if (!maxExpiry) { maxExpiry = OAuth2Client.MAX_TOKEN_LIFETIME_SECS_; } const segments = jwt.split('.'); if (segments.length !== 3) { throw new Error('Wrong number of segments in token: ' + jwt); } const signed = segments[0] + '.' + segments[1]; let signature = segments[2]; let envelope; let payload; try { envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); } catch (err) { if (err instanceof Error) { err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; } throw err; } if (!envelope) { throw new Error("Can't parse token envelope: " + segments[0]); } try { payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); } catch (err) { if (err instanceof Error) { err.message = `Can't parse token payload '${segments[0]}`; } throw err; } if (!payload) { throw new Error("Can't parse token payload: " + segments[1]); } if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { // If this is not present, then there's no reason to attempt verification throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); } const cert = certs[envelope.kid]; if (envelope.alg === 'ES256') { signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); } const verified = await crypto.verify(cert, signed, signature); if (!verified) { throw new Error('Invalid token signature: ' + jwt); } if (!payload.iat) { throw new Error('No issue time in token: ' + JSON.stringify(payload)); } if (!payload.exp) { throw new Error('No expiration time in token: ' + JSON.stringify(payload)); } const iat = Number(payload.iat); if (isNaN(iat)) throw new Error('iat field using invalid format'); const exp = Number(payload.exp); if (isNaN(exp)) throw new Error('exp field using invalid format'); const now = new Date().getTime() / 1000; if (exp >= now + maxExpiry) { throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); } const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; if (now < earliest) { throw new Error('Token used too early, ' + now + ' < ' + earliest + ': ' + JSON.stringify(payload)); } if (now > latest) { throw new Error('Token used too late, ' + now + ' > ' + latest + ': ' + JSON.stringify(payload)); } if (issuers && issuers.indexOf(payload.iss) < 0) { throw new Error('Invalid issuer, expected one of [' + issuers + '], but got ' + payload.iss); } // Check the audience matches if we have one if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { const aud = payload.aud; let audVerified = false; // If the requiredAudience is an array, check if it contains token // audience if (requiredAudience.constructor === Array) { audVerified = requiredAudience.indexOf(aud) > -1; } else { audVerified = aud === requiredAudience; } if (!audVerified) { throw new Error('Wrong recipient, payload audience != requiredAudience'); } } return new loginticket_1.LoginTicket(envelope, payload); } /** * Returns a promise that resolves with AccessTokenResponse type if * refreshHandler is defined. * If not, nothing is returned. */ async processAndValidateRefreshHandler() { if (this.refreshHandler) { const accessTokenResponse = await this.refreshHandler(); if (!accessTokenResponse.access_token) { throw new Error('No access token is returned by the refreshHandler callback.'); } return accessTokenResponse; } return; } /** * Returns true if a token is expired or will expire within * eagerRefreshThresholdMillismilliseconds. * If there is no expiry time, assumes the token is not expired or expiring. */ isTokenExpiring() { const expiryDate = this.credentials.expiry_date; return expiryDate ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis : false; } } exports.OAuth2Client = OAuth2Client; OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; /** * The base URL for auth endpoints. */ OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ = 'https://accounts.google.com/o/oauth2/v2/auth'; /** * The base endpoint for token retrieval. */ OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ = 'https://oauth2.googleapis.com/token'; /** * The base endpoint to revoke tokens. */ OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ = 'https://oauth2.googleapis.com/revoke'; /** * Google Sign on certificates in PEM format. */ OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v1/certs'; /** * Google Sign on certificates in JWK format. */ OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v3/certs'; /** * Google Sign on certificates in JWK format. */ OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_ = 'https://www.gstatic.com/iap/verify/public_key'; /** * Clock skew - five minutes in seconds */ OAuth2Client.CLOCK_SKEW_SECS_ = 300; /** * Max Token Lifetime is one day in seconds */ OAuth2Client.MAX_TOKEN_LIFETIME_SECS_ = 86400; /** * The allowed oauth token issuers. */ OAuth2Client.ISSUERS_ = [ 'accounts.google.com', 'https://accounts.google.com', ]; //# sourceMappingURL=oauth2client.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/google-auth-library/build/src/auth/downscopedclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/downscopedclient.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0; const stream = require("stream"); const authclient_1 = require("./authclient"); const sts = require("./stscredentials"); /** * The required token exchange grant_type: rfc8693#section-2.1 */ const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; /** * The requested token exchange requested_token_type: rfc8693#section-2.1 */ const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; /** * The requested token exchange subject_token_type: rfc8693#section-2.1 */ const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; /** The STS access token exchange end point. */ const STS_ACCESS_TOKEN_URL = 'https://sts.googleapis.com/v1/token'; /** * The maximum number of access boundary rules a Credential Access Boundary * can contain. */ exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; /** * Offset to take into account network delays and server clock skews. */ exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; /** * Defines a set of Google credentials that are downscoped from an existing set * of Google OAuth2 credentials. This is useful to restrict the Identity and * Access Management (IAM) permissions that a short-lived credential can use. * The common pattern of usage is to have a token broker with elevated access * generate these downscoped credentials from higher access source credentials * and pass the downscoped short-lived access tokens to a token consumer via * some secure authenticated channel for limited access to Google Cloud Storage * resources. */ class DownscopedClient extends authclient_1.AuthClient { /** * Instantiates a downscoped client object using the provided source * AuthClient and credential access boundary rules. * To downscope permissions of a source AuthClient, a Credential Access * Boundary that specifies which resources the new credential can access, as * well as an upper bound on the permissions that are available on each * resource, has to be defined. A downscoped client can then be instantiated * using the source AuthClient and the Credential Access Boundary. * @param authClient The source AuthClient to be downscoped based on the * provided Credential Access Boundary rules. * @param credentialAccessBoundary The Credential Access Boundary which * contains a list of access boundary rules. Each rule contains information * on the resource that the rule applies to, the upper bound of the * permissions that are available on that resource and an optional * condition to further restrict permissions. * @param additionalOptions Optional additional behavior customization * options. These currently customize expiration threshold time and * whether to retry on 401/403 API request errors. * @param quotaProjectId Optional quota project id for setting up in the * x-goog-user-project header. */ constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) { super(); this.authClient = authClient; this.credentialAccessBoundary = credentialAccessBoundary; // Check 1-10 Access Boundary Rules are defined within Credential Access // Boundary. if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { throw new Error('At least one access boundary rule needs to be defined.'); } else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { throw new Error('The provided access boundary has more than ' + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); } // Check at least one permission should be defined in each Access Boundary // Rule. for (const rule of credentialAccessBoundary.accessBoundary .accessBoundaryRules) { if (rule.availablePermissions.length === 0) { throw new Error('At least one permission should be defined in access boundary rules.'); } } this.stsCredential = new sts.StsCredentials(STS_ACCESS_TOKEN_URL); this.cachedDownscopedAccessToken = null; // As threshold could be zero, // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the // zero value. if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') { this.eagerRefreshThresholdMillis = exports.EXPIRATION_TIME_OFFSET; } else { this.eagerRefreshThresholdMillis = additionalOptions .eagerRefreshThresholdMillis; } this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure); this.quotaProjectId = quotaProjectId; } /** * Provides a mechanism to inject Downscoped access tokens directly. * The expiry_date field is required to facilitate determination of the token * expiration which would make it easier for the token consumer to handle. * @param credentials The Credentials object to set on the current client. */ setCredentials(credentials) { if (!credentials.expiry_date) { throw new Error('The access token expiry_date field is missing in the provided ' + 'credentials.'); } super.setCredentials(credentials); this.cachedDownscopedAccessToken = credentials; } async getAccessToken() { // If the cached access token is unavailable or expired, force refresh. // The Downscoped access token will be returned in // DownscopedAccessTokenResponse format. if (!this.cachedDownscopedAccessToken || this.isExpired(this.cachedDownscopedAccessToken)) { await this.refreshAccessTokenAsync(); } // Return Downscoped access token in DownscopedAccessTokenResponse format. return { token: this.cachedDownscopedAccessToken.access_token, expirationTime: this.cachedDownscopedAccessToken.expiry_date, res: this.cachedDownscopedAccessToken.res, }; } /** * The main authentication interface. It takes an optional url which when * present is the endpoint being accessed, and returns a Promise which * resolves with authorization header fields. * * The result has the form: * { Authorization: 'Bearer <access_token_value>' } */ async getRequestHeaders() { const accessTokenResponse = await this.getAccessToken(); const headers = { Authorization: `Bearer ${accessTokenResponse.token}`, }; return this.addSharedMetadataHeaders(headers); } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } /** * Authenticates the provided HTTP request, processes it and resolves with the * returned response. * @param opts The HTTP request options. * @param retry Whether the current attempt is a retry after a failed attempt. * @return A promise that resolves with the successful response. */ async requestAsync(opts, retry = false) { let response; try { const requestHeaders = await this.getRequestHeaders(); opts.headers = opts.headers || {}; if (requestHeaders && requestHeaders['x-goog-user-project']) { opts.headers['x-goog-user-project'] = requestHeaders['x-goog-user-project']; } if (requestHeaders && requestHeaders.Authorization) { opts.headers.Authorization = requestHeaders.Authorization; } response = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - forceRefreshOnFailure is true const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!retry && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { await this.refreshAccessTokenAsync(); return await this.requestAsync(opts, true); } } throw e; } return response; } /** * Forces token refresh, even if unexpired tokens are currently cached. * GCP access tokens are retrieved from authclient object/source credential. * Then GCP access tokens are exchanged for downscoped access tokens via the * token exchange endpoint. * @return A promise that resolves with the fresh downscoped access token. */ async refreshAccessTokenAsync() { var _a; // Retrieve GCP access token from source credential. const subjectToken = (await this.authClient.getAccessToken()).token; // Construct the STS credentials options. const stsCredentialsOptions = { grantType: STS_GRANT_TYPE, requestedTokenType: STS_REQUEST_TOKEN_TYPE, subjectToken: subjectToken, subjectTokenType: STS_SUBJECT_TOKEN_TYPE, }; // Exchange the source AuthClient access token for a Downscoped access // token. const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); /** * The STS endpoint will only return the expiration time for the downscoped * access token if the original access token represents a service account. * The downscoped token's expiration time will always match the source * credential expiration. When no expires_in is returned, we can copy the * source credential's expiration time. */ const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null; const expiryDate = stsResponse.expires_in ? new Date().getTime() + stsResponse.expires_in * 1000 : sourceCredExpireDate; // Save response in cached access token. this.cachedDownscopedAccessToken = { access_token: stsResponse.access_token, expiry_date: expiryDate, res: stsResponse.res, }; // Save credentials. this.credentials = {}; Object.assign(this.credentials, this.cachedDownscopedAccessToken); delete this.credentials.res; // Trigger tokens event to notify external listeners. this.emit('tokens', { refresh_token: null, expiry_date: this.cachedDownscopedAccessToken.expiry_date, access_token: this.cachedDownscopedAccessToken.access_token, token_type: 'Bearer', id_token: null, }); // Return the cached access token. return this.cachedDownscopedAccessToken; } /** * Returns whether the provided credentials are expired or not. * If there is no expiry time, assumes the token is not expired or expiring. * @param downscopedAccessToken The credentials to check for expiration. * @return Whether the credentials are expired or not. */ isExpired(downscopedAccessToken) { const now = new Date().getTime(); return downscopedAccessToken.expiry_date ? now >= downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis : false; } } exports.DownscopedClient = DownscopedClient; //# sourceMappingURL=downscopedclient.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/google-auth-library/build/src/auth/iam.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/iam.js
"use strict"; // Copyright 2014 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.IAMAuth = void 0; class IAMAuth { /** * IAM credentials. * * @param selector the iam authority selector * @param token the token * @constructor */ constructor(selector, token) { this.selector = selector; this.token = token; this.selector = selector; this.token = token; } /** * Acquire the HTTP headers required to make an authenticated request. */ getRequestHeaders() { return { 'x-goog-iam-authority-selector': this.selector, 'x-goog-iam-authorization-token': this.token, }; } } exports.IAMAuth = IAMAuth; //# sourceMappingURL=iam.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/google-auth-library/build/src/auth/idtokenclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/idtokenclient.js
"use strict"; // Copyright 2020 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.IdTokenClient = void 0; const oauth2client_1 = require("./oauth2client"); class IdTokenClient extends oauth2client_1.OAuth2Client { /** * Google ID Token client * * Retrieve access token from the metadata server. * See: https://developers.google.com/compute/docs/authentication */ constructor(options) { super(); this.targetAudience = options.targetAudience; this.idTokenProvider = options.idTokenProvider; } async getRequestMetadataAsync( // eslint-disable-next-line @typescript-eslint/no-unused-vars url) { if (!this.credentials.id_token || (this.credentials.expiry_date || 0) < Date.now()) { const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); this.credentials = { id_token: idToken, expiry_date: this.getIdTokenExpiryDate(idToken), }; } const headers = { Authorization: 'Bearer ' + this.credentials.id_token, }; return { headers }; } getIdTokenExpiryDate(idToken) { const payloadB64 = idToken.split('.')[1]; if (payloadB64) { const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); return payload.exp * 1000; } } } exports.IdTokenClient = IdTokenClient; //# sourceMappingURL=idtokenclient.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/google-auth-library/build/src/auth/loginticket.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/loginticket.js
"use strict"; // Copyright 2014 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.LoginTicket = void 0; class LoginTicket { /** * Create a simple class to extract user ID from an ID Token * * @param {string} env Envelope of the jwt * @param {TokenPayload} pay Payload of the jwt * @constructor */ constructor(env, pay) { this.envelope = env; this.payload = pay; } getEnvelope() { return this.envelope; } getPayload() { return this.payload; } /** * Create a simple class to extract user ID from an ID Token * * @return The user ID */ getUserId() { const payload = this.getPayload(); if (payload && payload.sub) { return payload.sub; } return null; } /** * Returns attributes from the login ticket. This can contain * various information about the user session. * * @return The envelope and payload */ getAttributes() { return { envelope: this.getEnvelope(), payload: this.getPayload() }; } } exports.LoginTicket = LoginTicket; //# sourceMappingURL=loginticket.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/google-auth-library/build/src/auth/authclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/authclient.js
"use strict"; // Copyright 2012 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.AuthClient = void 0; const events_1 = require("events"); const transporters_1 = require("../transporters"); class AuthClient extends events_1.EventEmitter { constructor() { super(...arguments); this.transporter = new transporters_1.DefaultTransporter(); this.credentials = {}; this.eagerRefreshThresholdMillis = 5 * 60 * 1000; this.forceRefreshOnFailure = false; } /** * Sets the auth credentials. */ setCredentials(credentials) { this.credentials = credentials; } /** * Append additional headers, e.g., x-goog-user-project, shared across the * classes inheriting AuthClient. This method should be used by any method * that overrides getRequestMetadataAsync(), which is a shared helper for * setting request information in both gRPC and HTTP API calls. * * @param headers object to append additional headers to. */ addSharedMetadataHeaders(headers) { // quota_project_id, stored in application_default_credentials.json, is set in // the x-goog-user-project header, to indicate an alternate account for // billing and quota: if (!headers['x-goog-user-project'] && // don't override a value the user sets. this.quotaProjectId) { headers['x-goog-user-project'] = this.quotaProjectId; } return headers; } } exports.AuthClient = AuthClient; //# sourceMappingURL=authclient.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/google-auth-library/build/src/auth/refreshclient.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/refreshclient.js
"use strict"; // Copyright 2015 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.UserRefreshClient = void 0; const oauth2client_1 = require("./oauth2client"); class UserRefreshClient extends oauth2client_1.OAuth2Client { constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { const opts = optionsOrClientId && typeof optionsOrClientId === 'object' ? optionsOrClientId : { clientId: optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure, }; super({ clientId: opts.clientId, clientSecret: opts.clientSecret, eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis, forceRefreshOnFailure: opts.forceRefreshOnFailure, }); this._refreshToken = opts.refreshToken; this.credentials.refresh_token = opts.refreshToken; } /** * Refreshes the access token. * @param refreshToken An ignored refreshToken.. * @param callback Optional callback. */ async refreshTokenNoCache( // eslint-disable-next-line @typescript-eslint/no-unused-vars refreshToken) { return super.refreshTokenNoCache(this._refreshToken); } /** * Create a UserRefreshClient credentials instance using the given input * options. * @param json The input object. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the user refresh token'); } if (json.type !== 'authorized_user') { throw new Error('The incoming JSON object does not have the "authorized_user" type'); } if (!json.client_id) { throw new Error('The incoming JSON object does not contain a client_id field'); } if (!json.client_secret) { throw new Error('The incoming JSON object does not contain a client_secret field'); } if (!json.refresh_token) { throw new Error('The incoming JSON object does not contain a refresh_token field'); } this._clientId = json.client_id; this._clientSecret = json.client_secret; this._refreshToken = json.refresh_token; this.credentials.refresh_token = json.refresh_token; this.quotaProjectId = json.quota_project_id; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } async fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { return reject(new Error('Must pass in a stream containing the user refresh token.')); } let s = ''; inputStream .setEncoding('utf8') .on('error', reject) .on('data', chunk => (s += chunk)) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); return resolve(); } catch (err) { return reject(err); } }); }); } } exports.UserRefreshClient = UserRefreshClient; //# sourceMappingURL=refreshclient.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/google-auth-library/build/src/auth/stscredentials.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/stscredentials.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.StsCredentials = void 0; const gaxios_1 = require("gaxios"); const querystring = require("querystring"); const transporters_1 = require("../transporters"); const oauth2common_1 = require("./oauth2common"); /** * Implements the OAuth 2.0 token exchange based on * https://tools.ietf.org/html/rfc8693 */ class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { /** * Initializes an STS credentials instance. * @param tokenExchangeEndpoint The token exchange endpoint. * @param clientAuthentication The client authentication credentials if * available. */ constructor(tokenExchangeEndpoint, clientAuthentication) { super(clientAuthentication); this.tokenExchangeEndpoint = tokenExchangeEndpoint; this.transporter = new transporters_1.DefaultTransporter(); } /** * Exchanges the provided token for another type of token based on the * rfc8693 spec. * @param stsCredentialsOptions The token exchange options used to populate * the token exchange request. * @param additionalHeaders Optional additional headers to pass along the * request. * @param options Optional additional GCP-specific non-spec defined options * to send with the request. * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` * @return A promise that resolves with the token exchange response containing * the requested token and its expiration time. */ async exchangeToken(stsCredentialsOptions, additionalHeaders, // eslint-disable-next-line @typescript-eslint/no-explicit-any options) { var _a, _b, _c; const values = { grant_type: stsCredentialsOptions.grantType, resource: stsCredentialsOptions.resource, audience: stsCredentialsOptions.audience, scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '), requested_token_type: stsCredentialsOptions.requestedTokenType, subject_token: stsCredentialsOptions.subjectToken, subject_token_type: stsCredentialsOptions.subjectTokenType, actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken, actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType, // Non-standard GCP-specific options. options: options && JSON.stringify(options), }; // Remove undefined fields. Object.keys(values).forEach(key => { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof values[key] === 'undefined') { // eslint-disable-next-line @typescript-eslint/no-explicit-any delete values[key]; } }); const headers = { 'Content-Type': 'application/x-www-form-urlencoded', }; // Inject additional STS headers if available. Object.assign(headers, additionalHeaders || {}); const opts = { url: this.tokenExchangeEndpoint, method: 'POST', headers, data: querystring.stringify(values), responseType: 'json', }; // Apply OAuth client authentication. this.applyClientAuthenticationOptions(opts); try { const response = await this.transporter.request(opts); // Successful response. const stsSuccessfulResponse = response.data; stsSuccessfulResponse.res = response; return stsSuccessfulResponse; } catch (error) { // Translate error to OAuthError. if (error instanceof gaxios_1.GaxiosError && error.response) { throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, // Preserve other fields from the original error. error); } // Request could fail before the server responds. throw error; } } } exports.StsCredentials = StsCredentials; //# sourceMappingURL=stscredentials.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/google-auth-library/build/src/auth/impersonated.js
aws/lti-middleware/node_modules/google-auth-library/build/src/auth/impersonated.js
"use strict"; /** * 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Impersonated = void 0; const oauth2client_1 = require("./oauth2client"); const gaxios_1 = require("gaxios"); class Impersonated extends oauth2client_1.OAuth2Client { /** * Impersonated service account credentials. * * Create a new access token by impersonating another service account. * * Impersonated Credentials allowing credentials issued to a user or * service account to impersonate another. The source project using * Impersonated Credentials must enable the "IAMCredentials" API. * Also, the target service account must grant the orginating principal * the "Service Account Token Creator" IAM role. * * @param {object} options - The configuration object. * @param {object} [options.sourceClient] the source credential used as to * acquire the impersonated credentials. * @param {string} [options.targetPrincipal] the service account to * impersonate. * @param {string[]} [options.delegates] the chained list of delegates * required to grant the final access_token. If set, the sequence of * identities must have "Service Account Token Creator" capability granted to * the preceding identity. For example, if set to [serviceAccountB, * serviceAccountC], the sourceCredential must have the Token Creator role on * serviceAccountB. serviceAccountB must have the Token Creator on * serviceAccountC. Finally, C must have Token Creator on target_principal. * If left unset, sourceCredential must have that role on targetPrincipal. * @param {string[]} [options.targetScopes] scopes to request during the * authorization grant. * @param {number} [options.lifetime] number of seconds the delegated * credential should be valid for up to 3600 seconds by default, or 43,200 * seconds by extending the token's lifetime, see: * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth * @param {string} [options.endpoint] api endpoint override. */ constructor(options = {}) { var _a, _b, _c, _d, _e, _f; super(options); this.credentials = { expiry_date: 1, refresh_token: 'impersonated-placeholder', }; this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client(); this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : ''; this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : []; this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : []; this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600; this.endpoint = (_f = options.endpoint) !== null && _f !== void 0 ? _f : 'https://iamcredentials.googleapis.com'; } /** * Refreshes the access token. * @param refreshToken Unused parameter */ async refreshToken(refreshToken) { var _a, _b, _c, _d, _e, _f; try { await this.sourceClient.getAccessToken(); const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; const u = `${this.endpoint}/v1/${name}:generateAccessToken`; const body = { delegates: this.delegates, scope: this.targetScopes, lifetime: this.lifetime + 's', }; const res = await this.sourceClient.request({ url: u, data: body, method: 'POST', }); const tokenResponse = res.data; this.credentials.access_token = tokenResponse.accessToken; this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); return { tokens: this.credentials, res, }; } catch (error) { if (!(error instanceof Error)) throw error; let status = 0; let message = ''; if (error instanceof gaxios_1.GaxiosError) { status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status; message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message; } if (status && message) { error.message = `${status}: unable to impersonate: ${message}`; throw error; } else { error.message = `unable to impersonate: ${error}`; throw error; } } } } exports.Impersonated = Impersonated; //# sourceMappingURL=impersonated.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/google-auth-library/build/src/crypto/crypto.js
aws/lti-middleware/node_modules/google-auth-library/build/src/crypto/crypto.js
"use strict"; // 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. /* global window */ Object.defineProperty(exports, "__esModule", { value: true }); exports.fromArrayBufferToHex = exports.hasBrowserCrypto = exports.createCrypto = void 0; const crypto_1 = require("./browser/crypto"); const crypto_2 = require("./node/crypto"); function createCrypto() { if (hasBrowserCrypto()) { return new crypto_1.BrowserCrypto(); } return new crypto_2.NodeCrypto(); } exports.createCrypto = createCrypto; function hasBrowserCrypto() { return (typeof window !== 'undefined' && typeof window.crypto !== 'undefined' && typeof window.crypto.subtle !== 'undefined'); } exports.hasBrowserCrypto = hasBrowserCrypto; /** * Converts an ArrayBuffer to a hexadecimal string. * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. * @return The hexadecimal encoding of the ArrayBuffer. */ function fromArrayBufferToHex(arrayBuffer) { // Convert buffer to byte array. const byteArray = Array.from(new Uint8Array(arrayBuffer)); // Convert bytes to hex string. return byteArray .map(byte => { return byte.toString(16).padStart(2, '0'); }) .join(''); } exports.fromArrayBufferToHex = fromArrayBufferToHex; //# sourceMappingURL=crypto.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/google-auth-library/build/src/crypto/node/crypto.js
aws/lti-middleware/node_modules/google-auth-library/build/src/crypto/node/crypto.js
"use strict"; // 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. Object.defineProperty(exports, "__esModule", { value: true }); exports.NodeCrypto = void 0; const crypto = require("crypto"); class NodeCrypto { async sha256DigestBase64(str) { return crypto.createHash('sha256').update(str).digest('base64'); } randomBytesBase64(count) { return crypto.randomBytes(count).toString('base64'); } async verify(pubkey, data, signature) { const verifier = crypto.createVerify('sha256'); verifier.update(data); verifier.end(); return verifier.verify(pubkey, signature, 'base64'); } async sign(privateKey, data) { const signer = crypto.createSign('RSA-SHA256'); signer.update(data); signer.end(); return signer.sign(privateKey, 'base64'); } decodeBase64StringUtf8(base64) { return Buffer.from(base64, 'base64').toString('utf-8'); } encodeBase64StringUtf8(text) { return Buffer.from(text, 'utf-8').toString('base64'); } /** * Computes the SHA-256 hash of the provided string. * @param str The plain text string to hash. * @return A promise that resolves with the SHA-256 hash of the provided * string in hexadecimal encoding. */ async sha256DigestHex(str) { return crypto.createHash('sha256').update(str).digest('hex'); } /** * Computes the HMAC hash of a message using the provided crypto key and the * SHA-256 algorithm. * @param key The secret crypto key in utf-8 or ArrayBuffer format. * @param msg The plain text message. * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer * format. */ async signWithHmacSha256(key, msg) { const cryptoKey = typeof key === 'string' ? key : toBuffer(key); return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest()); } } exports.NodeCrypto = NodeCrypto; /** * Converts a Node.js Buffer to an ArrayBuffer. * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer * @param buffer The Buffer input to covert. * @return The ArrayBuffer representation of the input. */ function toArrayBuffer(buffer) { return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); } /** * Converts an ArrayBuffer to a Node.js Buffer. * @param arrayBuffer The ArrayBuffer input to covert. * @return The Buffer representation of the input. */ function toBuffer(arrayBuffer) { return Buffer.from(arrayBuffer); } //# sourceMappingURL=crypto.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/google-auth-library/build/src/crypto/browser/crypto.js
aws/lti-middleware/node_modules/google-auth-library/build/src/crypto/browser/crypto.js
"use strict"; // 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. /* global window */ Object.defineProperty(exports, "__esModule", { value: true }); exports.BrowserCrypto = void 0; // This file implements crypto functions we need using in-browser // SubtleCrypto interface `window.crypto.subtle`. const base64js = require("base64-js"); // Not all browsers support `TextEncoder`. The following `require` will // provide a fast UTF8-only replacement for those browsers that don't support // text encoding natively. // eslint-disable-next-line node/no-unsupported-features/node-builtins if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') { require('fast-text-encoding'); } const crypto_1 = require("../crypto"); class BrowserCrypto { constructor() { if (typeof window === 'undefined' || window.crypto === undefined || window.crypto.subtle === undefined) { throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); } } async sha256DigestBase64(str) { // SubtleCrypto digest() method is async, so we must make // this method async as well. // To calculate SHA256 digest using SubtleCrypto, we first // need to convert an input string to an ArrayBuffer: // eslint-disable-next-line node/no-unsupported-features/node-builtins const inputBuffer = new TextEncoder().encode(str); // Result is ArrayBuffer as well. const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); return base64js.fromByteArray(new Uint8Array(outputBuffer)); } randomBytesBase64(count) { const array = new Uint8Array(count); window.crypto.getRandomValues(array); return base64js.fromByteArray(array); } static padBase64(base64) { // base64js requires padding, so let's add some '=' while (base64.length % 4 !== 0) { base64 += '='; } return base64; } async verify(pubkey, data, signature) { const algo = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, }; // eslint-disable-next-line node/no-unsupported-features/node-builtins const dataArray = new TextEncoder().encode(data); const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); // SubtleCrypto's verify method is async so we must make // this method async as well. const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); return result; } async sign(privateKey, data) { const algo = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, }; // eslint-disable-next-line node/no-unsupported-features/node-builtins const dataArray = new TextEncoder().encode(data); const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); // SubtleCrypto's sign method is async so we must make // this method async as well. const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); return base64js.fromByteArray(new Uint8Array(result)); } decodeBase64StringUtf8(base64) { const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); // eslint-disable-next-line node/no-unsupported-features/node-builtins const result = new TextDecoder().decode(uint8array); return result; } encodeBase64StringUtf8(text) { // eslint-disable-next-line node/no-unsupported-features/node-builtins const uint8array = new TextEncoder().encode(text); const result = base64js.fromByteArray(uint8array); return result; } /** * Computes the SHA-256 hash of the provided string. * @param str The plain text string to hash. * @return A promise that resolves with the SHA-256 hash of the provided * string in hexadecimal encoding. */ async sha256DigestHex(str) { // SubtleCrypto digest() method is async, so we must make // this method async as well. // To calculate SHA256 digest using SubtleCrypto, we first // need to convert an input string to an ArrayBuffer: // eslint-disable-next-line node/no-unsupported-features/node-builtins const inputBuffer = new TextEncoder().encode(str); // Result is ArrayBuffer as well. const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); return (0, crypto_1.fromArrayBufferToHex)(outputBuffer); } /** * Computes the HMAC hash of a message using the provided crypto key and the * SHA-256 algorithm. * @param key The secret crypto key in utf-8 or ArrayBuffer format. * @param msg The plain text message. * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer * format. */ async signWithHmacSha256(key, msg) { // Convert key, if provided in ArrayBuffer format, to string. const rawKey = typeof key === 'string' ? key : String.fromCharCode(...new Uint16Array(key)); // eslint-disable-next-line node/no-unsupported-features/node-builtins const enc = new TextEncoder(); const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { name: 'HMAC', hash: { name: 'SHA-256', }, }, false, ['sign']); return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); } } exports.BrowserCrypto = BrowserCrypto; //# sourceMappingURL=crypto.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/https-proxy-agent/node_modules/ms/index.js
aws/lti-middleware/node_modules/https-proxy-agent/node_modules/ms/index.js
/** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/index.js
aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/index.js
/** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = require('./browser.js'); } else { module.exports = require('./node.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/https-proxy-agent/node_modules/debug/src/browser.js
aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/browser.js
/* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/common.js
aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/common.js
/** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require('ms'); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/node.js
aws/lti-middleware/node_modules/https-proxy-agent/node_modules/debug/src/node.js
/** * Module dependencies. */ const tty = require('tty'); const util = require('util'); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); };
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/https-proxy-agent/dist/parse-proxy-response.js
aws/lti-middleware/node_modules/https-proxy-agent/dist/parse-proxy-response.js
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const debug_1 = __importDefault(require("debug")); const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); function parseProxyResponse(socket) { return new Promise((resolve, reject) => { // we need to buffer any HTTP traffic that happens with the proxy before we get // the CONNECT response, so that if the response is anything other than an "200" // response code, then we can re-play the "data" events on the socket once the // HTTP parser is hooked up... let buffersLength = 0; const buffers = []; function read() { const b = socket.read(); if (b) ondata(b); else socket.once('readable', read); } function cleanup() { socket.removeListener('end', onend); socket.removeListener('error', onerror); socket.removeListener('close', onclose); socket.removeListener('readable', read); } function onclose(err) { debug('onclose had error %o', err); } function onend() { debug('onend'); } function onerror(err) { cleanup(); debug('onerror %o', err); reject(err); } function ondata(b) { buffers.push(b); buffersLength += b.length; const buffered = Buffer.concat(buffers, buffersLength); const endOfHeaders = buffered.indexOf('\r\n\r\n'); if (endOfHeaders === -1) { // keep buffering debug('have not received end of HTTP headers yet...'); read(); return; } const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); const statusCode = +firstLine.split(' ')[1]; debug('got proxy server response: %o', firstLine); resolve({ statusCode, buffered }); } socket.on('error', onerror); socket.on('close', onclose); socket.on('end', onend); read(); }); } exports.default = parseProxyResponse; //# sourceMappingURL=parse-proxy-response.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/https-proxy-agent/dist/index.js
aws/lti-middleware/node_modules/https-proxy-agent/dist/index.js
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const agent_1 = __importDefault(require("./agent")); function createHttpsProxyAgent(opts) { return new agent_1.default(opts); } (function (createHttpsProxyAgent) { createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; createHttpsProxyAgent.prototype = agent_1.default.prototype; })(createHttpsProxyAgent || (createHttpsProxyAgent = {})); module.exports = createHttpsProxyAgent; //# sourceMappingURL=index.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/https-proxy-agent/dist/agent.js
aws/lti-middleware/node_modules/https-proxy-agent/dist/agent.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const net_1 = __importDefault(require("net")); const tls_1 = __importDefault(require("tls")); const url_1 = __importDefault(require("url")); const assert_1 = __importDefault(require("assert")); const debug_1 = __importDefault(require("debug")); const agent_base_1 = require("agent-base"); const parse_proxy_response_1 = __importDefault(require("./parse-proxy-response")); const debug = debug_1.default('https-proxy-agent:agent'); /** * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * * Outgoing HTTP requests are first tunneled through the proxy server using the * `CONNECT` HTTP request method to establish a connection to the proxy server, * and then the proxy server connects to the destination target and issues the * HTTP request from the proxy server. * * `https:` requests have their socket connection upgraded to TLS once * the connection to the proxy server has been established. * * @api public */ class HttpsProxyAgent extends agent_base_1.Agent { constructor(_opts) { let opts; if (typeof _opts === 'string') { opts = url_1.default.parse(_opts); } else { opts = _opts; } if (!opts) { throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); } debug('creating new HttpsProxyAgent instance: %o', opts); super(opts); const proxy = Object.assign({}, opts); // If `true`, then connect to the proxy server over TLS. // Defaults to `false`. this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); // Prefer `hostname` over `host`, and set the `port` if needed. proxy.host = proxy.hostname || proxy.host; if (typeof proxy.port === 'string') { proxy.port = parseInt(proxy.port, 10); } if (!proxy.port && proxy.host) { proxy.port = this.secureProxy ? 443 : 80; } // ALPN is supported by Node.js >= v5. // attempt to negotiate http/1.1 for proxy servers that support http/2 if (this.secureProxy && !('ALPNProtocols' in proxy)) { proxy.ALPNProtocols = ['http 1.1']; } if (proxy.host && proxy.path) { // If both a `host` and `path` are specified then it's most likely // the result of a `url.parse()` call... we need to remove the // `path` portion so that `net.connect()` doesn't attempt to open // that as a Unix socket file. delete proxy.path; delete proxy.pathname; } this.proxy = proxy; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. * * @api protected */ callback(req, opts) { return __awaiter(this, void 0, void 0, function* () { const { proxy, secureProxy } = this; // Create a socket connection to the proxy server. let socket; if (secureProxy) { debug('Creating `tls.Socket`: %o', proxy); socket = tls_1.default.connect(proxy); } else { debug('Creating `net.Socket`: %o', proxy); socket = net_1.default.connect(proxy); } const headers = Object.assign({}, proxy.headers); const hostname = `${opts.host}:${opts.port}`; let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; // Inject the `Proxy-Authorization` header if necessary. if (proxy.auth) { headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; } // The `Host` header should only include the port // number when it is not the default port. let { host, port, secureEndpoint } = opts; if (!isDefaultPort(port, secureEndpoint)) { host += `:${port}`; } headers.Host = host; headers.Connection = 'close'; for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r\n`; } const proxyResponsePromise = parse_proxy_response_1.default(socket); socket.write(`${payload}\r\n`); const { statusCode, buffered } = yield proxyResponsePromise; if (statusCode === 200) { req.once('socket', resume); if (opts.secureEndpoint) { // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); const servername = opts.servername || opts.host; return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, servername })); } return socket; } // Some other status code that's not 200... need to re-play the HTTP // header "data" events onto the socket once the HTTP machinery is // attached so that the node core `http` can parse and handle the // error status code. // Close the original socket, and a new "fake" socket is returned // instead, so that the proxy doesn't get the HTTP request // written to it (which may contain `Authorization` headers or other // sensitive data). // // See: https://hackerone.com/reports/541502 socket.destroy(); const fakeSocket = new net_1.default.Socket({ writable: false }); fakeSocket.readable = true; // Need to wait for the "socket" event to re-play the "data" events. req.once('socket', (s) => { debug('replaying proxy buffer for failed request'); assert_1.default(s.listenerCount('data') > 0); // Replay the "buffered" Buffer onto the fake `socket`, since at // this point the HTTP module machinery has been hooked up for // the user. s.push(buffered); s.push(null); }); return fakeSocket; }); } } exports.default = HttpsProxyAgent; function resume(socket) { socket.resume(); } function isDefaultPort(port, secure) { return Boolean((!secure && port === 80) || (secure && port === 443)); } function isHTTPS(protocol) { return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; } function omit(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } //# sourceMappingURL=agent.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/pseudomap/map.js
aws/lti-middleware/node_modules/pseudomap/map.js
if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true' if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) { module.exports = Map } else { module.exports = require('./pseudomap') }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/pseudomap/pseudomap.js
aws/lti-middleware/node_modules/pseudomap/pseudomap.js
var hasOwnProperty = Object.prototype.hasOwnProperty module.exports = PseudoMap function PseudoMap (set) { if (!(this instanceof PseudoMap)) // whyyyyyyy throw new TypeError("Constructor PseudoMap requires 'new'") this.clear() if (set) { if ((set instanceof PseudoMap) || (typeof Map === 'function' && set instanceof Map)) set.forEach(function (value, key) { this.set(key, value) }, this) else if (Array.isArray(set)) set.forEach(function (kv) { this.set(kv[0], kv[1]) }, this) else throw new TypeError('invalid argument') } } PseudoMap.prototype.forEach = function (fn, thisp) { thisp = thisp || this Object.keys(this._data).forEach(function (k) { if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key) }, this) } PseudoMap.prototype.has = function (k) { return !!find(this._data, k) } PseudoMap.prototype.get = function (k) { var res = find(this._data, k) return res && res.value } PseudoMap.prototype.set = function (k, v) { set(this._data, k, v) } PseudoMap.prototype.delete = function (k) { var res = find(this._data, k) if (res) { delete this._data[res._index] this._data.size-- } } PseudoMap.prototype.clear = function () { var data = Object.create(null) data.size = 0 Object.defineProperty(this, '_data', { value: data, enumerable: false, configurable: true, writable: false }) } Object.defineProperty(PseudoMap.prototype, 'size', { get: function () { return this._data.size }, set: function (n) {}, enumerable: true, configurable: true }) PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () { throw new Error('iterators are not implemented in this version') } // Either identical, or both NaN function same (a, b) { return a === b || a !== a && b !== b } function Entry (k, v, i) { this.key = k this.value = v this._index = i } function find (data, k) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) return data[key] } } function set (data, k, v) { for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) { if (same(data[key].key, k)) { data[key].value = v return } } data.size++ data[key] = new Entry(k, v, key) }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/pseudomap/test/basic.js
aws/lti-middleware/node_modules/pseudomap/test/basic.js
var t = require('tap') process.env.TEST_PSEUDOMAP = 'true' var PM = require('../') runTests(PM) // if possible, verify that Map also behaves the same way if (typeof Map === 'function') runTests(Map) function runTests (Map) { t.throws(Map) var m = new Map() t.equal(m.size, 0) m.set(1, '1 string') t.equal(m.get(1), '1 string') t.equal(m.size, 1) m.size = 1000 t.equal(m.size, 1) m.size = 0 t.equal(m.size, 1) m = new Map([[1, 'number 1'], ['1', 'string 1']]) t.equal(m.get(1), 'number 1') t.equal(m.get('1'), 'string 1') t.equal(m.size, 2) m = new Map(m) t.equal(m.get(1), 'number 1') t.equal(m.get('1'), 'string 1') t.equal(m.size, 2) var akey = {} var bkey = {} m.set(akey, { some: 'data' }) m.set(bkey, { some: 'other data' }) t.same(m.get(akey), { some: 'data' }) t.same(m.get(bkey), { some: 'other data' }) t.equal(m.size, 4) var x = /x/ var y = /x/ m.set(x, 'x regex') m.set(y, 'y regex') t.equal(m.get(x), 'x regex') m.set(x, 'x again') t.equal(m.get(x), 'x again') t.equal(m.size, 6) m.set(NaN, 'not a number') t.equal(m.get(NaN), 'not a number') m.set(NaN, 'it is a ' + typeof NaN) t.equal(m.get(NaN), 'it is a number') m.set('NaN', 'stringie nan') t.equal(m.get(NaN), 'it is a number') t.equal(m.get('NaN'), 'stringie nan') t.equal(m.size, 8) m.delete(NaN) t.equal(m.get(NaN), undefined) t.equal(m.size, 7) var expect = [ { value: 'number 1', key: 1 }, { value: 'string 1', key: '1' }, { value: { some: 'data' }, key: {} }, { value: { some: 'other data' }, key: {} }, { value: 'x again', key: /x/ }, { value: 'y regex', key: /x/ }, { value: 'stringie nan', key: 'NaN' } ] var actual = [] m.forEach(function (value, key) { actual.push({ value: value, key: key }) }) t.same(actual, expect) m.clear() t.equal(m.size, 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/get-caller-file/index.js
aws/lti-middleware/node_modules/get-caller-file/index.js
"use strict"; // Call this function in a another function to find out the file from // which that function was called from. (Inspects the v8 stack trace) // // Inspired by http://stackoverflow.com/questions/13227489 module.exports = function getCallerFile(position) { if (position === void 0) { position = 2; } if (position >= Error.stackTraceLimit) { throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); } var oldPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = function (_, stack) { return stack; }; var stack = new Error().stack; Error.prepareStackTrace = oldPrepareStackTrace; if (stack !== null && typeof stack === 'object') { // stack[0] holds this file // stack[1] holds where this function was called // stack[2] holds the file we're interested in return stack[position] ? stack[position].getFileName() : undefined; } }; //# sourceMappingURL=index.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/await-to-js/dist/await-to-js.umd.js
aws/lti-middleware/node_modules/await-to-js/dist/await-to-js.umd.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.awaitToJs = {}))); }(this, (function (exports) { 'use strict'; /** * @param { Promise } promise * @param { Object= } errorExt - Additional Information you can pass to the err object * @return { Promise } */ function to(promise, errorExt) { return promise .then(function (data) { return [null, data]; }) .catch(function (err) { if (errorExt) { Object.assign(err, errorExt); } return [err, undefined]; }); } exports.to = to; exports['default'] = to; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=await-to-js.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/await-to-js/dist/await-to-js.es5.js
aws/lti-middleware/node_modules/await-to-js/dist/await-to-js.es5.js
/** * @param { Promise } promise * @param { Object= } errorExt - Additional Information you can pass to the err object * @return { Promise } */ function to(promise, errorExt) { return promise .then(function (data) { return [null, data]; }) .catch(function (err) { if (errorExt) { Object.assign(err, errorExt); } return [err, undefined]; }); } export { to }; export default to; //# sourceMappingURL=await-to-js.es5.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/await-to-js/dist/docs/assets/js/main.js
aws/lti-middleware/node_modules/await-to-js/dist/docs/assets/js/main.js
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){function s(a){var b=a.length,c=n.type(a);return"function"!==c&&!n.isWindow(a)&&(!(1!==a.nodeType||!b)||("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a))}function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}function D(a,b){for(;(a=a[b])&&1!==a.nodeType;);return a}function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),"string"==typeof(c=a.getAttribute(d))){try{c="true"===c||"false"!==c&&("null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c)}catch(e){}M.set(a,b,c)}else c=void 0;return c}function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qb[0].contentDocument,b.write(),b.close(),c=sb(a,b),qb.detach()),rb[a]=c),c}function xb(a,b,c){var d,e,f,g,h=a.style;return c=c||wb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),vb.test(g)&&ub.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function yb(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}function Fb(a,b){if(b in a)return b;for(var c=b[0].toUpperCase()+b.slice(1),d=b,e=Eb.length;e--;)if((b=Eb[e]+c)in a)return b;return d}function Gb(a,b,c){var d=Ab.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Hb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ib(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wb(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xb(a,b,f),(0>e||null==e)&&(e=a.style[b]),vb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Hb(a,b,c||(g?"border":"content"),d,f)+"px"}function Jb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",tb(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Kb(a,b,c,d,e){return new Kb.prototype.init(a,b,c,d,e)}function Sb(){return setTimeout(function(){Lb=void 0}),Lb=n.now()}function Tb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ub(a,b,c){for(var d,e=(Rb[b]||[]).concat(Rb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Vb(a,b,c){var d,e,f,g,h,i,j,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),"inline"===("none"===j?L.get(a,"olddisplay")||tb(a.nodeName):j)&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Nb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?tb(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ub(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),(g=n.cssHooks[d])&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xb(a,b,c){var d,e,f=0,g=Qb.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Lb||Sb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Lb||Sb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wb(k,j.opts.specialEasing);g>f;f++)if(d=Qb[f].call(j,a,k,j.opts))return d;return n.map(k,Ub,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function rc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))for(;d=f[e++];)"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function sc(a,b,c,d){function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}var e={},f=a===oc;return g(b.dataTypes[0])||!e["*"]&&g("*")}function tc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function uc(a,b,c){for(var d,e,f,g,h=a.contents,i=a.dataTypes;"*"===i[0];)i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function vc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];for(f=k.shift();f;)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(!(g=j[i+" "+f]||j["* "+f]))for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){!0===g?g=j[e]:!0!==j[e]&&(f=h[0],k.unshift(h[1]));break}if(!0!==g)if(g&&a.throws)b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}function Bc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||xc.test(a)?d(a,e):Bc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Bc(a+"["+e+"]",b[e],c,d)}function Kc(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.1",n=function(a,b){return new n.fn.init(a,b)},r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"===n.type(a)&&!a.nodeType&&!n.isWindow(a)&&!(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;(a=n.trim(a))&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var e=0,f=a.length,g=s(a);if(c){if(g)for(;f>e&&!1!==b.apply(a[e],c);e++);else for(e in a)if(!1===b.apply(a[e],c))break}else if(g)for(;f>e&&!1!==b.call(a[e],e,a[e]);e++);else for(e in a)if(!1===b.call(a[e],e,a[e]))break;return a},trim:function(a){return null==a?"":(a+"").replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var e=[],f=0,g=a.length,h=!c;g>f;f++)!b(a[f],f)!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)null!=(d=b(a[f],f,c))&&i.push(d);else for(f in a)null!=(d=b(a[f],f,c))&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});var t=function(a){function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(!(h=b.getElementById(j))||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){for(o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;l--;)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}var a=[];return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){for(var c=a.split("|"),e=a.length;e--;)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}function pb(){}function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){for(;b=b[d];)if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){for(;b=b[d];)if((1===b.nodeType||e)&&a(b,c,g))return!0}else for(;b=b[d];)if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d)for(j=ub(r,n),d(j,[],h,i),k=j.length;k--;)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l));if(f){if(e||a){if(e){for(j=[],k=r.length;k--;)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}for(k=r.length;k--;)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e&&!d.relative[a[e].type];e++);return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){for(m=0;o=a[m++];)if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){for(m=0;o=b[m++];)o(r,s,g,h);if(f){if(p>0)for(;q--;)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d||(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);for(c=a;c=c.parentNode;)h.unshift(c);for(c=b;c=c.parentNode;)i.unshift(c);for(;h[d]===i[d];)d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){for(;b=a[f++];)b===a[f]&&(e=d.push(f));for(;e--;)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else for(;b=a[d++];)c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){for(;p;){for(l=b;l=l[p];)if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){for(k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];l=++n&&l&&l[p]||(m=n=0)||o.pop();)if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else for(;(l=++n&&l&&l[p]||(m=n=0)||o.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++m||(s&&((l[u]||(l[u]={}))[a]=[w,m]),l!==b)););return(m-=e)===d||m%d==0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){for(var d,f=e(a,b),g=f.length;g--;)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){for(var f,g=d(a,null,e,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do{if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return(c=c.toLowerCase())===a||0===c.indexOf(a+"-")}while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return!1===a.disabled},disabled:function(a){return!0===a.disabled},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,!0===a.selected},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=function(a){return function(b){return"input"===b.nodeName.toLowerCase()&&b.type===a}}(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=function(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}(b);return pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);for(h=a,i=[],j=d.preFilter;h;){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)},h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){for(b||(b=g(a)),c=b.length;c--;)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(!(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0]))return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}for(i=X.needsContext.test(a)?0:j.length;i--&&(k=j[i],!d.relative[l=k.type]);)if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),!(a=f.length&&qb(j)))return I.apply(e,f),e;break}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:!0===a[b]?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
true
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/await-to-js/dist/docs/assets/js/search.js
aws/lti-middleware/node_modules/await-to-js/dist/docs/assets/js/search.js
var typedoc = typedoc || {}; typedoc.search = typedoc.search || {}; typedoc.search.data = {"kinds":{"1":"External module","64":"Function"},"rows":[{"id":0,"kind":1,"name":"\"await-to-js\"","url":"modules/_await_to_js_.html","classes":"tsd-kind-external-module"},{"id":1,"kind":64,"name":"to","url":"modules/_await_to_js_.html#to","classes":"tsd-kind-function tsd-parent-kind-external-module tsd-has-type-parameter","parent":"\"await-to-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/express-unless/index.js
aws/lti-middleware/node_modules/express-unless/index.js
var URL = require('url'); function unless(middleware, options) { if (typeof options === 'undefined') { options = middleware; middleware = this; } var opts = typeof options === 'function' ? {custom: options} : options; opts.useOriginalUrl = (typeof opts.useOriginalUrl === 'undefined') ? true : opts.useOriginalUrl; const result = async function (req, res, next) { var url = URL.parse((opts.useOriginalUrl ? req.originalUrl : req.url) || req.url || '', true); var skip = false; if (opts.custom) { skip = skip || (await opts.custom(req)); } var paths = oneOrMany(opts.path); if (paths) { skip = skip || paths.some(function (p) { var methods = p.methods || oneOrMany(p.method); return isUrlMatch(p, url.pathname) && isMethodMatch(methods, req.method); }); } var exts = (!opts.ext || Array.isArray(opts.ext)) ? opts.ext : [opts.ext]; if (exts) { skip = skip || exts.some(function (ext) { return url.pathname.substr(ext.length * -1) === ext; }); } var methods = oneOrMany(opts.method); if (methods) { skip = skip || methods.indexOf(req.method) > -1; } if (skip) { return next(); } middleware(req, res, next); }; result.unless = unless; return result; } function oneOrMany(elementOrArray) { return !elementOrArray || Array.isArray(elementOrArray) ? elementOrArray : [elementOrArray]; } function isUrlMatch(p, url) { var ret = (typeof p === 'string' && p === url) || (p instanceof RegExp && !!p.exec(url)); if (p instanceof RegExp) { p.lastIndex = 0; } if (p && p.url) { ret = isUrlMatch(p.url, url); } return ret; } function isMethodMatch(methods, m) { if (!methods) { return true; } methods = oneOrMany(methods); return methods.indexOf(m) > -1; } module.exports = unless;
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express-unless/test/unless.tests.js
aws/lti-middleware/node_modules/express-unless/test/unless.tests.js
var unless = require('..'); var assert = require('chai').assert; var noop = function(){}; function testMiddleware (req, res, next) { req.called = true; next(); } testMiddleware.unless = unless; describe('express-unless', function () { describe('with PATH and method exception', function () { var mid = testMiddleware.unless({ path: [ { url: '/test', methods: ['POST', 'GET'] }, { url: '/bar', method: 'PUT' }, '/foo' ] }); it('should not call the middleware when path and method match', function () { var req = { originalUrl: '/test?das=123', method: 'POST' }; mid(req, {}, noop); assert.notOk(req.called); req = { originalUrl: '/test?test=123', method: 'GET' }; mid(req, {}, noop); assert.notOk(req.called); req = { originalUrl: '/bar?test=123', method: 'PUT' }; mid(req, {}, noop); assert.notOk(req.called); req = { originalUrl: '/foo', method: 'PUT' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when path or method mismatch', function () { var req = { originalUrl: '/test?test=123', method: 'PUT' }; mid(req, {}, noop); assert.ok(req.called); req = { originalUrl: '/bar?test=123', method: 'GET' }; mid(req, {}, noop); assert.ok(req.called); req = { originalUrl: '/unless?test=123', method: 'PUT' }; mid(req, {}, noop); assert.ok(req.called); }); }); describe('with PATH exception', function () { var mid = testMiddleware.unless({ path: ['/test', '/fobo'] }); it('should not call the middleware when one of the path match', function () { var req = { originalUrl: '/test?das=123' }; mid(req, {}, noop); assert.notOk(req.called); req = { originalUrl: '/fobo?test=123' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when the path doesnt match', function () { var req = { originalUrl: '/foobar/test=123' }; mid(req, {}, noop); assert.ok(req.called); }); }); describe('with PATH (regex) exception', function () { var mid = testMiddleware.unless({ path: ['/test', /ag$/ig] }); it('should not call the middleware when the regex match', function () { var req = { originalUrl: '/foboag?test=123' }; var req2 = { originalUrl: '/foboag?test=456' }; mid(req, {}, noop); mid(req2, {}, noop); assert.notOk(req.called); assert.notOk(req2.called); }); }); describe('with PATH (useOriginalUrl) exception', function () { var mid = testMiddleware.unless({ path: ['/test', '/fobo'], useOriginalUrl: false }); it('should not call the middleware when one of the path match '+ 'req.url instead of req.originalUrl', function () { var req = { originalUrl: '/orig/test?das=123', url: '/test?das=123' }; mid(req, {}, noop); assert.notOk(req.called); req = { originalUrl: '/orig/fobo?test=123', url: '/fobo?test=123' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when the path doesnt match '+ 'req.url even if path matches req.originalUrl', function () { var req = { originalUrl: '/test/test=123', url: '/foobar/test=123' }; mid(req, {}, noop); assert.ok(req.called); }); }); describe('with EXT exception', function () { var mid = testMiddleware.unless({ ext: ['jpg', 'html', 'txt'] }); it('should not call the middleware when the ext match', function () { var req = { originalUrl: '/foo.html?das=123' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when the ext doesnt match', function () { var req = { originalUrl: '/foobar/test=123' }; mid(req, {}, noop); assert.ok(req.called); }); }); describe('with METHOD exception', function () { var mid = testMiddleware.unless({ method: ['OPTIONS', 'DELETE'] }); it('should not call the middleware when the method match', function () { var req = { originalUrl: '/foo.html?das=123', method: 'OPTIONS' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when the method doesnt match', function () { var req = { originalUrl: '/foobar/test=123', method: 'PUT' }; mid(req, {}, noop); assert.ok(req.called); }); }); describe('with custom exception', function () { var mid = testMiddleware.unless({ custom: function (req) { return req.baba; } }); it('should not call the middleware when the custom rule match', function () { var req = { baba: true }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when the custom rule doesnt match', function (done) { var req = { baba: false }; mid(req, {}, () => { assert.ok(req.called); done(); }); }); }); describe('with async custom exception', function () { var mid = testMiddleware.unless({ custom: async function (req) { return req.baba; } }); it('should not call the middleware when the async custom rule match', function (done) { var req = { baba: true }; mid(req, {}, () => { assert.notOk(req.called); done(); }); }); it('should call the middleware when the async custom rule doesnt match', function (done) { var req = { baba: false }; mid(req, {}, () => { assert.ok(req.called); done(); }); }); }); describe('without originalUrl', function () { var mid = testMiddleware.unless({ path: ['/test'] }); it('should not call the middleware when one of the path match', function () { var req = { url: '/test?das=123' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when the path doesnt match', function () { var req = { url: '/foobar/test=123' }; mid(req, {}, noop); assert.ok(req.called); }); }); describe('chaining', function () { var mid = testMiddleware .unless({ path: '/test' }) .unless({ method: 'GET' }); it('should not call the middleware when first unless match', function () { var req = { url: '/test' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should not call the middleware when second unless match', function () { var req = { url: '/safsa', method: 'GET' }; mid(req, {}, noop); assert.notOk(req.called); }); it('should call the middleware when none of the conditions are met', function () { var req = { url: '/foobar/test=123' }; mid(req, {}, noop); assert.ok(req.called); }); }); });
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/end-of-stream/index.js
aws/lti-middleware/node_modules/end-of-stream/index.js
var once = require('once'); var noop = function() {}; var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { process.nextTick(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { 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 && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function() { cancelled = true; 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('exit', onexit); 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/jose/lib/index.js
aws/lti-middleware/node_modules/jose/lib/index.js
module.exports = { JWE: require('./jwe'), JWK: require('./jwk'), JWKS: require('./jwks'), JWS: require('./jws'), JWT: require('./jwt'), errors: require('./errors') }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/jose/lib/errors.js
aws/lti-middleware/node_modules/jose/lib/errors.js
const CODES = { JOSEAlgNotWhitelisted: 'ERR_JOSE_ALG_NOT_WHITELISTED', JOSECritNotUnderstood: 'ERR_JOSE_CRIT_NOT_UNDERSTOOD', JOSEInvalidEncoding: 'ERR_JOSE_INVALID_ENCODING', JOSEMultiError: 'ERR_JOSE_MULTIPLE_ERRORS', JOSENotSupported: 'ERR_JOSE_NOT_SUPPORTED', JWEDecryptionFailed: 'ERR_JWE_DECRYPTION_FAILED', JWEInvalid: 'ERR_JWE_INVALID', JWKImportFailed: 'ERR_JWK_IMPORT_FAILED', JWKInvalid: 'ERR_JWK_INVALID', JWKKeySupport: 'ERR_JWK_KEY_SUPPORT', JWKSNoMatchingKey: 'ERR_JWKS_NO_MATCHING_KEY', JWSInvalid: 'ERR_JWS_INVALID', JWSVerificationFailed: 'ERR_JWS_VERIFICATION_FAILED', JWTClaimInvalid: 'ERR_JWT_CLAIM_INVALID', JWTExpired: 'ERR_JWT_EXPIRED', JWTMalformed: 'ERR_JWT_MALFORMED' } const DEFAULT_MESSAGES = { JWEDecryptionFailed: 'decryption operation failed', JWEInvalid: 'JWE invalid', JWKSNoMatchingKey: 'no matching key found in the KeyStore', JWSInvalid: 'JWS invalid', JWSVerificationFailed: 'signature verification failed' } class JOSEError extends Error { constructor (message) { super(message) if (message === undefined) { this.message = DEFAULT_MESSAGES[this.constructor.name] } this.name = this.constructor.name this.code = CODES[this.constructor.name] Error.captureStackTrace(this, this.constructor) } } const isMulti = e => e instanceof JOSEMultiError class JOSEMultiError extends JOSEError { constructor (errors) { super() let i while ((i = errors.findIndex(isMulti)) && i !== -1) { errors.splice(i, 1, ...errors[i]) } Object.defineProperty(this, 'errors', { value: errors }) } * [Symbol.iterator] () { for (const error of this.errors) { yield error } } } module.exports.JOSEError = JOSEError module.exports.JOSEAlgNotWhitelisted = class JOSEAlgNotWhitelisted extends JOSEError {} module.exports.JOSECritNotUnderstood = class JOSECritNotUnderstood extends JOSEError {} module.exports.JOSEInvalidEncoding = class JOSEInvalidEncoding extends JOSEError {} module.exports.JOSEMultiError = JOSEMultiError module.exports.JOSENotSupported = class JOSENotSupported extends JOSEError {} module.exports.JWEDecryptionFailed = class JWEDecryptionFailed extends JOSEError {} module.exports.JWEInvalid = class JWEInvalid extends JOSEError {} module.exports.JWKImportFailed = class JWKImportFailed extends JOSEError {} module.exports.JWKInvalid = class JWKInvalid extends JOSEError {} module.exports.JWKKeySupport = class JWKKeySupport extends JOSEError {} module.exports.JWKSNoMatchingKey = class JWKSNoMatchingKey extends JOSEError {} module.exports.JWSInvalid = class JWSInvalid extends JOSEError {} module.exports.JWSVerificationFailed = class JWSVerificationFailed extends JOSEError {} class JWTClaimInvalid extends JOSEError { constructor (message, claim = 'unspecified', reason = 'unspecified') { super(message) this.claim = claim this.reason = reason } } module.exports.JWTClaimInvalid = JWTClaimInvalid module.exports.JWTExpired = class JWTExpired extends JWTClaimInvalid {} module.exports.JWTMalformed = class JWTMalformed extends JOSEError {}
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/jose/lib/jwk/import.js
aws/lti-middleware/node_modules/jose/lib/jwk/import.js
const { createPublicKey, createPrivateKey, createSecretKey, KeyObject } = require('../help/key_object') const base64url = require('../help/base64url') const isObject = require('../help/is_object') const { jwkToPem } = require('../help/key_utils') const errors = require('../errors') const RSAKey = require('./key/rsa') const ECKey = require('./key/ec') const OKPKey = require('./key/okp') const OctKey = require('./key/oct') const importable = new Set(['string', 'buffer', 'object']) const mergedParameters = (target = {}, source = {}) => { return { alg: source.alg, key_ops: source.key_ops, kid: source.kid, use: source.use, x5c: source.x5c, x5t: source.x5t, 'x5t#S256': source['x5t#S256'], ...target } } const openSSHpublicKey = /^[a-zA-Z0-9-]+ AAAA(?:[0-9A-Za-z+/])+(?:==|=)?(?: .*)?$/ const asKey = (key, parameters, { calculateMissingRSAPrimes = false } = {}) => { let privateKey, publicKey, secret if (!importable.has(typeof key)) { throw new TypeError('key argument must be a string, buffer or an object') } if (parameters !== undefined && !isObject(parameters)) { throw new TypeError('parameters argument must be a plain object when provided') } if (key instanceof KeyObject) { switch (key.type) { case 'private': privateKey = key break case 'public': publicKey = key break case 'secret': secret = key break } } else if (typeof key === 'object' && key && 'kty' in key && key.kty === 'oct') { // symmetric key <Object> try { secret = createSecretKey(base64url.decodeToBuffer(key.k)) } catch (err) { if (!('k' in key)) { secret = { type: 'secret' } } } parameters = mergedParameters(parameters, key) } else if (typeof key === 'object' && key && 'kty' in key) { // assume JWK formatted asymmetric key <Object> ({ calculateMissingRSAPrimes = false } = parameters || { calculateMissingRSAPrimes }) let pem try { pem = jwkToPem(key, { calculateMissingRSAPrimes }) } catch (err) { if (err instanceof errors.JOSEError) { throw err } } if (pem && key.d) { privateKey = createPrivateKey(pem) } else if (pem) { publicKey = createPublicKey(pem) } parameters = mergedParameters({}, key) } else if (key && (typeof key === 'object' || typeof key === 'string')) { // <Object> | <string> | <Buffer> passed to crypto.createPrivateKey or crypto.createPublicKey or <Buffer> passed to crypto.createSecretKey try { privateKey = createPrivateKey(key) } catch (err) { if (err instanceof errors.JOSEError) { throw err } } try { publicKey = createPublicKey(key) if (key.startsWith('-----BEGIN CERTIFICATE-----') && (!parameters || !('x5c' in parameters))) { parameters = mergedParameters(parameters, { x5c: [key.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '')] }) } } catch (err) { if (err instanceof errors.JOSEError) { throw err } } try { // this is to filter out invalid PEM keys and certs, i'll rather have them fail import then // have them imported as symmetric "oct" keys if (!key.includes('-----BEGIN') && !openSSHpublicKey.test(key.toString('ascii').replace(/[\r\n]/g, ''))) { secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key)) } } catch (err) {} } const keyObject = privateKey || publicKey || secret if (privateKey || publicKey) { switch (keyObject.asymmetricKeyType) { case 'rsa': return new RSAKey(keyObject, parameters) case 'ec': return new ECKey(keyObject, parameters) case 'ed25519': case 'ed448': case 'x25519': case 'x448': return new OKPKey(keyObject, parameters) default: throw new errors.JOSENotSupported('only RSA, EC and OKP asymmetric keys are supported') } } else if (secret) { return new OctKey(keyObject, parameters) } throw new errors.JWKImportFailed('key import failed') } module.exports = asKey
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/jose/lib/jwk/generate.js
aws/lti-middleware/node_modules/jose/lib/jwk/generate.js
const errors = require('../errors') const importKey = require('./import') const RSAKey = require('./key/rsa') const ECKey = require('./key/ec') const OKPKey = require('./key/okp') const OctKey = require('./key/oct') const generate = async (kty, crvOrSize, params, generatePrivate = true) => { switch (kty) { case 'RSA': return importKey( await RSAKey.generate(crvOrSize, generatePrivate), params ) case 'EC': return importKey( await ECKey.generate(crvOrSize, generatePrivate), params ) case 'OKP': return importKey( await OKPKey.generate(crvOrSize, generatePrivate), params ) case 'oct': return importKey( await OctKey.generate(crvOrSize, generatePrivate), params ) default: throw new errors.JOSENotSupported(`unsupported key type: ${kty}`) } } const generateSync = (kty, crvOrSize, params, generatePrivate = true) => { switch (kty) { case 'RSA': return importKey(RSAKey.generateSync(crvOrSize, generatePrivate), params) case 'EC': return importKey(ECKey.generateSync(crvOrSize, generatePrivate), params) case 'OKP': return importKey(OKPKey.generateSync(crvOrSize, generatePrivate), params) case 'oct': return importKey(OctKey.generateSync(crvOrSize, generatePrivate), params) default: throw new errors.JOSENotSupported(`unsupported key type: ${kty}`) } } module.exports.generate = generate module.exports.generateSync = generateSync
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false
CAHLR/OATutor
https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/jose/lib/jwk/index.js
aws/lti-middleware/node_modules/jose/lib/jwk/index.js
const Key = require('./key/base') const None = require('./key/none') const EmbeddedJWK = require('./key/embedded.jwk') const EmbeddedX5C = require('./key/embedded.x5c') const importKey = require('./import') const generate = require('./generate') module.exports = { ...generate, asKey: importKey, isKey: input => input instanceof Key, None, EmbeddedJWK, EmbeddedX5C }
javascript
MIT
10a5baf153a505267af8045b05c217b4be6bd8b4
2026-01-05T03:39:09.711315Z
false