File: CookieStore.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (688 lines) | stat: -rw-r--r-- 25,783 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/*
 * Copyright (C) 2023 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "CookieStore.h"

#include "Cookie.h"
#include "CookieChangeEvent.h"
#include "CookieChangeEventInit.h"
#include "CookieInit.h"
#include "CookieJar.h"
#include "CookieListItem.h"
#include "CookieStoreDeleteOptions.h"
#include "CookieStoreGetOptions.h"
#include "Document.h"
#include "EventNames.h"
#include "ExceptionOr.h"
#include "JSCookieListItem.h"
#include "JSDOMPromiseDeferred.h"
#include "Page.h"
#include "PublicSuffixStore.h"
#include "ScriptExecutionContext.h"
#include "ScriptExecutionContextIdentifier.h"
#include "SecurityOrigin.h"
#include "ServiceWorkerGlobalScope.h"
#include "TaskSource.h"
#include "WorkerGlobalScope.h"
#include "WorkerLoaderProxy.h"
#include "WorkerThread.h"
#include <cmath>
#include <optional>
#include <wtf/CompletionHandler.h>
#include <wtf/Function.h>
#include <wtf/HashMap.h>
#include <wtf/MainThread.h>
#include <wtf/Ref.h>
#include <wtf/Seconds.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/URL.h>
#include <wtf/Vector.h>
#include <wtf/WallTime.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(CookieStore);

class CookieStore::MainThreadBridge : public ThreadSafeRefCounted<MainThreadBridge, WTF::DestructionThread::Main> {
public:
    static Ref<MainThreadBridge> create(CookieStore& cookieStore)
    {
        return adoptRef(*new MainThreadBridge(cookieStore));
    }

    void get(CookieStoreGetOptions&&, URL&&, Function<void(CookieStore&, ExceptionOr<Vector<Cookie>>&&)>&&);
    void getAll(CookieStoreGetOptions&&, URL&&, Function<void(CookieStore&, ExceptionOr<Vector<Cookie>>&&)>&&);
    void set(CookieInit&& options, Cookie&&, URL&&, Function<void(CookieStore&, std::optional<Exception>&&)>&&);

    void detach() { m_cookieStore = nullptr; }

private:
    explicit MainThreadBridge(CookieStore&);

    void ensureOnMainThread(Function<void(ScriptExecutionContext&)>&&);
    void ensureOnContextThread(Function<void(CookieStore&)>&&);

    RefPtr<CookieStore> protectedCookieStore() const { return m_cookieStore.get(); }
    WeakPtr<CookieStore, WeakPtrImplWithEventTargetData> m_cookieStore;
    Markable<ScriptExecutionContextIdentifier> m_contextIdentifier;
};

CookieStore::MainThreadBridge::MainThreadBridge(CookieStore& cookieStore)
    : m_cookieStore(cookieStore)
    , m_contextIdentifier(cookieStore.scriptExecutionContext() ? std::optional { cookieStore.scriptExecutionContext()->identifier() } : std::nullopt)
{
}

void CookieStore::MainThreadBridge::ensureOnMainThread(Function<void(ScriptExecutionContext&)>&& task)
{
    ASSERT(m_cookieStore);

    RefPtr context = protectedCookieStore()->scriptExecutionContext();
    if (!context)
        return;
    ASSERT(context->isContextThread());

    if (is<Document>(*context)) {
        task(*context);
        return;
    }

    downcast<WorkerGlobalScope>(*context).protectedThread()->workerLoaderProxy()->postTaskToLoader(WTFMove(task));
}

void CookieStore::MainThreadBridge::ensureOnContextThread(Function<void(CookieStore&)>&& task)
{
    ScriptExecutionContext::ensureOnContextThread(*m_contextIdentifier, [protectedThis = Ref { *this }, task = WTFMove(task)](auto&) {
        if (RefPtr cookieStore = protectedThis->m_cookieStore.get())
            task(*cookieStore);
    });
}

void CookieStore::MainThreadBridge::get(CookieStoreGetOptions&& options, URL&& url, Function<void(CookieStore&, ExceptionOr<Vector<Cookie>>&&)>&& completionHandler)
{
    ASSERT(m_cookieStore);

    auto getCookies = [protectedThis = Ref { *this }, options = crossThreadCopy(WTFMove(options)), url = crossThreadCopy(WTFMove(url)), completionHandler = WTFMove(completionHandler)](ScriptExecutionContext& context) mutable {
        Ref document = downcast<Document>(context);
        WeakPtr page = document->page();
        if (!page) {
            protectedThis->ensureOnContextThread([completionHandler = WTFMove(completionHandler)](CookieStore& cookieStore) mutable {
                completionHandler(cookieStore, Exception { ExceptionCode::SecurityError });
            });
            return;
        }

        Ref cookieJar = page->cookieJar();
        auto resultHandler = [protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)] (std::optional<Vector<Cookie>>&& cookies) mutable {
            protectedThis->ensureOnContextThread([completionHandler = WTFMove(completionHandler), cookies = crossThreadCopy(WTFMove(cookies))](CookieStore& cookieStore) mutable {
                if (!cookies)
                    completionHandler(cookieStore, Exception { ExceptionCode::TypeError });
                else
                    completionHandler(cookieStore, WTFMove(*cookies));
            });
        };

        cookieJar->getCookiesAsync(document, url, options, WTFMove(resultHandler));
    };

    ensureOnMainThread(WTFMove(getCookies));
}

void CookieStore::MainThreadBridge::getAll(CookieStoreGetOptions&& options, URL&& url, Function<void(CookieStore&, ExceptionOr<Vector<Cookie>>&&)>&& completionHandler)
{
    ASSERT(m_cookieStore);

    auto getAllCookies = [protectedThis = Ref { *this }, options = crossThreadCopy(WTFMove(options)), url = crossThreadCopy(WTFMove(url)), completionHandler = WTFMove(completionHandler)](ScriptExecutionContext& context) mutable {
        Ref document = downcast<Document>(context);
        WeakPtr page = document->page();
        if (!page) {
            protectedThis->ensureOnContextThread([completionHandler = WTFMove(completionHandler)](CookieStore& cookieStore) mutable {
                completionHandler(cookieStore, Exception { ExceptionCode::SecurityError });
            });
            return;
        }

        Ref cookieJar = page->cookieJar();
        auto resultHandler = [protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)] (std::optional<Vector<Cookie>>&& cookies) mutable {
            protectedThis->ensureOnContextThread([completionHandler = WTFMove(completionHandler), cookies = crossThreadCopy(WTFMove(cookies))](CookieStore& cookieStore) mutable {
                if (!cookies)
                    completionHandler(cookieStore, Exception { ExceptionCode::TypeError });
                else
                    completionHandler(cookieStore, WTFMove(*cookies));
            });
        };

        cookieJar->getCookiesAsync(document, url, options, WTFMove(resultHandler));
    };

    ensureOnMainThread(WTFMove(getAllCookies));
}

void CookieStore::MainThreadBridge::set(CookieInit&& options, Cookie&& cookie, URL&& url, Function<void(CookieStore&, std::optional<Exception>&&)>&& completionHandler)
{
    ASSERT(m_cookieStore);

    auto setCookie = [this, protectedThis = Ref { *this }, options = crossThreadCopy(WTFMove(options)), cookie = crossThreadCopy(WTFMove(cookie)), url = crossThreadCopy(WTFMove(url)), completionHandler = WTFMove(completionHandler)](ScriptExecutionContext& context) mutable {
        Ref document = downcast<Document>(context);
        WeakPtr page = document->page();
        if (!page) {
            ensureOnContextThread([completionHandler = WTFMove(completionHandler)](CookieStore& cookieStore) mutable {
                completionHandler(cookieStore, Exception { ExceptionCode::SecurityError });
            });
            return;
        }

        Ref cookieJar = page->cookieJar();
        auto resultHandler = [this, protectedThis = WTFMove(protectedThis), completionHandler = WTFMove(completionHandler)] (bool setSuccessfully) mutable {
            ensureOnContextThread([completionHandler = WTFMove(completionHandler), setSuccessfully](CookieStore& cookieStore) mutable {
                if (!setSuccessfully)
                    completionHandler(cookieStore, Exception { ExceptionCode::TypeError });
                else
                    completionHandler(cookieStore, std::nullopt);
            });
        };

        document->invalidateDOMCookieCache();
        cookieJar->setCookieAsync(document, url, cookie, WTFMove(resultHandler));
    };

    ensureOnMainThread(WTFMove(setCookie));
}

Ref<CookieStore> CookieStore::create(ScriptExecutionContext* context)
{
    auto cookieStore = adoptRef(*new CookieStore(context));
    cookieStore->suspendIfNeeded();
    return cookieStore;
}

CookieStore::CookieStore(ScriptExecutionContext* context)
    : ActiveDOMObject(context)
    , m_mainThreadBridge(MainThreadBridge::create(*this))
{
}

CookieStore::~CookieStore()
{
    protectedMainThreadBridge()->detach();
}

static bool containsInvalidCharacters(const String& string)
{
    // The invalid characters are specified at https://wicg.github.io/cookie-store/#set-a-cookie.
    return string.contains([](UChar character) {
        return character == 0x003B || character == 0x007F || (character <= 0x001F && character != 0x0009);
    });
}

void CookieStore::get(String&& name, Ref<DeferredPromise>&& promise)
{
    get(CookieStoreGetOptions { WTFMove(name), { } }, WTFMove(promise));
}

void CookieStore::get(CookieStoreGetOptions&& options, Ref<DeferredPromise>&& promise)
{
    RefPtr context = scriptExecutionContext();
    if (!context) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    RefPtr origin = context->securityOrigin();
    if (!origin) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    if (origin->isOpaque()) {
        promise->reject(Exception { ExceptionCode::SecurityError, "The origin is opaque"_s });
        return;
    }

    if (options.name.isNull() && options.url.isNull()) {
        promise->reject(Exception { ExceptionCode::TypeError, "CookieStoreGetOptions must not be empty"_s });
        return;
    }

    auto url = context->cookieURL();
    if (!options.url.isNull()) {
        auto parsed = context->completeURL(options.url);
        if (context->isDocument() && !equalIgnoringFragmentIdentifier(parsed, url)) {
            promise->reject(Exception { ExceptionCode::TypeError, "URL must match the document URL"_s });
            return;
        }

        if (!origin->isSameOriginAs(SecurityOrigin::create(parsed))) {
            promise->reject(Exception { ExceptionCode::TypeError, "Origin must match the context's origin"_s });
            return;
        }
        url = WTFMove(parsed);
        options.url = nullString();
    }

    m_promises.add(++m_nextPromiseIdentifier, WTFMove(promise));
    auto completionHandler = [promiseIdentifier = m_nextPromiseIdentifier](CookieStore& cookieStore, ExceptionOr<Vector<Cookie>>&& result) {
        auto promise = cookieStore.takePromise(promiseIdentifier);
        if (!promise)
            return;

        if (result.hasException()) {
            promise->reject(result.releaseException());
            return;
        }

        auto cookies = result.releaseReturnValue();
        if (cookies.isEmpty()) {
            promise->resolveWithJSValue(JSC::jsNull());
            return;
        }

        promise->resolve<IDLDictionary<CookieListItem>>(CookieListItem(WTFMove(cookies[0])));
    };

    protectedMainThreadBridge()->get(WTFMove(options), WTFMove(url), WTFMove(completionHandler));
}

void CookieStore::getAll(String&& name, Ref<DeferredPromise>&& promise)
{
    getAll(CookieStoreGetOptions { WTFMove(name), { } }, WTFMove(promise));
}

void CookieStore::getAll(CookieStoreGetOptions&& options, Ref<DeferredPromise>&& promise)
{
    RefPtr context = scriptExecutionContext();
    if (!context) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    RefPtr origin = context->securityOrigin();
    if (!origin) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    if (origin->isOpaque()) {
        promise->reject(Exception { ExceptionCode::SecurityError, "The origin is opaque"_s });
        return;
    }

    auto url = context->cookieURL();
    if (!options.url.isNull()) {
        auto parsed = context->completeURL(options.url);
        if (context->isDocument() && !equalIgnoringFragmentIdentifier(parsed, url)) {
            promise->reject(Exception { ExceptionCode::TypeError, "URL must match the document URL"_s });
            return;
        }

        if (!origin->isSameOriginAs(SecurityOrigin::create(parsed))) {
            promise->reject(Exception { ExceptionCode::TypeError, "Origin must match the context's origin"_s });
            return;
        }
        url = WTFMove(parsed);
        options.url = nullString();
    }

    m_promises.add(++m_nextPromiseIdentifier, WTFMove(promise));
    auto completionHandler = [promiseIdentifier = m_nextPromiseIdentifier](CookieStore& cookieStore, ExceptionOr<Vector<Cookie>>&& result) {
        auto promise = cookieStore.takePromise(promiseIdentifier);
        if (!promise)
            return;

        if (result.hasException()) {
            promise->reject(result.releaseException());
            return;
        }

        auto cookies = result.releaseReturnValue();
        promise->resolve<IDLSequence<IDLDictionary<CookieListItem>>>(WTF::map(WTFMove(cookies), [](Cookie&& cookie) {
            return CookieListItem { WTFMove(cookie) };
        }));
    };

    protectedMainThreadBridge()->getAll(WTFMove(options), WTFMove(url), WTFMove(completionHandler));
}

void CookieStore::set(String&& name, String&& value, Ref<DeferredPromise>&& promise)
{
    set(CookieInit { WTFMove(name), WTFMove(value) }, WTFMove(promise));
}

void CookieStore::set(CookieInit&& options, Ref<DeferredPromise>&& promise)
{
    RefPtr context = scriptExecutionContext();
    if (!context) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    RefPtr origin = context->securityOrigin();
    if (!origin) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    if (origin->isOpaque()) {
        promise->reject(Exception { ExceptionCode::SecurityError, "The origin is opaque"_s });
        return;
    }

    // The maximum attribute value size is specified at https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size.
    static constexpr auto maximumAttributeValueSize = 1024;

    auto url = context->cookieURL();
    auto host = url.host();
    auto domain = origin->domain();

    Cookie cookie;
    cookie.created = WallTime::now().secondsSinceEpoch().milliseconds();

    cookie.name = WTFMove(options.name);
    cookie.value = WTFMove(options.value);

    if (containsInvalidCharacters(cookie.name)) {
        promise->reject(Exception { ExceptionCode::TypeError, "The cookie name must not contain '\u003B', '\u007F', or any C0 control character except '\u0009'."_s });
        return;
    }

    if (containsInvalidCharacters(cookie.value)) {
        promise->reject(Exception { ExceptionCode::TypeError, "The cookie value must not contain '\u003B', '\u007F', or any C0 control character except '\u0009'."_s });
        return;
    }

    if (cookie.name.isEmpty()) {
        if (cookie.value.contains('=')) {
            promise->reject(Exception { ExceptionCode::TypeError, "The cookie name and value must not both be set from the 'value' field."_s });
            return;
        }

        if (cookie.value.isEmpty()) {
            promise->reject(Exception { ExceptionCode::TypeError, "The cookie name and value must not both be empty."_s });
            return;
        }
    }

    if (cookie.name.startsWithIgnoringASCIICase("__Host-"_s)) {
        if (!options.domain.isNull()) {
            promise->reject(Exception { ExceptionCode::TypeError, "If the cookie name begins with \"__Host-\", the domain must not be specified."_s });
            return;
        }

        if (!options.path.isNull() && options.path != "/"_s)  {
            promise->reject(Exception { ExceptionCode::TypeError, "If the cookie name begins with \"__Host-\", the path must either not be specified or be \"/\"."_s });
            return;
        }
    }

    cookie.domain = options.domain.isNull() ? domain : options.domain;
    if (!cookie.domain.isNull()) {
        if (cookie.domain.startsWith('.')) {
            promise->reject(Exception { ExceptionCode::TypeError, "The domain must not begin with a '.'"_s });
            return;
        }

        if (!host.endsWith(cookie.domain) || (host.length() > cookie.domain.length() && !host.substring(0, host.length() - cookie.domain.length()).endsWith('.'))) {
            promise->reject(Exception { ExceptionCode::TypeError, "The domain must domain-match current host"_s });
            return;
        }

        // FIXME: <rdar://85515842> Obtain the encoded length without allocating and encoding.
        if (cookie.domain.utf8().length() > maximumAttributeValueSize) {
            promise->reject(Exception { ExceptionCode::TypeError, makeString("The size of the domain must not be greater than "_s, maximumAttributeValueSize, " bytes"_s) });
            return;
        }

        if (PublicSuffixStore::singleton().isPublicSuffix(cookie.domain)) {
            promise->reject(Exception { ExceptionCode::TypeError, "The domain must not be a public suffix"_s });
            return;
        }

        // In CFNetwork, a domain without a leading dot means host-only cookie.
        // If a non-null domain was passed in, prepend dot to domain to set
        // host-only to false and make the cookie accessible by subdomains.
        if (!options.domain.isNull())
            cookie.domain = makeString('.', cookie.domain);
    }

    cookie.path = WTFMove(options.path);
    if (!cookie.path.isNull()) {
        if (!cookie.path.startsWith('/')) {
            promise->reject(Exception { ExceptionCode::TypeError, "The path must begin with a '/'"_s });
            return;
        }

        if (!cookie.path.endsWith('/'))
            cookie.path = makeString(cookie.path, '/');

        // FIXME: <rdar://85515842> Obtain the encoded length without allocating and encoding.
        if (cookie.path.utf8().length() > maximumAttributeValueSize) {
            promise->reject(Exception { ExceptionCode::TypeError, makeString("The size of the path must not be greater than "_s, maximumAttributeValueSize, " bytes"_s) });
            return;
        }
    }

    if (options.expires) {
        // When this cookie is converted to an NSHTTPCookie, the creation and expiration
        // times will first be converted to seconds and then CFNetwork will floor these times.
        // If the creation and expiration differ by less than 1 second, flooring them may
        // reduce the difference to 0 seconds. This can cause the onchange event to wrongly
        // fire as a deletion instead of a change. In such cases, account for this flooring by
        // adding 1 second to the expiration.

        auto expires = *options.expires;
        bool equalAfterConversion = floor(expires / 1000.0) == floor(cookie.created / 1000.0);
        if (equalAfterConversion && (expires > cookie.created))
            expires += 1000.0;

        cookie.expires = expires;
    }

    switch (options.sameSite) {
    case CookieSameSite::Strict:
        cookie.sameSite = Cookie::SameSitePolicy::Strict;
        break;
    case CookieSameSite::Lax:
        cookie.sameSite = Cookie::SameSitePolicy::Lax;
        break;
    case CookieSameSite::None:
        cookie.sameSite = Cookie::SameSitePolicy::None;
        break;
    }

    cookie.secure = true;

    m_promises.add(++m_nextPromiseIdentifier, WTFMove(promise));
    auto completionHandler = [promiseIdentifier = m_nextPromiseIdentifier](CookieStore& cookieStore, std::optional<Exception>&& result) {
        auto promise = cookieStore.takePromise(promiseIdentifier);
        if (!promise)
            return;

        if (result)
            promise->reject(*result);
        else
            promise->resolve();
    };

    protectedMainThreadBridge()->set(WTFMove(options), WTFMove(cookie), WTFMove(url), WTFMove(completionHandler));
}

void CookieStore::remove(String&& name, Ref<DeferredPromise>&& promise)
{
    remove(CookieStoreDeleteOptions { WTFMove(name), { } }, WTFMove(promise));
}

void CookieStore::remove(CookieStoreDeleteOptions&& options, Ref<DeferredPromise>&& promise)
{
    RefPtr context = scriptExecutionContext();
    if (!context) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    RefPtr origin = context->securityOrigin();
    if (!origin) {
        promise->reject(ExceptionCode::SecurityError);
        return;
    }

    if (origin->isOpaque()) {
        promise->reject(Exception { ExceptionCode::SecurityError, "The origin is opaque"_s });
        return;
    }

    CookieInit initOptions;
    initOptions.name = WTFMove(options.name);
    initOptions.value = emptyString();
    initOptions.domain = WTFMove(options.domain);
    initOptions.path = WTFMove(options.path);
    initOptions.expires = (WallTime::now() - 24_h).secondsSinceEpoch().milliseconds();

    set(WTFMove(initOptions), WTFMove(promise));
}

void CookieStore::cookiesAdded(const String& host, const Vector<Cookie>& cookies)
{
    ASSERT(m_hasChangeEventListener);

    RefPtr context = scriptExecutionContext();
    if (!context)
        return;

    ASSERT_UNUSED(host, host == downcast<Document>(context)->url().host().toString());

    CookieChangeEventInit eventInit;
    for (auto cookie : cookies) {
        if (cookie.expires && *cookie.expires <= cookie.created) {
            cookie.value = nullString();
            eventInit.deleted.append(CookieListItem { WTFMove(cookie) });
        } else
            eventInit.changed.append(CookieListItem { WTFMove(cookie) });
    }

    queueTaskToDispatchEvent(*this, TaskSource::DOMManipulation, CookieChangeEvent::create(eventNames().changeEvent, WTFMove(eventInit), CookieChangeEvent::IsTrusted::Yes));
}

void CookieStore::cookiesDeleted(const String& host, const Vector<Cookie>& cookies)
{
    ASSERT(m_hasChangeEventListener);

    RefPtr context = scriptExecutionContext();
    if (!context)
        return;

    ASSERT_UNUSED(host, host == downcast<Document>(context)->url().host().toString());

    CookieChangeEventInit eventInit;
    eventInit.deleted = cookies.map([](auto cookie) {
        cookie.value = nullString();
        return CookieListItem { WTFMove(cookie) };
    });

    queueTaskToDispatchEvent(*this, TaskSource::DOMManipulation, CookieChangeEvent::create(eventNames().changeEvent, WTFMove(eventInit), CookieChangeEvent::IsTrusted::Yes));
}

void CookieStore::stop()
{
    // FIXME: This should work for service worker contexts as well.
    RefPtr document = dynamicDowncast<Document>(scriptExecutionContext());
    if (!document)
        return;

    if (!m_hasChangeEventListener)
        return;

    WeakPtr page = document->page();
    if (!page)
        return;

#if HAVE(COOKIE_CHANGE_LISTENER_API)
    auto host = document->url().host().toString();
    if (host.isEmpty())
        return;

    page->protectedCookieJar()->removeChangeListener(host, *this);
#endif
    m_hasChangeEventListener = false;
}

bool CookieStore::virtualHasPendingActivity() const
{
    return m_hasChangeEventListener;
}

enum EventTargetInterfaceType CookieStore::eventTargetInterface() const
{
    return EventTargetInterfaceType::CookieStore;
}

ScriptExecutionContext* CookieStore::scriptExecutionContext() const
{
    return ActiveDOMObject::scriptExecutionContext();
}

void CookieStore::eventListenersDidChange()
{
    // FIXME: This should work for service worker contexts as well.
    RefPtr document = dynamicDowncast<Document>(scriptExecutionContext());
    if (!document)
        return;

    auto host = document->url().host().toString();
    if (host.isEmpty())
        return;

    bool hadChangeEventListener = m_hasChangeEventListener;
    m_hasChangeEventListener = hasEventListeners(eventNames().changeEvent);

    if (hadChangeEventListener == m_hasChangeEventListener)
        return;

    WeakPtr page = document->page();
    if (!page)
        return;

#if HAVE(COOKIE_CHANGE_LISTENER_API)
    Ref cookieJar = page->cookieJar();
    if (m_hasChangeEventListener)
        cookieJar->addChangeListener(*document, *this);
    else
        cookieJar->removeChangeListener(host, *this);
#endif
}

RefPtr<DeferredPromise> CookieStore::takePromise(uint64_t promiseIdentifier)
{
    return m_promises.take(promiseIdentifier);
}

Ref<CookieStore::MainThreadBridge> CookieStore::protectedMainThreadBridge() const
{
    return m_mainThreadBridge;
}

}