code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
private async getKey() {
const bKey = AesCbcCryptor.encoder.encode(this.cipherKey);
const abHash = await crypto.subtle.digest('SHA-256', bKey.buffer);
return crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt']);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get identifier() {
return 'ACRH';
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: decode(
this.CryptoJS.AES.encrypt(data, this.encryptedKey, {
iv: this.bufferToWordArray(abIv),
mode: this.CryptoJS.mode.CBC,
}).ciphertext.toString(this.CryptoJS.enc.Base64), | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
private getIv() {
return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE));
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get algo() {
return 'AES-CBC';
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
decrypt(encryptedData: EncryptedDataType) {
const data = typeof encryptedData.data === 'string' ? encryptedData.data : encode(encryptedData.data);
return this.cryptor.decrypt(data);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async decryptFile(file: PubNubFileType, File: PubNubFileType) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: can not detect cipherKey from old Config
return this.fileCryptor.decryptFile(this.config.cipherKey, file, File);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get identifier() {
return '';
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async encryptFile(file: PubNubFileType, File: PubNubFileType) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: can not detect cipherKey from old Config
return this.fileCryptor.encryptFile(this.config?.cipherKey, file, File);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: this.cryptor.encrypt(stringData),
metadata: null,
};
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
constructor(config: any) {
this.config = config;
this.cryptor = new Crypto({ config });
this.fileCryptor = new FileCryptor();
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get identifier() {
return this._identifier;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
encrypt(data: ArrayBuffer | string) {
const encrypted = (this.defaultCryptor as ICryptor).encrypt(data);
if (!encrypted.metadata) return encrypted.data;
const headerData = this.getHeaderData(encrypted);
return this.concatArrayBuffer(headerData!, encrypted.data);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
constructor(cryptoModuleConfiguration: CryptoModuleConfiguration) {
this.defaultCryptor = cryptoModuleConfiguration.default;
this.cryptors = cryptoModuleConfiguration.cryptors ?? [];
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
set identifier(value) {
this._identifier = value;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
static tryParse(data: ArrayBuffer) {
const encryptedData = new Uint8Array(data);
let sentinel: any = '';
let version = null;
if (encryptedData.byteLength >= 4) {
sentinel = encryptedData.slice(0, 4);
if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) return '';
}
if (encryptedData.byteLength >= 5) {
version = (encryptedData as Uint8Array)[4] as number;
} else {
throw new Error('decryption error. invalid header version');
}
if (version > CryptorHeader.MAX_VERSION) throw new Error('unknown cryptor error');
let identifier: any = '';
let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH;
if (encryptedData.byteLength >= pos) {
identifier = encryptedData.slice(5, pos);
} else {
throw new Error('decryption error. invalid crypto identifier');
}
let metadataLength = null;
if (encryptedData.byteLength >= pos + 1) {
metadataLength = (encryptedData as Uint8Array)[pos];
} else {
throw new Error('decryption error. invalid metadata length');
}
pos += 1;
if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) {
metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0);
pos += 2;
}
return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get version() {
return CryptorHeader.VERSION;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
cryptors: [new AesCbcCryptor({ cipherKey: config.cipherKey })],
});
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
const cryptor = this.getAllCryptors().find((c) => id === c.identifier); | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
private getAllCryptors() {
return [this.defaultCryptor, ...this.cryptors];
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: this.concatArrayBuffer(this.getHeaderData(encrypted)!, encrypted.data),
}); | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get data() {
let pos = 0;
const header = new Uint8Array(this.length);
const encoder = new TextEncoder();
header.set(encoder.encode(CryptorHeader.SENTINEL));
pos += CryptorHeader.SENTINEL.length;
header[pos] = this.version;
pos++;
if (this.identifier) header.set(encoder.encode(this.identifier), pos);
pos += CryptorHeader.IDENTIFIER_LENGTH;
const metadataLength = this.metadataLength;
if (metadataLength < 255) {
header[pos] = metadataLength;
} else {
header.set([255, metadataLength >> 8, metadataLength & 0xff], pos);
}
return header;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
static from(id: string, metadata: ArrayBuffer) {
if (id === CryptorHeader.LEGACY_IDENTIFIER) return;
return new CryptorHeaderV1(id, metadata.byteLength);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: encryptedData.slice(header.length),
metadata: metadata,
});
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get length() {
return (
CryptorHeader.SENTINEL.length +
1 +
CryptorHeader.IDENTIFIER_LENGTH +
(this.metadataLength < 255 ? 1 : 3) +
this.metadataLength
);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
get metadataLength() {
return this._metadataLength;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
new LegacyCryptor({
cipherKey: config.cipherKey,
useRandomIVs: config.useRandomIVs ?? true,
}),
],
});
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
set metadataLength(value) {
this._metadataLength = value;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
constructor(id: string, metadataLength: number) {
this._identifier = id;
this._metadataLength = metadataLength;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
static withDefaultCryptor(defaultCryptor: CryptorType) {
return new this({ default: defaultCryptor });
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
decryptBuffer(key, ciphertext) {
const bIv = ciphertext.slice(0, NodeCryptography.IV_LENGTH);
const bCiphertext = ciphertext.slice(NodeCryptography.IV_LENGTH);
if (bCiphertext.byteLength <= 0) throw new Error('decryption error: empty content');
const aes = createDecipheriv(this.algo, key, bIv);
return Buffer.concat([aes.update(bCiphertext), aes.final()]);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
transform(chunk, _, cb) {
if (!inited) {
inited = true;
this.push(Buffer.concat([bIv, chunk]));
} else {
this.push(chunk);
}
cb();
}, | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async encryptStream(key, stream) {
const bIv = this.getIv();
const aes = createCipheriv('aes-256-cbc', key, bIv).setAutoPadding(true);
let inited = false;
return stream.pipe(aes).pipe(
new Transform({
transform(chunk, _, cb) {
if (!inited) {
inited = true;
this.push(Buffer.concat([bIv, chunk]));
} else {
this.push(chunk);
}
cb();
},
}),
);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async decryptArrayBuffer(key, ciphertext) {
const abIv = ciphertext.slice(0, 16);
if (ciphertext.slice(WebCryptography.IV_LENGTH).byteLength <= 0) throw new Error('decryption error: empty content');
const data = await crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: abIv },
key,
ciphertext.slice(WebCryptography.IV_LENGTH),
);
return data;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async encryptString(key, plaintext) {
const abIv = crypto.getRandomValues(new Uint8Array(16));
const abPlaintext = WebCryptography.encoder.encode(plaintext).buffer;
const abPayload = await crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext);
const ciphertext = concatArrayBuffer(abIv.buffer, abPayload);
return WebCryptography.decoder.decode(ciphertext);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async encryptFile(key, file, File) {
if (file.data.byteLength <= 0) throw new Error('encryption error. empty content');
const bKey = await this.getKey(key);
const abPlaindata = await file.data.arrayBuffer();
const abCipherdata = await this.encryptArrayBuffer(bKey, abPlaindata);
return File.create({
name: file.name,
mimeType: 'application/octet-stream',
data: abCipherdata,
});
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async getKey(key) {
const digest = await crypto.subtle.digest('SHA-256', WebCryptography.encoder.encode(key));
const hashHex = Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
const abKey = WebCryptography.encoder.encode(hashHex.slice(0, 32)).buffer;
return crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt']);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async decryptFile(key, file, File) {
const bKey = await this.getKey(key);
const abCipherdata = await file.data.arrayBuffer();
const abPlaindata = await this.decryptArrayBuffer(bKey, abCipherdata);
return File.create({
name: file.name,
data: abPlaindata,
});
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async decryptString(key, ciphertext) {
const abCiphertext = WebCryptography.encoder.encode(ciphertext).buffer;
const abIv = abCiphertext.slice(0, 16);
const abPayload = abCiphertext.slice(16);
const abPlaintext = await crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload);
return WebCryptography.decoder.decode(abPlaintext);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
constructor({ stream, data, encoding, name, mimeType }) {
if (stream instanceof Readable) {
this.data = stream;
if (stream instanceof fs.ReadStream) {
// $FlowFixMe: incomplete flow node definitions
this.name = basename(stream.path);
this.contentLength = fs.statSync(stream.path).size;
}
} else if (data instanceof Buffer) {
this.data = Buffer.from(data);
} else if (typeof data === 'string') {
// $FlowFixMe: incomplete flow node definitions
this.data = Buffer.from(data, encoding ?? 'utf8');
}
if (name) {
this.name = basename(name);
}
if (mimeType) {
this.mimeType = mimeType;
}
if (this.data === undefined) {
throw new Error("Couldn't construct a file out of supplied options.");
}
if (this.name === undefined) {
throw new Error("Couldn't guess filename out of the options. Please provide one.");
}
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
}; | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default: new LegacyCryptor({
cipherKey: cryptoConfiguration.cipherKey,
useRandomIVs: cryptoConfiguration.useRandomIVs,
}),
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
};
if (!('ssl' in setup)) {
setup.ssl = true;
}
super(setup);
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
}; | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
default: new LegacyCryptor({
cipherKey: cryptoConfiguration.cipherKey,
useRandomIVs: cryptoConfiguration.useRandomIVs,
}),
cryptors: [new AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
});
};
super(setup);
if (listenToBrowserNetworkEvents) {
// mount network events.
window.addEventListener('offline', () => {
this.networkDownDetected();
});
window.addEventListener('online', () => {
this.networkUpDetected();
});
}
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
stream: fs.createReadStream(this.getFilePath(fileName)),
});
this.isStream = true;
} else { | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
fs.unlink(tempFilePath, () => {}); | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
data: fs.readFileSync(this.getFilePath(fileName)),
});
try {
this.binaryFileResult = await this.cryptoModule.decryptFile(encrypteFile, pubnub.File);
} catch (e: any) {
this.errorMessage = e?.message;
}
} else if (format === 'stream') { | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
this._initCryptor = (id: string) => {
return id === 'legacy'
? new LegacyCryptor({ cipherKey: this.cipherKey, useRandomIVs: this.useRandomIVs })
: new AesCbcCryptor({ cipherKey: this.cipherKey });
}; | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
fs.unlink(tempFilePath, () => {});
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
return `${process.cwd()}/dist/contract/contract/features/encryption/assets/${filename}`;
} | 1 | TypeScript | CWE-331 | Insufficient Entropy | The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. | https://cwe.mitre.org/data/definitions/331.html | safe |
async function run() {
console.log(`Starting chromedriver. Instance: ${JSON.stringify(chromedriver)}`);
await chromedriver.start(null, true);
console.log(`Started Chromedriver. Instance is null: ${chromedriver.defaultInstance === null}.`);
chromedriver.stop();
console.log(`Stopped Chromedriver. Instance is null: ${chromedriver.defaultInstance === null}.`);
} | 1 | TypeScript | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
function pointInPolygon(testx, testy, polygon) {
let intersections = 0;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const [prevX, prevY] = polygon[j];
const [x, y] = polygon[i];
// count intersections
if (((y > testy) != (prevY > testy)) && (testx < (prevX - x) * (testy - y) / (prevY - y) + x)) {
intersections++;
}
}
// point is in polygon if intersection count is odd
return intersections & 1;
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
export function intersectLasso(markname, pixelLasso, unit) {
const { x, y, mark } = unit;
const bb = new Bounds().set(
Number.MAX_SAFE_INTEGER,
Number.MAX_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER
);
// Get bounding box around lasso
for (const [px, py] of pixelLasso) {
if (px < bb.x1) bb.x1 = px;
if (px > bb.x2) bb.x2 = px;
if (py < bb.y1) bb.y1 = py;
if (py > bb.y2) bb.y2 = py;
}
// Translate bb against unit coordinates
bb.translate(x, y);
const intersection = intersect([[bb.x1, bb.y1], [bb.x2, bb.y2]],
markname,
mark);
// Check every point against the lasso
return intersection.filter(tuple => pointInPolygon(tuple.x, tuple.y, pixelLasso));
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
export function lassoAppend(lasso, x, y, minDist = 5) {
lasso = array(lasso);
const last = lasso[lasso.length - 1];
// Add point to lasso if its the first point or distance to last point exceed minDist
return (last === undefined || Math.sqrt(((last[0] - x) ** 2) + ((last[1] - y) ** 2)) > minDist)
? [...lasso, [x, y]]
: lasso;
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
export function lassoPath(lasso) {
return array(lasso).reduce((svg, [x, y], i) => {
return svg += i == 0
? `M ${x},${y} `
: i === lasso.length - 1
? ' Z'
: `L ${x},${y} `;
}, '');
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
data: this.receiver.contract.methods.mockFunction().encodeABI(),
value,
},
],
`<proposal description>#wrong-suffix=${proposer}`,
);
}); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
data: this.receiver.contract.methods.mockFunction().encodeABI(),
value,
},
],
`<proposal description>#wrong-suffix=${proposer}`,
);
});
it('proposer can propose', async function () {
expectEvent(await this.helper.propose({ from: proposer }), 'ProposalCreated');
});
it('someone else can propose', async function () {
expectEvent(await this.helper.propose({ from: voter1 }), 'ProposalCreated');
});
}); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
axiosDefault.mockResolvedValue({ | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
axiosDefault.mockResolvedValue({
status: 200,
statusText: 'OK',
headers: {},
data: {},
}),
})); | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
use: vi.fn(),
},
},
} as unknown as AxiosInstance;
vi.mocked(axios.create).mockReturnValue(mockAxiosInstance);
}); | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export async function getAxios() {
if (!_cache.axiosInstance) {
const axios = (await import('axios')).default;
_cache.axiosInstance = axios.create();
_cache.axiosInstance.interceptors.response.use(responseInterceptor);
}
return _cache.axiosInstance;
} | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
url: randUrl(),
};
sampleResponseConfig = {
request: {
socket: {
remoteAddress: sample.remoteAddress,
},
url: sample.url,
},
} as AxiosResponse<any, any>;
}); | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export const responseInterceptor = async (config: AxiosResponse<any, any>) => {
await validateIP(config.request.socket.remoteAddress, config.request.url);
return config;
}; | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
url: randUrl(),
};
}); | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export const validateIP = async (ip: string, url: string) => {
const env = getEnv();
if (env.IMPORT_IP_DENY_LIST.includes(ip)) {
throw new Error(`Requested URL "${url}" resolves to a denied IP address`);
}
if (env.IMPORT_IP_DENY_LIST.includes('0.0.0.0')) {
const networkInterfaces = os.networkInterfaces();
for (const networkInfo of Object.values(networkInterfaces)) {
if (!networkInfo) continue;
for (const info of networkInfo) {
if (info.address === ip) {
throw new Error(`Requested URL "${url}" resolves to a denied IP address`);
}
}
}
}
}; | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
res(response: SerializedResponse) {
if (response.headers?.['set-cookie']) {
response.headers['set-cookie'] = redactHeaderCookie(response.headers['set-cookie'], [
'access_token',
`${env.REFRESH_TOKEN_COOKIE_NAME}`,
]);
}
return response;
}, | 1 | TypeScript | CWE-284 | Improper Access Control | The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor. | https://cwe.mitre.org/data/definitions/284.html | safe |
res(response: SerializedResponse) {
if (response.headers?.['set-cookie']) {
response.headers['set-cookie'] = redactHeaderCookie(response.headers['set-cookie'], [
'access_token',
`${env.REFRESH_TOKEN_COOKIE_NAME}`,
]);
}
return response;
}, | 1 | TypeScript | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
req(request: Request) {
const output = stdSerializers.req(request);
output.url = redactQuery(output.url);
if (output.headers?.cookie) {
output.headers.cookie = redactHeaderCookie(output.headers.cookie, [
'access_token',
`${env.REFRESH_TOKEN_COOKIE_NAME}`,
]);
}
return output;
}, | 1 | TypeScript | CWE-284 | Improper Access Control | The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor. | https://cwe.mitre.org/data/definitions/284.html | safe |
req(request: Request) {
const output = stdSerializers.req(request);
output.url = redactQuery(output.url);
if (output.headers?.cookie) {
output.headers.cookie = redactHeaderCookie(output.headers.cookie, [
'access_token',
`${env.REFRESH_TOKEN_COOKIE_NAME}`,
]);
}
return output;
}, | 1 | TypeScript | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
export function redactHeaderCookie(cookieHeader: string, cookieNames: string[]) {
for (const cookieName of cookieNames) {
const re = new RegExp(`(${cookieName}=)([^;]+)`);
cookieHeader = cookieHeader.replace(re, `$1--redacted--`);
}
return cookieHeader;
} | 1 | TypeScript | CWE-284 | Improper Access Control | The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor. | https://cwe.mitre.org/data/definitions/284.html | safe |
export function redactHeaderCookie(cookieHeader: string, cookieNames: string[]) {
for (const cookieName of cookieNames) {
const re = new RegExp(`(${cookieName}=)([^;]+)`);
cookieHeader = cookieHeader.replace(re, `$1--redacted--`);
}
return cookieHeader;
} | 1 | TypeScript | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
this.server.handleUpgrade(request, socket, head, async (ws) => {
this.catchInvalidMessages(ws);
const state = { accountability: null, expires_at: null } as AuthenticationState;
this.server.emit('connection', ws, state);
}); | 1 | TypeScript | CWE-755 | Improper Handling of Exceptional Conditions | The product does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | safe |
function handleDataChannelChat(data) {
if (!data) return;
// prevent XSS injection from remote peer through Data Channel
const dataMessage = JSON.parse(filterXSS(JSON.stringify(data)));
let msgFrom = dataMessage.from;
let msgTo = dataMessage.to;
let msg = dataMessage.msg;
let msgPrivate = dataMessage.privateMsg;
let msgId = dataMessage.id;
// private message but not for me return
if (msgPrivate && msgTo != myPeerName) return;
console.log('handleDataChannelChat', dataMessage);
// chat message for me also
if (!isChatRoomVisible && showChatOnMessage) {
showChatRoomDraggable();
chatRoomBtn.className = className.chatOff;
}
// show message from
if (!showChatOnMessage) {
userLog('toast', `New message from: ${msgFrom}`);
}
playSound('chatMessage');
setPeerChatAvatarImgName('left', msgFrom);
appendMessage(msgFrom, leftChatAvatar, 'left', msg, msgPrivate, msgId);
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
function addMsgerPrivateBtn(msgerPrivateBtn, msgerPrivateMsgInput, peerId) {
// add button to send private messages
msgerPrivateBtn.addEventListener('click', (e) => {
e.preventDefault();
sendPrivateMessage();
});
// Number 13 is the "Enter" key on the keyboard
msgerPrivateMsgInput.addEventListener('keyup', (e) => {
if (e.keyCode === 13) {
e.preventDefault();
sendPrivateMessage();
}
});
msgerPrivateMsgInput.onpaste = () => {
isChatPasteTxt = true;
};
function sendPrivateMessage() {
let pMsg = msgerPrivateMsgInput.value.trim();
// let pMsg = checkMsg(msgerPrivateMsgInput.value.trim());
// if (!pMsg) {
// msgerPrivateMsgInput.value = '';
// isChatPasteTxt = false;
// return;
// }
let toPeerName = msgerPrivateBtn.value;
emitMsg(myPeerName, toPeerName, pMsg, true, peerId);
appendMessage(myPeerName, rightChatAvatar, 'right', pMsg + '<hr>Private message to ' + toPeerName, true);
msgerPrivateMsgInput.value = '';
msgerCP.style.display = 'none';
}
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
function sendPrivateMessage() {
let pMsg = msgerPrivateMsgInput.value.trim();
// let pMsg = checkMsg(msgerPrivateMsgInput.value.trim());
// if (!pMsg) {
// msgerPrivateMsgInput.value = '';
// isChatPasteTxt = false;
// return;
// }
let toPeerName = msgerPrivateBtn.value;
emitMsg(myPeerName, toPeerName, pMsg, true, peerId);
appendMessage(myPeerName, rightChatAvatar, 'right', pMsg + '<hr>Private message to ' + toPeerName, true);
msgerPrivateMsgInput.value = '';
msgerCP.style.display = 'none';
} | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
getUserInfo (req) {
return userInfoDB[req.body.username]
}, | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
secret: 'a'.repeat(32),
cookie: { path: '/', secure: false }
})
await fastify.register(fastifyCsrf, {
sessionPlugin: '@fastify/session',
getUserInfo (req) {
return req.session.username
},
csrfOpts: {
hmacKey: 'foo'
}
})
fastify.post('/login', async (req, reply) => {
req.session.username = req.body.username
const token = await reply.generateCsrf({ userInfo: req.body.username })
return { token }
})
// must be preHandler as we are parsing the body
fastify.post('/', { preHandler: fastify.csrfProtection }, async (req, reply) => {
return req.body
})
const response1 = await fastify.inject({
method: 'POST',
path: '/login',
body: {
username: 'foo'
}
})
t.equal(response1.statusCode, 200)
const cookie1 = response1.cookies[0]
const { token } = response1.json()
const response2 = await fastify.inject({
method: 'POST',
path: '/',
cookies: {
sessionId: cookie1.value
},
body: {
_csrf: token,
username: 'foo'
}
})
t.equal(response2.statusCode, 200)
}) | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
getUserInfo(req) {
return req.session.get('username')
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
host.scopedSync().read(normalize('dist/ngssc.json'))
); | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
async function runNgsscbuild() {
architect = (await createArchitect(host.root())).architect;
// A "run" can have multiple outputs, and contains progress information.
const run = await architect.scheduleTarget(targetSpec);
// The "result" member (of type BuilderOutput) is the next output.
const output = await run.result;
// Stop the builder from running. This stops Architect from keeping
// the builder-associated states in memory, since builders keep waiting
// to be scheduled.
await run.stop();
return output;
} | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
export async function detectVariables(
context: BuilderContext,
searchPattern?: string | null
): Promise<NgsscContext> {
const projectName = context.target && context.target.project;
if (!projectName) {
throw new Error('The builder requires a target.');
}
const projectMetadata = await context.getProjectMetadata(projectName);
const sourceRoot = projectMetadata.sourceRoot as string | undefined;
const defaultSearchPattern = sourceRoot ? `${sourceRoot}/**/!(*server*).ts` : '**/!(*server*).ts';
const detector = new VariableDetector(context.logger);
const typeScriptFiles = await glob(searchPattern || defaultSearchPattern, {
absolute: true,
cwd: context.workspaceRoot,
ignore: ['**/node_modules/**', '**/*.spec.ts', '**/*.d.ts'],
});
let ngsscContext: NgsscContext | null = null;
for (const file of typeScriptFiles) {
const fileContent = await readFileAsync(file, 'utf8');
const innerNgsscContext = detector.detect(fileContent);
if (!innerNgsscContext.variables.length) {
continue;
} else if (!ngsscContext) {
ngsscContext = innerNgsscContext;
continue;
}
if (ngsscContext.variant !== innerNgsscContext.variant) {
context.logger.info(
`ngssc: Detected conflicting variants (${ngsscContext.variant} and ${innerNgsscContext.variant}) being used`
);
}
ngsscContext.variables.push(
...innerNgsscContext.variables.filter((v) => !ngsscContext!.variables.includes(v))
);
}
if (!ngsscContext) {
return { variant: 'process', variables: [] };
}
context.logger.info(
`ngssc: Detected variant '${ngsscContext.variant}' with variables ` +
`'${ngsscContext.variables.join(', ')}'`
);
return ngsscContext;
} | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
export async function detectVariablesAndBuildNgsscJson(
options: NgsscBuildSchema,
browserOptions: BrowserBuilderOptions,
context: BuilderContext,
multiple: boolean = false
) {
const ngsscContext = await detectVariables(context, options.searchPattern);
const outputPath = join(context.workspaceRoot, browserOptions.outputPath);
const ngssc = buildNgssc(ngsscContext, options, browserOptions, multiple);
await writeFileAsync(join(outputPath, 'ngssc.json'), JSON.stringify(ngssc, null, 2), 'utf8');
} | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
project: resolve(__dirname, './e2e/tsconfig.e2e.json'),
});
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: StacktraceOption.PRETTY
}
}));
}, | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
print: function() {}, | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
export async function createArchitect(workspaceRoot: Path) {
const registry = new schema.CoreSchemaRegistry();
registry.addPostTransform(schema.transforms.addUndefinedDefaults);
const workspaceSysPath = getSystemPath(workspaceRoot);
const { workspace } = await workspaces.readWorkspace(
workspaceSysPath,
workspaces.createWorkspaceHost(host)
);
const architectHost = new TestingArchitectHost(
workspaceSysPath,
workspaceSysPath,
new WorkspaceNodeModulesArchitectHost(workspace, workspaceSysPath)
);
await architectHost.addBuilderFromPackage('..');
//require('ts-node').register(require('../projects/angular-server-side-configuration/builders/tsconfig.json'));
await architectHost.addBuilderFromPackage(
'../../../../dist/angular-server-side-configuration'
); | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
export function is_form_content_type(request) {
// These content types must be protected against CSRF
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype
return is_content_type(
request,
'application/x-www-form-urlencoded',
'multipart/form-data',
'text/plain'
);
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
async logIn(request: FastifyRequest, user: any) {
const object = await this.serializeUser(user, request)
// Handle sessions using @fastify/session
if (request.session.regenerate) {
// regenerate session to guard against session fixation
await request.session.regenerate()
}
request.session.set(this.key, object)
} | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
async logOut(request: FastifyRequest) {
request.session.set(this.key, undefined)
if (request.session.regenerate) {
await request.session.regenerate()
}
} | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
{ preValidation: fastifyPassport.authenticate('test', { authInfo: false }) },
async (request, reply) => {
await request.logout()
void reply.send('logged out')
}
)
return server
} | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
constructor(options: AuthenticatorOptions = {}) {
this.key = options.key || 'passport'
this.userProperty = options.userProperty || 'user'
this.use(new SessionStrategy(this.deserializeUser.bind(this)))
this.clearSessionOnLogin = options.clearSessionOnLogin ?? true
this.clearSessionIgnoreFields = ['passport', 'session', ...(options.clearSessionIgnoreFields || [])]
this.sessionManager = new SecureSessionManager(
{
key: this.key,
clearSessionOnLogin: this.clearSessionOnLogin,
clearSessionIgnoreFields: this.clearSessionIgnoreFields,
},
this.serializeUser.bind(this)
)
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
constructor(
options: SerializeFunction | { key?: string; clearSessionOnLogin?: boolean; clearSessionIgnoreFields?: string[] },
serializeUser?: SerializeFunction
) {
if (typeof options === 'function') {
this.serializeUser = options
this.key = 'passport'
this.clearSessionOnLogin = true
} else if (typeof serializeUser === 'function') {
this.serializeUser = serializeUser
this.key =
(options && typeof options === 'object' && typeof options.key === 'string' && options.key) || 'passport'
this.clearSessionOnLogin = options.clearSessionOnLogin ?? true
this.clearSessionIgnoreFields = [...this.clearSessionIgnoreFields, ...(options.clearSessionIgnoreFields || [])]
} else {
throw new Error('SecureSessionManager#constructor must have a valid serializeUser-function passed as a parameter')
}
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
async logIn(request: FastifyRequest, user: any) {
const object = await this.serializeUser(user, request)
if (this.clearSessionOnLogin && object) {
// Handle @fastify/session to prevent token/CSRF fixation
if (request.session.regenerate) {
await request.session.regenerate(this.clearSessionIgnoreFields)
} else {
const currentFields = request.session.data() || {}
// Handle @fastify/secure-session against CSRF fixation
// TODO: This is quite hacky. The best option would be having a regenerate method
// on secure-session as well
for (const field of Object.keys(currentFields)) {
if (this.clearSessionIgnoreFields.includes(field)) {
continue
}
request.session.set(field, undefined)
}
}
}
// Handle sessions using @fastify/session
if (request.session.regenerate) {
// regenerate session to guard against session fixation
await request.session.regenerate()
}
request.session.set(this.key, object)
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
expect(sess.body).not.toBe('')
}
await user.inject({
method: 'POST',
url: '/login',
payload: { login: 'test', password: 'test' },
})
{
const sess = await user.inject({ method: 'GET', url: '/session' })
expect(sess.body).toBe('')
}
})
})
})
delete process.env.SESSION_PLUGIN
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
{ preValidation: fastifyPassport.authenticate('test', { authInfo: false }) },
async () => 'success'
)
server.get('/csrf', async (_req, reply) => {
return reply.generateCsrf()
})
server.get('/session', async (req) => {
return req.session.get('_csrf')
})
return server
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
expect(sess.body).toBe('')
}
}) | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
expect(sess.body).toBe('')
}
})
}) | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
const sess = await user.inject({ method: 'GET', url: '/session' })
expect(sess.body).toBe('')
}
})
})
}) | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
) => {
const { fastifyPassport, server } = getRegisteredTestServer(sessionOptions, passportOptions)
fastifyPassport.use(name, strategy)
return { fastifyPassport, server }
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
) => {
const fastifyPassport = new Authenticator(passportOptions)
fastifyPassport.registerUserSerializer(async (user) => JSON.stringify(user))
fastifyPassport.registerUserDeserializer(async (serialized: string) => JSON.parse(serialized))
const server = getTestServer(sessionOptions)
void server.register(fastifyPassport.initialize())
void server.register(fastifyPassport.secureSession())
return { fastifyPassport, server }
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
export const getTestServer = (sessionOptions: SessionOptions = null) => {
const server = fastify()
loadSessionPlugins(server, sessionOptions)
server.setErrorHandler((error, _request, reply) => {
void reply.status(500)
void reply.send(error)
})
return server
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.