تخزين الـ Passwords بـ Argon2id: صح من أول مرة
ليه sha256 للـ passwords غلط (سريع جدًّا ونفس الـ hash لنفس الـ password). Argon2id: salt عشوائي جُوّه الـ hash، و memoryCost و timeCost و parallelism بتوصيات OWASP، و verify، و needsRehash لما ترفع الـ parameters. password policy على طريقة NIST (طول، ومش من القوايم المشهورة). وثغرة user enumeration بالوقت، والحل بـ dummy hash ورسالة واحدة.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك في قسم الـ authentication. أول قاعدة: الـ password عمرها ما تتخزن زي ما هي. لو الـ database اتسرقت، وده بيحصل كتير، الـ passwords كلها هتبقى مكشوفة، والناس بتستخدم نفس الـ password في كل حتة. الحل: hash. بس مش أي hash. نجرّب sha two fifty six: نفس الـ password مرتين، وبعدين نشوف بيعمل كام hash في التانية. نشغّل.
import crypto from "node:crypto";
// ❌ sha256 للـ passwords
const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
// 1) نفس الـ password = نفس الـ hash (اللي عرف واحد، عرف الكل)
console.log(sha("123456") === sha("123456"));
// 2) سريع جدًّا: المهاجم بيجرّب ملايين في التانية
const t0 = performance.now();
let n = 0;
while (performance.now() - t0 < 200) {
sha(`guess${n++}`);
}
console.log(`sha256: أكتر من ${Math.floor((n * 5) / 100000) * 100000} تخمينة في التانية على core واحد`);المخرجات
$ node main.js true sha256: أكتر من 400000 تخمينة في التانية على core واحد
نفس الـ password، نفس الـ hash: يعني كل اللي الـ password بتاعهم واحد، الـ hash بتاعهم واحد، والمهاجم بيكسرهم مرة واحدة، ويقدر يستخدم جداول جاهزة لملايين الـ passwords المشهورة. ومئات الآلاف في التانية على core واحد، و GPU بيعمل مليارات. محتاجين hash بطيء بقصد، وكل password ليها salt عشوائي، و بياكل memory علشان الـ GPUs ما تقدرش تعمل منه كتير مع بعض. وده بالزبط Argon2id. Argon2id، الكسبان في مسابقة الـ password hashing، وتوصية OWASP. memoryCost: تسعتاشر ميجا لكل hash. timeCost اتنين: عدد اللفات. parallelism واحد. وهنشوف الـ hash، والوقت، ونعمل hash لنفس الـ password مرة تانية، و verify صح وغلط، و needsRehash. نشغّل.
import argon2 from "argon2";
const OPTS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 }; // توصيات OWASP
const t0 = performance.now();
const hash = await argon2.hash("correct horse battery staple", OPTS);
const ms = performance.now() - t0;
console.log(hash);
console.log("وقت الـ hash:", ms > 10 ? "عشرات الـ milliseconds" : "سريع");
console.log("نفس الـ password، hash تاني:", hash !== (await argon2.hash("correct horse battery staple", OPTS)));
console.log("verify صح:", await argon2.verify(hash, "correct horse battery staple"));
console.log("verify غلط:", await argon2.verify(hash, "correct horse battery stapler"));
// يوم ما ترفع الـ parameters: الـ hashes القديمة لسه شغالة، وبتعرف مين محتاج يتعاد
console.log("محتاج rehash؟", argon2.needsRehash(hash, { ...OPTS, timeCost: 3 }));المخرجات
$ node main.js $argon2id$v=19$m=19456,p=1,t=2$hHQaWYcAYOuGYiehZTFRaw$9HYQ0X8ixSeuqqpNey2DaDlrNta49B02f6oAHvl+e84 وقت الـ hash: عشرات الـ milliseconds نفس الـ password، hash تاني: true verify صح: true verify غلط: false محتاج rehash؟ true
الـ hash string واحدة فيها كل حاجة: argon2id، والإصدار، والـ parameters، والـ salt، والنتيجة. فمش محتاج تخزن الـ salt لوحده. بياخد عشرات الـ milliseconds: للمستخدم مش فارقة، وللمهاجم مصيبة. نفس الـ password، hash مختلف، بفضل الـ salt. verify صح وغلط. و needsRehash: لو بعدين رفعت الـ timeCost، تعرف إن الـ hash ده قديم، وتعمله تاني أول ما المستخدم يسجّل دخول، لأن ساعتها معاك الـ password. vulnerability خفية في الـ login: الوقت. لو الإيميل مش موجود، الـ code بيرد فورًا. لو موجود، بيعمل verify، وده عشرات الـ milliseconds. نقيس. نشغّل.
import argon2 from "argon2";
const OPTS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 };
const users = new Map([["[email protected]", await argon2.hash("S3cure-pass!", OPTS)]]);
// ❌ بيرد بسرعة لو الإيميل مش موجود ← المهاجم يعرف مين متسجل من الوقت
async function login(email, password) {
const hash = users.get(email);
if (!hash) return "مش موجود";
return (await argon2.verify(hash, password)) ? "تمام" : "password غلط";
}
async function timed(email) {
const t0 = performance.now();
const r = await login(email, "wrong-pass");
return `${email}: ${r} (${performance.now() - t0 > 5 ? "بطيء" : "سريع جدًّا"})`;
}
console.log(await timed("[email protected]"));
console.log(await timed("[email protected]"));المخرجات
$ node main.js [email protected]: password غلط (بطيء) [email protected]: مش موجود (سريع جدًّا)
mona: بطيء. nobody: سريع جدًّا. يعني حتى لو الرسايل اتغيرت لرسالة واحدة، المهاجم يقدر يعرف مين متسجل عندك من الوقت بس، ويبدأ يخمّن passwords للإيميلات الحقيقية بس. ده اسمه user enumeration. الحل: لو المستخدم مش موجود، اعمل verify على hash وهمي، علشان الوقت يبقى نفسه، ورد بنفس الرسالة بالحرف.
والـ password policy. التوصيات الجديدة من NIST: الطول أهم حاجة: اتناشر حرف على الأقل. ما تجبرش على رموز وحروف كبيرة، ده بيخلي الناس تكتب Password one وعلامة تعجب. امنع الـ passwords المشهورة والمسرّبة. وما تجبرش الناس تغيّرها كل شوية من غير سبب. واسمح بالـ password managers: ما تمنعش الـ paste. التحدي: register و login بـ Argon2id. register بـ policy، و four oh nine للمكرر. login برسالة واحدة لكل فشل، و dummy hash علشان الوقت. و rehash للمستخدم القديم اللي الـ hash بتاعه بـ parameters ضعيفة. التفاصيل وحالات الاختبار في الكومنت.
POST /register (policy 12-128 ومش مشهور، 409 للمكرر) و POST /login (dummy verify للمش موجود، نفس رسالة 401، و needsRehash ← rehash).
الحل. OPTS، و COMMON، و DUMMY مرة واحدة، و FAIL رسالة واحدة. register: email lowercase، والـ password من غير trim، والـ policy، و four oh nine. login: مش موجود؟ verify على الـ DUMMY ونرد FAIL. غلط؟ FAIL. صح؟ needsRehash، ولو محتاج نعمل hash جديد. نشغّل.
import express from "express";
import argon2 from "argon2";
const app = express();
app.use(express.json());
const users = new Map(); // email ← { hash }
// hash قديم بـ parameters ضعيفة (من سنة فاتت)
const OLD = { type: argon2.argon2id, memoryCost: 4096, timeCost: 1, parallelism: 1 };
users.set("[email protected]", { hash: await argon2.hash("Old-but-good-1", OLD) });
const OPTS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 };
const COMMON = new Set(["password1234", "123456789012", "qwertyuiop12"]);
const DUMMY = await argon2.hash("dummy-password-for-timing", OPTS);
const FAIL = { error: "الإيميل أو الـ password غلط" };
app.post("/register", async (req, res) => {
const email = String(req.body.email ?? "").trim().toLowerCase();
const password = String(req.body.password ?? "");
if (password.length < 12 || password.length > 128 || COMMON.has(password.toLowerCase())) {
return res.status(422).json({ error: "password ضعيف: 12 حرف على الأقل ومش من المشهورين" });
}
if (users.has(email)) return res.status(409).json({ error: "الإيميل متسجل" });
users.set(email, { hash: await argon2.hash(password, OPTS) });
res.status(201).json({ ok: true });
});
app.post("/login", async (req, res) => {
const email = String(req.body.email ?? "").trim().toLowerCase();
const password = String(req.body.password ?? "");
const user = users.get(email);
if (!user) {
await argon2.verify(DUMMY, password);
return res.status(401).json(FAIL);
}
if (!(await argon2.verify(user.hash, password))) return res.status(401).json(FAIL);
const rehashed = argon2.needsRehash(user.hash, OPTS);
if (rehashed) user.hash = await argon2.hash(password, OPTS);
res.json({ ok: true, rehashed });
});
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node main.js
http://localhost:3000
→ POST /register
{"email":"[email protected]","password":"short"}
← 422 Unprocessable Entity
{
"error": "password ضعيف: 12 حرف على الأقل ومش من المشهورين"
}
→ POST /register
{"email":"[email protected]","password":"password1234"}
← 422 Unprocessable Entity
{
"error": "password ضعيف: 12 حرف على الأقل ومش من المشهورين"
}
→ POST /register
{"email":" [email protected] ","password":"long enough passphrase"}
← 201 Created
{
"ok": true
}
→ POST /register
{"email":"[email protected]","password":"another long passphrase"}
← 409 Conflict
{
"error": "الإيميل متسجل"
}
→ POST /login
{"email":"[email protected]","password":"long enough passphrase"}
← 200 OK
{
"ok": true,
"rehashed": false
}
→ POST /login
{"email":"[email protected]","password":"wrong"}
← 401 Unauthorized
{
"error": "الإيميل أو الـ password غلط"
}
→ POST /login
{"email":"[email protected]","password":"wrong"}
← 401 Unauthorized
{
"error": "الإيميل أو الـ password غلط"
}
→ POST /login
{"email":"[email protected]","password":"Old-but-good-1"}
← 200 OK
{
"ok": true,
"rehashed": true
}
→ POST /login
{"email":"[email protected]","password":"Old-but-good-1"}
← 200 OK
{
"ok": true,
"rehashed": false
}القصير و password one two three four: four twenty two. التسجيل: two oh one، والإيميل بالـ capital اتزبط. المكرر: four oh nine. login صح، وغلط four oh one، و ghost نفس الرسالة بالحرف. old: rehashed true، وتاني مرة false. الدرس الجاي: الـ sessions بالتفصيل: session fixation والـ rotation.
03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرةانت هنا
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem