From 6fc4d7316928835210b6be13a5d554e666f57f0a Mon Sep 17 00:00:00 2001 From: hknfrt Date: Mon, 28 Aug 2023 10:43:15 +0300 Subject: [PATCH 1/2] Cookies, document.cookie is done --- 6-data-storage/01-cookie/article.md | 312 ++++++++++++++-------------- 1 file changed, 153 insertions(+), 159 deletions(-) diff --git a/6-data-storage/01-cookie/article.md b/6-data-storage/01-cookie/article.md index 2d1161e34..c478ab1c3 100644 --- a/6-data-storage/01-cookie/article.md +++ b/6-data-storage/01-cookie/article.md @@ -1,58 +1,55 @@ # Cookies, document.cookie -Cookies are small strings of data that are stored directly in the browser. They are a part of HTTP protocol, defined by [RFC 6265](https://tools.ietf.org/html/rfc6265) specification. +Çerezler, doğrudan tarayıcıda depolanan küçük veri dizileridir. Çerezler [RFC 6265](https://tools.ietf.org/html/rfc6265) teknik şartnamesi tarafından tanımlanan HTTP protokolünün bir parçasıdırlar. -Most of the time, cookies are set by a web server. Then they are automatically added to every request to the same domain. +Çoğu zaman, çerezler bir web sunucusu tarafından ayarlanır. Daha sonra aynı etki alanına yapılan her isteğe otomatik olarak eklenirler. -One of the most widespread use cases is authentication: +En yaygın kullanım alanlarından biri kimlik doğrulamadır: -1. Upon sign in, the server uses `Set-Cookie` HTTP-header in the response to set a cookie with "session identifier". -2. Next time when the request is set to the same domain, the browser sends the over the net using `Cookie` HTTP-header. -3. So the server knows who made the request. +1. Oturum açıldığında, sunucu "session identifier" içeren bir çerez ayarlamak için, gönderilen isteğe verdiği yanıtta `Set-Cookie` HTTP başlığını kullanır. +2. Gelecek sefere istek aynı etki alanından yapıldığında, tarayıcı `Cookie` HTTP-header başlağını kullanarak ağ üzerinden gönderir. +3. Böylece sunucu isteğin kim tarafından yapıldığını bilir. -We can also access cookies from the browser, using `document.cookie` property. +Ayrıca `document.cookie` özelliğini kullarak çerezelere tarayıcıdan da erişebiliriz. -There are many tricky things about cookies and their options. In this chapter we'll cover them in detail. +Çerezler ve seçenekleri hakkında birçok ince detay var. Bu bölümde bunları ayrıntılı olarak ele alacağız. ## Reading from document.cookie ```online -Do you have any cookies on this site? Let's see: +Bu sitede hiç çerezin var mı? Hadi görelim: ``` ```offline -Assuming you're on a website, it's possible to see the cookies, like this: +Bir web sitesinde olduğunuzu varsayalım, çerezleri şu şekilde görmek mümkündür: ``` ```js run -// At javascript.info, we use Google Analytics for statistics, -// so there should be some cookies +// javascript.info sitesinde, biz istatistikler için Google Analytics kullanırız, +// bu yüzden bazı çerezler olmalı alert( document.cookie ); // cookie1=value1; cookie2=value2;... ``` +`document.cookie` değeri `; ` ile ayrılmış `name=value` çiftlerinden oluşur. Her biri ayrı bir çerezdir. +Bellirli bir çerezi bulmak için, `document.cookie` yi `; ` ile ayırabiliriz ve sonra doğru ismi bulabiliriz. Ayrıca bunu yapmak için düzenli ifadeler (regular expresion) veya dizi methodlarını da kullanabiliriz. -The value of `document.cookie` consists of `name=value` pairs, delimited by `; `. Each one is a separate cookie. +Bunu okuyucu için bir egseriz olarak bırakıyoruz. Ayrıca, bu bölümün sonunda yardımcı fonksiyonlar ve üzerinde değişiklik yapabileceğiniz çerezler bulacaksınız. -To find a particular cookie, we can split `document.cookie` by `; `, and then find the right name. We can use either a regular expression or array functions to do that. +## document.cookie' ye yazma -We leave it as an exercise for the reader. Also, at the end of the chapter you'll find helper functions to manipulate cookies. +`document.cookie` ye yazabilir. Ancak bu bir veri özelliği değildir, bu bir erişimdir. -## Writing to document.cookie +**`document.cookie` yazılan bir işlemi, tarayıcında sayesinde belirttiğimiz çerezleri günceller fakat bu, diğer çerezleri etkilemez.** -We can write to `document.cookie`. But it's not a data property, it's an accessor. - -**A write operation to `document.cookie` passes through the browser that updates cookies mentioned in it, but doesn't touch other cookies.** - -For instance, this call sets a cookie with the name `user` and value `John`: +Örneğin, bu ismi `user` ve değeri `John` olan bir çerezi ayarlar : ```js run -document.cookie = "user=John"; // update only cookie named 'user' -alert(document.cookie); // show all cookies +document.cookie = "user=John"; // sadece 'user' isimli çerezi günceller +alert(document.cookie); // tüm çerezleri göster ``` +Eğer komutu çalıştırırsanız, muhtemelen birden fazla çerez göreceksiniz. Bunun nedeni `document.cookie=` işlem tüm çerezleri etkilemediği içindir. Sadece `user` adlı çerezi değiştirir. -If you run it, then probably you'll see multiple cookies. That's because `document.cookie=` operation does not overwrite all cookies. It only sets the mentioned cookie `user`. - -Technically, name and value can have any characters, but to keep the formatting valid they should be escaped using a built-in `encodeURIComponent` function: +Tekinik olarak, isim ve değer herhangi bir karakter içerebilir, fakat geçerli bir atama yapmak için `encodeURIComponent` yerleşik fonksiyonu kullanılmalıdır: ```js run // special values, need encoding @@ -65,16 +62,16 @@ document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value); alert(document.cookie); // ...; my%20name=John%20Smith ``` - ```warn header="Limitations" -There are few limitations: -- The `name=value` pair, after `encodeURIComponent`, should not exceed 4kb. So we can't store anything huge in a cookie. -- The total number of cookies per domain is limited to around 20+, the exact limit depends on a browser. +Birkaç kısıtlama vardır: +- `encodeURIComponent` fonksiyonunu kullanırken `name=value` çifti 4kb yi geçmemelidir. Yani br çerezde çok büyük bir değer tutulamaz. +- +- Kesin sınır tarayıcının türüne bağlı olmakla birlilte, etki alanı başına toplam çerez sayısı 20+ ile sınırlıdır. ``` -Cookies have several options, many of them are important and should be set. +Çerezlerin birkaç seçeneği vardır, bunların çoğu önemli ve ayarlanması gerekir. -The options are listed after `key=value`, delimited by `;`, like this: +Seçenekler `key=value` ile belirtilmiş ve `;` ile ayrılmış, aşağıdaki gibi listelenir: ```js run document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT" @@ -84,59 +81,59 @@ document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT" - **`path=/mypath`** -The url path prefix, where the cookie is accessible. Must be absolute. By default, it's the current path. +Çerezin URL öneki ulaşılabilir olmalıdır. Tam olmalıdır. Varsayılan olarak, geçerli yoldur. -If a cookie is set with `path=/admin`, it's visible at pages `/admin` and `/admin/something`, but not at `/home` or `/adminpage`. +Eğer bir çerez `path=/admin` olarak ayarlandıysa, bu çerez `/admin` ve `/admin/something` sayfalarında görülebilir, ancak `/home` ya da `/adminpage` sayfalarında görünmez. -Usually, we set `path=/` to make the cookie accessible from all website pages. +Genelde, biz çerezin tüm web sayfalarında erişebilir olması için `path=/` şeklinde ayarlarız. ## domain - **`domain=site.com`** -A domain where the cookie is accessible. In practice though, there are limitations. We can't set any domain. +Çerezlere etki alanı üzerinden erişilebilir. Ancak pratikte bazı kısıtlamalar vardır. Bu çerezleri herhangi bir etki alanına ayarlayamayız. + +Varsayılan olarak, bir çerez sadece onu ayarladığımız etki alanından erişilebilir. Yani, eğer çerez `site.com` etki alanına ayarlanmışsa, biz ona `other.com` etki alanından erişemeyiz. -By default, a cookie is accessible only at the domain that set it. So, if the cookie was set by `site.com`, we won't get it `other.com`. +...Ancak daha ilginç olanı, `forum.site.com` alt etki alnından da çerezlere erişilemez. -...But what's more tricky, we also won't get the cookie at a subdomain `forum.site.com`! ```js -// at site.com +// diyelim ki site.com alan adlı sitede şöyle bir çerez ataması yapılmış olsun document.cookie = "user=John" -// at forum.site.com -alert(document.cookie); // no user +// forum.site.com alt etki alanından aynı çereze erişmeye çalıştığımızda çıktı aşağıdaki gibi olur +alert(document.cookie); // kullanıcı yok ``` -**There's no way to let a cookie be accessible from another 2nd-level domain, so `other.com` will never receive a cookie set at `site.com`.** +**Bir çerezin başka 2.seviye bir etki alanından erişilebilmesini sağlamanın bir yolu yok, bu nedenle `other.com` sitesi hiçbir zaman `site.com` sitesinde ayarlanmış bir çereze erişemeyeektir.** -It's a safety restriction, to allow us to store sensitive data in cookies. +Bunun sebebi, önemli verileri çerezlerde saklamamıza izin veren bir günvelik sınırlamasıdır. -...But if we'd like to grant access to subdomains like `forum.site.com`, that's possible. We should explicitly set `domain` option to the root domain: `domain=site.com`: +...Ancak `forum.site.com` gibi alt alan adlarına erişim izni vermek istiyorsak, bu mümkündür. Bunun için `domain` seçeneğini açıkça `domain=site.com` seçeneğine ayarlamamız gerekiyor: ```js -// at site.com, make the cookie accessible on any subdomain: +// site.com etki alnında, herhangi bir alt etki alanına şöyle ayarlayabiliriz: document.cookie = "user=John; domain=site.com" -// at forum.site.com -alert(document.cookie); // with user +// forum.site.com alt alanından çerezlere erişelim +alert(document.cookie); // çıktı: kullanıcılar ``` +Geçmişten gelen nedenlerden dolayı, `domain=.site.com` (başında bir nokta ile) şeklinde de çalışır, çok eski tarayıcıları desteklemek içn noktayı eklemek daha iyi olabilir. -For historical reasons, `domain=.site.com` (a dot at the start) also works this way, it might better to add the dot to support very old browsers. - -So, `domain` option allows to make a cookie accessible at subdomains. +Dolayısıyla, `domain` seçeneği, çerezlere alt alan adlarından da erişmeyi izin verir. ## expires, max-age -By default, if a cookie doesn't have one of these options, it disappears when the browser is closed. Such cookies are called "session cookies" +Varsayılan olarak, eğer bir çerez bu seçeneklerden birine sahip değilse, tarayıcı kapatıldığında çerezler de yok olur. Bu tür çerezlere "session cookies" denir. -To let cookies survive browser close, we can set either `expires` or `max-age` option. +Tarayıcı kapatıldığında bile çerezlerin yok olmasını engellemek için `expires` ya da `max-age` seçeneklerinden birini ayarlamak gerekir. - **`expires=Tue, 19 Jan 2038 03:14:07 GMT`** -Cookie expiration date, when the browser will delete it automatically. +Bu örnekte, tarayıcının 19 Ocak 2038 e kadar çerezi otomatik olarak tutumasını ve süresi dolunca silmesini sağlar. -The date must be exactly in this format, in GMT timezone. We can use `date.toUTCString` to get it. For instance, we can set the cookie to expire in 1 day: +Tarih, kesinlikle GMT zaman dilimi formatında olmalı. Bu formatı elde etmek için `date.toUTCString` methodunu kullanabiliriz. Örneğin, çerezi 1 gün sonra yok olacak şekilde ayarlabiliriz: ```js // +1 day from now @@ -144,20 +141,19 @@ let date = new Date(Date.now() + 86400e3); date = date.toUTCString(); document.cookie = "user=John; expires=" + date; ``` - -If we set `expires` to a date in the past, the cookie is deleted. +Eğer çerezin `expires` seçeneğini geçmişteki bir tarihe ayarlarsak, çerez silinir. - **`max-age=3600`** -An alternative to `expires`, specifies the cookie expiration in seconds from the current moment. +`expires` seçeneğine alternatif olarak, çerezi geçerli andan itibaren saniye türünden yok olmasını belirtir. -If zero or negative, then the cookie is deleted: +Eğer saniye, sıfır ya da negatif bir sayı olursa, çerez silinir. ```js -// cookie will die +1 hour from now +// çerez ayarlandığı zamandan bir saat sonra silinir. document.cookie = "user=John; max-age=3600"; -// delete cookie (let it expire right now) +// çerezi sil (çerezin süresinin sona ermesine izin ver) document.cookie = "user=John; max-age=0"; ``` @@ -165,14 +161,13 @@ document.cookie = "user=John; max-age=0"; - **`secure`** -The cookie should be transferred only over HTTPS. +Çerez sadece HTTPS üzerinden gönderilmelidir. -**By default, if we set a cookie at `http://site.com`, then it also appears at `https://site.com` and vice versa.** +**Varsayılan olarak, eğer `http://site.com` sitesi üzerinden bir çerez ayarlarsak, bu aynı zamanda `https://site.com` sitesi üzerinden görünür ve tersi de mümkündür.** -That is, cookies are domain-based, they do not distinguish between the protocols. - -With this option, if a cookie is set by `https://site.com`, then it doesn't appear when the same site is accessed by HTTP, as `http://site.com`. So if a cookie has sensitive content that should never be sent over unencrypted HTTP, then the flag is the right thing. +Yani, çerezler etki alanı tabanlıdır, protokoller arasında ayırım yapmaz. +Bu seçenekle beraber, eğer bir çerez hassas bilgiler içeriyorsa, durum değişir. Yani bir çerez `https://site.com` etki alanına ayarlamışsa, bu çereze `http://site.com` üzerinden erişem mümkün değildir, çünkü HTTP ile HTTPS arasında S günvelik flagı vardır. Bu da çerezlere erişilmesini engeller. Sonuç olarak hassas bilgilere sahip çerezleriniz varsa HTTPS protokülünü kullanmanız daha doğru olur. ```js // assuming we're on https:// now // set the cookie secure (only accessible if over HTTPS) @@ -181,107 +176,110 @@ document.cookie = "user=John; secure"; ## samesite -That's another security option, to protect from so-called XSRF (cross-site request forgery) attacks. +Bu, XSRF (siteler arası sahte istek) saldırılarından korunmak için başka bir güvenlik seçeneğidir. -To understand when it's useful, let's introduce the following attack scenario. +Bu seçeneğin ne zaman işimize yarayacağını anlamak için aşağıdaki senaryoya bakalım. ### XSRF attack -Imagine, you are logged into the site `bank.com`. That is: you have an authentication cookie from that site. Your browser sends it to `bank.com` with every request, so that it recognizes you and performs all sensitive financial operations. +`bank.com` sitesine giriş yaptığınızı düşünün. Yani: bu siteden bir tane kimlik doğrulama çereziniz var. Tarayıcınızla `bank.com` sitesine her giriş yaptığınızda, tarayıcınız bu çerezi `bank.com` sitesinin bulunduğu sunucuya gönderir, böylece `bank.com` sitesi sizi tanır ve tüm hassas finansal işlemlerinizi gerçekleştirir. + +Şimdi, başka bir sekmede internette gezinirken (`evil.com`), bu sitede (`evil.com`) de bilgisayar korsanına ait bir giriş hesabı var ve bu site zaman zaman
ile `bank.com` sitesine otomatik olarak bir form isteği gönderiyor. -Now, while browsing the web in another window, you occasionally come to another site `evil.com`, that automatically submits a form `` to `bank.com` with input fields that initiate a transaction to the hacker's account. +Bu form kayıt isteği `evil.com` sitesi üzerinden doğrudan `bank.com` sitesine istekler gönderir ve siz `bank.com` sitesini her ziyaret ettiğinizde gönderildiği için otomatik olarak bu siteye de size gönderilen çerezin aynısı gönderilir. Böylece bilgisayar korsanı kendi bilgiyasarı üzerinden işlem yaptığında, `bank.com` sitesinin sunucusu bunun siz olduğunuzu varsayıp, yapılan tüm finansal işlemlere onay verir. -The form is submitted from `evil.com` directly to the bank site, and your cookie is also sent, just because it's sent every time you visit `bank.com`. So the bank recognizes you and actually performs the payment. ![](cookie-xsrf.svg) -That's called a cross-site request forgery (or XSRF) attack. +Buna, siteler arası istek sahteciliği (ya da XSRF) saldırısı denir. -Real banks are protected from it of course. All forms generated by `bank.com` have a special field, so called "xsrf protection token", that an evil page can't neither generate, nor somehow extract from a remote page (it can submit a form there, but can't get the data back). +Tabi ki, gerçek bankalar buna karşı koruma sağlarlar. `bank.com` tarafından oluşturulan tüm formların özel bir alanı vardır, buna "xsrf protection token" (xsrf koruma belirteci) denir, kötü niyetli biri ne bir form oluşturabilir ne de buradan uzaktan veri çekebilir (formu kayıt edebilir ancak veriyi geri alamaz). -But that takes time to implement: we need to ensure that every form has the token field, and we must also check all requests. +Ancak bunu uygulamak zaman alır, her formun token (belirteç) alanına sahip olduğundan emin olmalıyız ve ayrıca tüm istekleri kontrol etmemiz gerekir. ### Enter cookie samesite option -The cookie `samesite` option provides another way to protect from such attacks, that (in theory) should not require "xsrf protection tokens". +`samesite` seçeneği, bu tür saldırılardan korunmak için, (teorik olarak) "xsrf protection tokens" kullanmayı gerektirmeyen, başka bir yol sağlar. -It has two possible values: +Olası iki değeri vardır: - **`samesite=strict` (same as `samesite` without value)** -A cookie with `samesite=strict` is never sent if the user comes from outside the site. +`samesite=strict` -In other words, whether a user follows a link from their mail or submits a form from `evil.com`, or does any operation that originates from another domain, the cookie is not sent. +`samesite=strict` özelliğine sahip bir çerez, kullanıcının web sitesine dışarıdan geldiği durumlarda hiçbir zaman tarayıcı tarafından gönderilmez veya paylaşılmaz. Bu, çerezin sadece aynı web sitesi içindeki isteklerde kullanılmasını ve diğer web siteleriyle paylaşılmamasını sağlayan bir güvenlik önlemidir. -If authentication cookies have `samesite` option, then XSRF attack has no chances to succeed, because a submission from `evil.com` comes without cookies. So `bank.com` will not recognize the user and will not proceed with the payment. +Başka bir deyişle, bir kullanıcı e-postalarından bir bağlantıyı takip etse veya `evil.com` 'dan bir form gönderse veya başka bir alan alanından kaynaklanan herhangi bir işlem yapsa da çerez gönderilmez. -The protection is quite reliable. Only operations that come from `bank.com` will send the `samesite` cookie. +Eğer kimlik doğrulama çerezleri `samesite` seçeneğine sahipse, XSRF saldırısının başarılı olma şansı yoktur, çünkü `evil.com` gelen istekler çerezler olmadan gelir. Böylece `bank.com` sitesi kullanıcıyı tanımayacak ve ödeme işlemi gerçekleşmeyecektir. -Although, there's a small inconvenience. +Koruma oldukça güvenilirdir. Yalnızca `bank.com` sitesi içerisinden gelen işlemlere `samesite` çerezi gönderecektir. -When a user follows a legitimate link to `bank.com`, like from their own notes, they'll be surprised that `bank.com` does not recognize them. Indeed, `samesite=strict` cookies are not sent in that case. +Yine de, küçük bir sıkıntı var. -We could work around that by using two cookies: one for "general recognition", only for the purposes of saying: "Hello, John", and the other one for data-changing operations with `samesite=strict`. Then a person coming from outside of the site will see a welcome, but payments must be initiated from the bank website. +Bir kullanıcı kendi bilgisayarında not defterine `bank.com` sitesine giden gerçek bir link kaydettiğinde ve daha sonra bu linke tıklayıp işlem yapmaya çalıştığında, ilginç bir şekilde karşılacağı durum, tekrardan oturum açması gerektiğidir. Aslında, `samesite=strict` çerezleri bu durumda gönderilmez. + +Bu durumu iki çerez kullarak aşabiliriz: birincisi "general recognition" (genel tanıma) için, bunun amacı sadece "Hello, John" gibi mesajları gösterme açmacı için kullanılır, ve diğeri de `samesite=strict` özelliği ile verileri değiştirmek içindir. O zaman eğer kişi site dışından geliyorsa hoşgeldin mesajını görecektir, ancak yine de işlem yapmak için (ödeme vs.) bankanın kendi sitesinden içinden işlem başlatmak zorundadır. - **`samesite=lax`** -A more relaxed approach that also protects from XSRF and doesn't break user experience. +XSRF saldırısından korunmak ve kullanıcı deneyimini olumsuz etkilememek için daha iyi bir yaklaşımdır. -Lax mode, just like `strict`, forbids the browser to send cookies when coming from outside the site, but adds an exception. +Lax modu, `strict` modu gibi, tarayıcının site dışından gelen istekleri çerezleri göndermesini engeller, ancak bir istisna ekler. -A `samesite=lax` cookie is sent if both of these conditions are true: -1. The HTTP method is "safe" (e.g. GET, but not POST). +Eğer aşağıdaki her iki koşul varsa `samesite=lax` çerezi gönderilir: - The full list of safe HTTP methods is in the [RFC7231 specification](https://tools.ietf.org/html/rfc7231). Basically, these are the methods that should be used for reading, but not writing the data. They must not perform any data-changing operations. Following a link is always GET, the safe method. +1. HTTP methodu eğer güvenli ise (örneğin GET, ama POST değilse). -2. The operation performs top-level navigation (changes URL in the browser address bar). + [RFC7231 specification](https://tools.ietf.org/html/rfc7231) (RFC7231 teknik şartnamesi) nin güvenli yöntemlerinin tam listesini burada bulabilirsiniz. Temel olarak, bunlar veriyi yazmak için değil, okumak için kullanılması gereken yöntemlerdir. Herhangi bir veriyi değiştirmek için kullanılmamalıdır. Bir link bağlantısını takip etmenin daima en güvenli yolu GET yöntemidir. - That's usually true, but if the navigation is performed in an `