TypeScript Secure Coding

Secure coding practices for TypeScript applications.


XSS Prevention

 1// ❌ Vulnerable
 2function displayMessage(message: string) {
 3    document.getElementById('output')!.innerHTML = message;
 4}
 5
 6// ✅ Secure
 7function displayMessage(message: string) {
 8    const element = document.getElementById('output')!;
 9    element.textContent = message;
10}
11
12// ✅ With sanitization
13import DOMPurify from 'dompurify';
14function displayMessage(message: string) {
15    const clean = DOMPurify.sanitize(message);
16    document.getElementById('output')!.innerHTML = clean;
17}

SQL Injection Prevention (Node.js)

1// ❌ Vulnerable
2const username = req.body.username;
3const query = `SELECT * FROM users WHERE username = '${username}'`;
4db.query(query);
5
6// ✅ Secure
7const username = req.body.username;
8const query = 'SELECT * FROM users WHERE username = ?';
9db.query(query, [username]);

Command Injection Prevention

 1// ❌ Vulnerable
 2import { exec } from 'child_process';
 3const filename = req.query.file;
 4exec(`cat ${filename}`, (error, stdout) => {
 5    res.send(stdout);
 6});
 7
 8// ✅ Secure
 9import { execFile } from 'child_process';
10const filename = req.query.file as string;
11if (!/^[a-zA-Z0-9_.-]+$/.test(filename)) {
12    throw new Error('Invalid filename');
13}
14execFile('cat', [filename], (error, stdout) => {
15    res.send(stdout);
16});

Secure Password Hashing

1// ❌ Insecure
2import crypto from 'crypto';
3const hash = crypto.createHash('md5').update(password).digest('hex');
4
5// ✅ Secure
6import bcrypt from 'bcrypt';
7const saltRounds = 12;
8const hash = await bcrypt.hash(password, saltRounds);
9const match = await bcrypt.compare(password, hash);

Secure Random Generation

1// ❌ Insecure
2const token = Math.random().toString(36).substring(2);
3
4// ✅ Secure
5import crypto from 'crypto';
6const token = crypto.randomBytes(32).toString('hex');

Related Snippets