-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.bs
1435 lines (1116 loc) · 61.3 KB
/
index.bs
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class='metadata'>
Title: Cookie Store API
Shortname: cookie-store
Level: 1
Status: CG-DRAFT
Group: WICG
ED: https://wicg.github.io/cookie-store/
Repository: WICG/cookie-store
Editor: Ayu Ishii, Google Inc. https://google.com, [email protected]
Editor: Joshua Bell, Google Inc. https://google.com, [email protected]
Favicon: logo-cookies.svg
Former Editor: Raymond Toy, Google Inc. https://google.com, [email protected]
Former Editor: Victor Costan, Google Inc. https://google.com, [email protected]
Markup Shorthands: markdown yes, css no, biblio yes
Abstract: An asynchronous Javascript cookies API for documents and service workers
Test Suite: https://github.com/web-platform-tests/wpt/tree/master/cookie-store
Include MDN Panels: yes
Assume Explicit For: yes
</pre>
<pre class=biblio>
{
"RFC6265BIS-14": {
"authors": [ "S. Bingler", "M. West", "J. Wilander" ],
"href": "https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-14",
"title": "Cookies: HTTP State Management Mechanism",
"publisher": "IETF",
"status": "Internet-Draft"
}
}
</pre>
<pre class=anchors>
spec: ecma262; urlPrefix: https://tc39.github.io/ecma262/
type: dfn
text: time values; url: sec-time-values-and-time-range
spec: html; urlPrefix: https://html.spec.whatwg.org/multipage/
urlPrefix: webappapis.html
type: dfn
text: DOM manipulation task source; url: dom-manipulation-task-source
</pre>
<pre class=link-defaults>
spec:service-workers; type:dfn; for:/; text:service worker
spec:service-workers; type:dfn; for:/; text:service worker registration
</pre>
<style>
.domintro::before {
content: 'For web developers (non-normative)';
text-transform: initial;
}
.domintro dt {
font-family: Menlo, Consolas, "DejaVu Sans Mono", Monaco, monospace;
padding-top: 0.5em;
padding-bottom: 1em;
}
.domintro dt a {
color: inherit; border-bottom-style: none;
}
.domintro dt code {
font-size: inherit;
}
</style>
<img id="speclogo" src="logo-cookies.svg" alt="logo" width="100" height="100">
<style>
#speclogo { height: 100px; width: 100px; background-color: transparent; }
main #speclogo { position: absolute; right: 20px; top: 30px; }
.logo #speclogo { margin-top: 20px; }
</style>
<script>
(function() {
const logo = document.querySelector('.logo');
if (logo) logo.appendChild(document.querySelector('#speclogo'));
})();
</script>
<!-- ============================================================ -->
# Introduction # {#intro}
<!-- ============================================================ -->
*This section is non-normative.*
This is a proposal to bring an asynchronous cookie API to scripts running in HTML documents and [[Service-Workers|service workers]].
[[RFC6265BIS-14|HTTP cookies]] have, since their origins at Netscape [(documentation preserved by archive.org)](https://web.archive.org/web/0/http://wp.netscape.com/newsref/std/cookie_spec.html), provided a [valuable state-management mechanism](https://montulli.blogspot.com/2013/05/the-reasoning-behind-web-cookies.html) for the web.
The synchronous single-threaded script-level {{Document/cookie|document.cookie}} interface to cookies has been a source of [complexity and performance woes](https://lists.w3.org/Archives/Public/public-whatwg-archive/2009Sep/0083.html) further exacerbated by the move in many browsers from:
- a single browser process,
- a single-threaded event loop model, and
- no general expectation of responsiveness for scripted event handling while processing cookie operations
... to the modern web which strives for smoothly responsive high performance:
- in multiple browser processes,
- with a multithreaded, multiple-event loop model, and
- with an expectation of responsiveness on human-reflex time scales.
On the modern web a cookie operation in one part of a web application cannot block:
- the rest of the web application,
- the rest of the web origin, or
- the browser as a whole.
Newer parts of the web built in service workers [need access to cookies too](https://github.com/w3c/ServiceWorker/issues/707) but cannot use the synchronous, blocking {{Document/cookie|document.cookie}} interface at all as they both have no `document` and also cannot block the event loop as that would interfere with handling of unrelated events.
<!-- ============================================================ -->
## A Taste of the Proposed Change ## {#intro-proposed-change}
<!-- ============================================================ -->
Although it is tempting to [rethink cookies](https://discourse.wicg.io/t/rethinking-cookies/744) entirely, web sites today continue to rely heavily on them, and the script APIs for using them are largely unchanged over their first decades of usage.
Today writing a cookie means blocking your event loop while waiting for the browser to synchronously update the cookie jar with a carefully-crafted cookie string in `Set-Cookie` format:
<div class=example>
```js
document.cookie =
'__Secure-COOKIENAME=cookie-value' +
'; Path=/' +
'; expires=Fri, 12 Aug 2016 23:05:17 GMT' +
'; Secure' +
'; Domain=example.org';
// now we could assume the write succeeded, but since
// failure is silent it is difficult to tell, so we
// read to see whether the write succeeded
var successRegExp =
/(^|; ?)__Secure-COOKIENAME=cookie-value(;|$)/;
if (String(document.cookie).match(successRegExp)) {
console.log('It worked!');
} else {
console.error('It did not work, and we do not know why');
}
```
</div>
What if you could instead write:
<div class=example>
```js
const one_day_ms = 24 * 60 * 60 * 1000;
cookieStore.set(
{
name: '__Secure-COOKIENAME',
value: 'cookie-value',
expires: Date.now() + one_day_ms,
domain: 'example.org'
}).then(function() {
console.log('It worked!');
}, function(reason) {
console.error(
'It did not work, and this is why:',
reason);
});
// Meanwhile we can do other things while waiting for
// the cookie store to process the write...
```
</div>
This also has the advantage of not relying on `document` and not blocking, which together make it usable from [[Service-Workers|Service Workers]], which otherwise do not have cookie access from script.
This proposal also includes a power-efficient monitoring API to replace `setTimeout`-based polling cookie monitors with cookie change observers.
<!-- ============================================================ -->
## Summary ## {#intro-summary}
<!-- ============================================================ -->
This proposal outlines an asynchronous API using Promises/async functions for the following cookie operations:
* [[#intro-modify|write]] (or "set") and delete (or "expire") cookies
* [[#intro-query|read]] (or "get") [=script-visible=] cookies
* ... including for specified in-scope request paths in
[[Service-Workers|service worker]] contexts
* [[#intro-monitor|monitor]] [=script-visible=] cookies for changes using `CookieChangeEvent`
* ... in long-running script contexts (e.g. `document`)
* ... for script-supplied in-scope request paths in [[Service-Workers|service worker]] contexts
<!-- ============================================================ -->
## Querying Cookies ## {#intro-query}
<!-- ============================================================ -->
Both [=documents=] and [=service workers=] access the same query API, via the
{{Window/cookieStore}} property on the [[#globals|global object]].
The {{CookieStore/get()}} and {{CookieStore/getAll()}} methods on {{CookieStore}} are used to query cookies.
Both methods return {{Promise}}s.
Both methods take the same arguments, which can be either:
* a name, or
* a dictionary of options (optional for {{CookieStore/getAll()}})
The {{CookieStore/get()}} method is essentially a form of {{CookieStore/getAll()}} that only returns the first result.
<div class=example>
Reading a cookie:
```js
try {
const cookie = await cookieStore.get('session_id');
if (cookie) {
console.log(`Found ${cookie.name} cookie: ${cookie.value}`);
} else {
console.log('Cookie not found');
}
} catch (e) {
console.error(`Cookie store error: ${e}`);
}
```
</div>
<div class=example>
Reading multiple cookies:
```js
try {
const cookies = await cookieStore.getAll('session_id'});
for (const cookie of cookies)
console.log(`Result: ${cookie.name} = ${cookie.value}`);
} catch (e) {
console.error(`Cookie store error: ${e}`);
}
```
</div>
[=Service workers=] can obtain the list of cookies that would be sent by a [=/fetch=] to
any URL under their [=service worker registration/scope url|scope=].
<div class=example>
Read the cookies for a specific URL (in a [=service worker=]):
```js
await cookieStore.getAll({url: '/admin'});
```
</div>
[=Documents=] can only obtain the cookies at their current URL. In other words,
the only valid {{CookieStoreGetOptions/url}} value in [=Document=] contexts is the document's URL.
The objects returned by {{CookieStore/get()}} and {{CookieStore/getAll()}} contain all the relevant information in the cookie store, not just the [=cookie/name=] and the [=cookie/value=] as in the older {{Document/cookie|document.cookie}} API.
<div class=example>
Accessing all the cookie data:
```js
await cookie = cookieStore.get('session_id');
console.log(`Cookie scope - Domain: ${cookie.domain} Path: ${cookie.path}`);
if (cookie.expires === null) {
console.log('Cookie expires at the end of the session');
} else {
console.log(`Cookie expires at: ${cookie.expires}`);
}
if (cookie.secure)
console.log('The cookie is restricted to secure origins');
```
</div>
<!-- ============================================================ -->
## Modifying Cookies ## {#intro-modify}
<!-- ============================================================ -->
Both [=documents=] and [=service workers=] access the same modification API, via the
{{Window/cookieStore}} property on the [[#globals|global object]].
Cookies are created or modified (written) using the {{CookieStore/set(name, value)|set()}} method.
<div class=example>
Write a cookie:
```js
try {
await cookieStore.set('opted_out', '1');
} catch (e) {
console.error(`Failed to set cookie: ${e}`);
}
```
The {{CookieStore/set(name, value)|set()}} call above is shorthand for using an options dictionary, as follows:
```js
await cookieStore.set({
name: 'opted_out',
value: '1',
expires: null, // session cookie
// By default, domain is set to null which means the scope is locked at the current domain.
domain: null,
path: '/'
});
```
</div>
Cookies are deleted (expired) using the {{CookieStore/delete(name)|delete()}} method.
<div class=example>
Delete a cookie:
```js
try {
await cookieStore.delete('session_id');
} catch (e) {
console.error(`Failed to delete cookie: ${e}`);
}
```
</div>
Under the hood, deleting a cookie is done by changing the cookie's expiration date to the past, which still works.
<div class=example>
Deleting a cookie by changing the expiry date:
```js
try {
const one_day_ms = 24 * 60 * 60 * 1000;
await cookieStore.set({
name: 'session_id',
value: 'value will be ignored',
expires: Date.now() - one_day_ms });
} catch (e) {
console.error(`Failed to delete cookie: ${e}`);
}
```
</div>
<!-- ============================================================ -->
## Monitoring Cookies ## {#intro-monitor}
<!-- ============================================================ -->
To avoid polling, it is possible to observe changes to cookies.
In [=documents=], `change` events are fired for all relevant cookie changes.
<div class=example>
Register for `change` events in documents:
```js
cookieStore.addEventListener('change', event => {
console.log(`${event.changed.length} changed cookies`);
for (const cookie in event.changed)
console.log(`Cookie ${cookie.name} changed to ${cookie.value}`);
console.log(`${event.deleted.length} deleted cookies`);
for (const cookie in event.deleted)
console.log(`Cookie ${cookie.name} deleted`);
});
```
</div>
In [=service workers=], `cookiechange` events are fired against the global scope, but an explicit subscription is required, associated with the service worker's registration.
<div class=example>
Register for `cookiechange` events in a service worker:
```js
self.addEventListener('activate', (event) => {
event.waitUntil(async () => {
// Snapshot current state of subscriptions.
const subscriptions = await self.registration.cookies.getSubscriptions();
// Clear any existing subscriptions.
await self.registration.cookies.unsubscribe(subscriptions);
await self.registration.cookies.subscribe([
{
name: 'session_id', // Get change events for cookies named session_id.
}
]);
});
});
self.addEventListener('cookiechange', event => {
// The event has |changed| and |deleted| properties with
// the same semantics as the Document events.
console.log(`${event.changed.length} changed cookies`);
console.log(`${event.deleted.length} deleted cookies`);
});
```
</div>
Calls to {{CookieStoreManager/subscribe()}} are cumulative, so that independently maintained
modules or libraries can set up their own subscriptions. As expected, a [=service worker=]'s
subscriptions are persisted for with the [=service worker registration=].
Subscriptions can use the same options as {{CookieStore/get()}} and {{CookieStore/getAll()}}.
The complexity of fine-grained subscriptions is justified
by the cost of dispatching an irrelevant cookie change event to a [=service worker=],
which is is much higher than the cost of dispatching an equivalent event
to a {{Window}}. Specifically, dispatching an event to a [=service worker=] might
require waking up the worker, which has a significant impact on battery life.
The {{CookieStoreManager/getSubscriptions()}} allows a [=service worker=] to introspect
the subscriptions that have been made.
<div class=example>
Checking change subscriptions:
```js
const subscriptions = await self.registration.cookies.getSubscriptions();
for (const sub of subscriptions) {
console.log(sub.name, sub.url);
}
```
</div>
<!-- ============================================================ -->
# Concepts # {#concepts}
<!-- ============================================================ -->
<!-- ============================================================ -->
## Cookie ## {#cookie-concept}
<!-- ============================================================ -->
A <dfn>cookie</dfn> is normatively defined for user agents by [[RFC6265BIS-14#name-user-agent-requirements|Cookies § User Agent Requirements]].
<div dfn-for=cookie>
Per [[RFC6265BIS-14#name-storage-model|Cookies § Storage Model]], a [=cookie=] has the following fields:
<dfn>name</dfn>,
<dfn>value</dfn>,
<dfn>expiry-time</dfn>,
<dfn>domain</dfn>,
<dfn>path</dfn>,
<dfn>creation-time</dfn>,
<dfn>last-access-time</dfn>,
<dfn>persistent-flag</dfn>,
<dfn>host-only-flag</dfn>,
<dfn>secure-only-flag</dfn>,
<dfn>http-only-flag</dfn>,
<dfn>same-site-flag</dfn>.
</div>
A cookie is <dfn>script-visible</dfn> when it is in-scope and does not have the `HttpOnly` cookie flag. This is more formally enforced in the processing model, which consults [[RFC6265BIS-14#name-retrieval-model|Cookies § Retrieval Model]] at appropriate points.
A cookie is also subject to certain size limits. Per [[RFC6265BIS-14#name-storage-model|Cookies § Storage Model]]:
* The combined lengths of the name and value fields must not be greater than 4096 [=bytes=] (the <dfn for=cookie>maximum name/value pair size</dfn>).
* The length of every field except the name and value fields must not be greater than 1024 [=bytes=] (the <dfn for=cookie>maximum attribute value size</dfn>).
NOTE: [=Cookie=] attribute-values are stored as [=byte sequences=], not strings.
<!-- ============================================================ -->
## Cookie Store ## {#cookie-store--concept}
<!-- ============================================================ -->
A <dfn>cookie store</dfn> is normatively defined for user agents by [[RFC6265BIS-14#name-user-agent-requirements|Cookies § User Agent Requirements]].
When any of the following conditions occur for a [=cookie store=], perform the steps to [=process cookie changes=].
* A newly-created [=cookie=] is inserted into the [=cookie store=].
* A user agent evicts expired [=cookies=] from the [=cookie store=].
* A user agent removes excess [=cookies=] from the [=cookie store=].
<!-- ============================================================ -->
## Extensions to Service Worker ## {#service-worker-extensions}
<!-- ============================================================ -->
[[Service-Workers]] defines [=service worker registration=], which this specification extends.
A [=service worker registration=] has an associated <dfn>cookie change subscription list</dfn> which is a [=/list=];
each member is a <dfn>cookie change subscription</dfn>. A [=cookie change subscription=] is
<span dfn-for="cookie change subscription">
a [=tuple=] of <dfn>name</dfn> and <dfn>url</dfn>.
</span>
<!-- ============================================================ -->
# The {{CookieStore}} Interface # {#CookieStore}
<!-- ============================================================ -->
<xmp class=idl>
[Exposed=(ServiceWorker,Window),
SecureContext]
interface CookieStore : EventTarget {
Promise<CookieListItem?> get(USVString name);
Promise<CookieListItem?> get(optional CookieStoreGetOptions options = {});
Promise<CookieList> getAll(USVString name);
Promise<CookieList> getAll(optional CookieStoreGetOptions options = {});
Promise<undefined> set(USVString name, USVString value);
Promise<undefined> set(CookieInit options);
Promise<undefined> delete(USVString name);
Promise<undefined> delete(CookieStoreDeleteOptions options);
[Exposed=Window]
attribute EventHandler onchange;
};
dictionary CookieStoreGetOptions {
USVString name;
USVString url;
};
enum CookieSameSite {
"strict",
"lax",
"none"
};
dictionary CookieInit {
required USVString name;
required USVString value;
DOMHighResTimeStamp? expires = null;
USVString? domain = null;
USVString path = "/";
CookieSameSite sameSite = "strict";
boolean partitioned = false;
};
dictionary CookieStoreDeleteOptions {
required USVString name;
USVString? domain = null;
USVString path = "/";
boolean partitioned = false;
};
dictionary CookieListItem {
USVString name;
USVString value;
USVString? domain;
USVString path;
DOMHighResTimeStamp? expires;
boolean secure;
CookieSameSite sameSite;
boolean partitioned;
};
typedef sequence<CookieListItem> CookieList;
</xmp>
<!-- ============================================================ -->
## The {{CookieStore/get()}} method ## {#CookieStore-get}
<!-- ============================================================ -->
<div class="domintro note">
: |cookie| = await cookieStore . {{CookieStore/get(name)|get}}(<var ignore>name</var>)
: |cookie| = await cookieStore . {{CookieStore/get(options)|get}}(<var ignore>options</var>)
:: Returns a promise resolving to the first in-scope [=script-visible=] value
for a given cookie name (or other options).
In a service worker context this defaults to the path of the service worker's registered scope.
In a document it defaults to the path of the current document and does not respect changes from {{History/replaceState()}} or {{Document/domain|document.domain}}.
</div>
<div algorithm>
The <dfn method for=CookieStore>get(|name|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |list| be the results of running [=query cookies=] with
|url| and |name|.
1. If |list| is failure, then [=/reject=] |p| with a {{TypeError}} and abort these steps.
1. If |list| [=list/is empty=], then [=/resolve=] |p| with null.
1. Otherwise, [=/resolve=] |p| with the first item of |list|.
1. Return |p|.
</div>
<div algorithm>
The <dfn method for=CookieStore>get(|options|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. If |options| is empty, then return [=a promise rejected with=] a {{TypeError}}.
1. If |options|["{{CookieStoreGetOptions/url}}"] is present, then run these steps:
1. Let |parsed| be the result of [=basic URL parser|parsing=] |options|["{{CookieStoreGetOptions/url}}"] with |settings|'s [=environment settings object/API base URL=].
1. If [=/this=]'s [=/relevant global object=] is a {{Window}} object and |parsed| does not [=url/equal=] |url|,
then return [=a promise rejected with=] a {{TypeError}}.
1. If |parsed|'s [=url/origin=] and |url|'s [=url/origin=] are not the [=same origin=],
then return [=a promise rejected with=] a {{TypeError}}.
1. Set |url| to |parsed|.
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |list| be the results of running [=query cookies=] with
|url| and
|options|["{{CookieStoreGetOptions/name}}"] (if present).
1. If |list| is failure, then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. If |list| [=list/is empty=], then [=/resolve=] |p| with null.
1. Otherwise, [=/resolve=] |p| with the first item of |list|.
1. Return |p|.
</div>
<!-- ============================================================ -->
## The {{CookieStore/getAll()}} method ## {#CookieStore-getAll}
<!-- ============================================================ -->
<div class="domintro note">
: |cookies| = await cookieStore . {{CookieStore/getAll(name)|getAll}}(<var ignore>name</var>)
: |cookies| = await cookieStore . {{CookieStore/getAll(options)|getAll}}(<var ignore>options</var>)
:: Returns a promise resolving to the all in-scope [=script-visible=] value for a given cookie name (or other options).
In a service worker context this defaults to the path of the service worker's registered scope.
In a document it defaults to the path of the current document and does not respect changes from {{History/replaceState()}} or {{Document/domain|document.domain}}.
</div>
<div algorithm>
The <dfn method for=CookieStore>getAll(|name|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |list| be the results of running [=query cookies=] with
|url| and |name|.
1. If |list| is failure, then [=reject=] |p| with a {{TypeError}}.
1. Otherwise, [=/resolve=] |p| with |list|.
1. Return |p|.
</div>
<div algorithm>
The <dfn method for=CookieStore>getAll(|options|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. If |options|["{{CookieStoreGetOptions/url}}"] is present, then run these steps:
1. Let |parsed| be the result of [=basic URL parser|parsing=] |options|["{{CookieStoreGetOptions/url}}"] with |settings|'s [=environment settings object/API base URL=].
1. If [=/this=]'s [=/relevant global object=] is a {{Window}} object and |parsed| does not [=url/equal=] |url|,
then return [=a promise rejected with=] a {{TypeError}}.
1. If |parsed|'s [=url/origin=] and |url|'s [=url/origin=] are not the [=same origin=],
then return [=a promise rejected with=] a {{TypeError}}.
1. Set |url| to |parsed|.
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |list| be the results of running [=query cookies=] with
|url| and
|options|["{{CookieStoreGetOptions/name}}"] (if present).
1. If |list| is failure, then [=reject=] |p| with a {{TypeError}}.
1. Otherwise, [=/resolve=] |p| with |list|.
1. Return |p|.
</div>
<!-- ============================================================ -->
## The {{CookieStore/set(name, value)|set()}} method ## {#CookieStore-set}
<!-- ============================================================ -->
<div class="domintro note">
: await cookieStore . {{CookieStore/set(name, value)|set}}(<var ignore>name</var>, <var ignore>value</var>)
: await cookieStore . {{CookieStore/set(options)|set}}(<var ignore>options</var>)
:: Writes (creates or modifies) a cookie.
The options default to:
* Path: `/`
* Domain: same as the domain of the current document or service worker's location
* No expiry date
* SameSite: strict
</div>
<div algorithm>
The <dfn method for=CookieStore>set(|name|, |value|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. Let |domain| be null.
1. Let |path| be "/".
1. Let |sameSite| be {{CookieSameSite/strict}}.
1. Let |partitioned| be false.
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |r| be the result of running [=set a cookie=] with
|url|,
|name|,
|value|,
|domain|,
|path|,
|sameSite|, and
|partitioned|.
1. If |r| is failure, then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. [=/Resolve=] |p| with undefined.
1. Return |p|.
</div>
<div algorithm>
The <dfn method for=CookieStore>set(|options|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |r| be the result of running [=set a cookie=] with
|url|,
|options|["{{CookieInit/name}}"],
|options|["{{CookieInit/value}}"],
|options|["{{CookieInit/expires}}"],
|options|["{{CookieInit/domain}}"],
|options|["{{CookieInit/path}}"],
|options|["{{CookieInit/sameSite}}"], and
|options|["{{CookieInit/partitioned}}"].
1. If |r| is failure, then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. [=/Resolve=] |p| with undefined.
1. Return |p|.
</div>
<!-- ============================================================ -->
## The {{CookieStore/delete(name)|delete()}} method ## {#CookieStore-delete}
<!-- ============================================================ -->
<div class="domintro note">
: await cookieStore . {{CookieStore/delete(name)|delete}}(<var ignore>name</var>)
: await cookieStore . {{CookieStore/delete(options)|delete}}(<var ignore>options</var>)
:: Deletes (expires) a cookie with the given name or name and optional domain and path.
</div>
<div algorithm>
The <dfn method for=CookieStore>delete(|name|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |r| be the result of running [=delete a cookie=] with
|url|,
|name|,
null,
"`/`",
true, and
"{{CookieSameSite/strict}}".
1. If |r| is failure, then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. [=/Resolve=] |p| with undefined.
1. Return |p|.
</div>
<div algorithm>
The <dfn method for=CookieStore>delete(|options|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |origin| be |settings|'s [=environment settings object/origin=].
1. If |origin| is an [=opaque origin=], then return [=a promise rejected with=] a "{{SecurityError}}" {{DOMException}}.
1. Let |url| be |settings|'s [=environment/creation URL=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |r| be the result of running [=delete a cookie=] with
|url|,
|options|["{{CookieStoreDeleteOptions/name}}"],
|options|["{{CookieStoreDeleteOptions/domain}}"],
|options|["{{CookieStoreDeleteOptions/path}}"], and
|options|["{{CookieStoreDeleteOptions/partitioned}}"].
1. If |r| is failure, then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. [=/Resolve=] |p| with undefined.
1. Return |p|.
</div>
<!-- ============================================================ -->
# The {{CookieStoreManager}} Interface # {#CookieStoreManager}
<!-- ============================================================ -->
A {{CookieStoreManager}} has an associated <dfn for=CookieStoreManager>registration</dfn> which is a [=service worker registration=].
The {{CookieStoreManager}} interface allows [=Service Workers=] to subscribe to events for cookie changes. Using the {{CookieStoreManager/subscribe()}} method is necessary to indicate that a particular [=service worker registration=] is interested in change events.
<xmp class=idl>
[Exposed=(ServiceWorker,Window),
SecureContext]
interface CookieStoreManager {
Promise<undefined> subscribe(sequence<CookieStoreGetOptions> subscriptions);
Promise<sequence<CookieStoreGetOptions>> getSubscriptions();
Promise<undefined> unsubscribe(sequence<CookieStoreGetOptions> subscriptions);
};
</xmp>
<!-- ============================================================ -->
## The {{CookieStoreManager/subscribe()|subscribe()}} method ## {#CookieStoreManager-subscribe}
<!-- ============================================================ -->
<div class="domintro note">
: await |registration| . cookies . {{CookieStoreManager/subscribe()|subscribe}}(<var ignore>subscriptions</var>)
:: Subscribe to changes to cookies. Subscriptions can use the same options as {{CookieStore/get()}} and {{CookieStore/getAll()}}, with optional {{CookieStoreGetOptions/name}} and {{CookieStoreGetOptions/url}} properties.
Once subscribed, notifications are delivered as "`cookiechange`" events fired against the [=Service Worker=]'s global scope:
</div>
<div algorithm>
The <dfn method for=CookieStoreManager>subscribe(|subscriptions|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |registration| be [=/this=]'s [=CookieStoreManager/registration=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |subscription list| be |registration|'s associated [=cookie change subscription list=].
1. [=list/For each=] |entry| in |subscriptions|, run these steps:
1. Let |name| be |entry|["{{CookieStoreGetOptions/name}}"].
1. Let |url| be the result of [=basic URL parser|parsing=] |entry|["{{CookieStoreGetOptions/url}}"] with |settings|'s [=environment settings object/API base URL=].
1. If |url| does not start with |registration|'s [=service worker registration/scope url=],
then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. Let |subscription| be the [=cookie change subscription=] (|name|, |url|).
1. If |subscription list| does not already [=list/contain=] |subscription|, then [=list/append=] |subscription| to |subscription list|.
1. [=/Resolve=] |p| with undefined.
1. Return |p|.
</div>
<!-- ============================================================ -->
## The {{CookieStoreManager/getSubscriptions()}} method ## {#CookieStoreManager-getSubscriptions}
<!-- ============================================================ -->
<div class="domintro note">
: |subscriptions| = await |registration| . cookies . {{CookieStoreManager/getSubscriptions()}}
:: This method returns a promise which resolves to a list of the cookie change subscriptions made for this Service Worker registration.
</div>
<div algorithm>
The <dfn method for=CookieStoreManager>getSubscriptions()</dfn> method steps are:
1. Let |registration| be [=/this=]'s [=CookieStoreManager/registration=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |subscriptions| be |registration|'s associated [=cookie change subscription list=].
1. Let |result| be a new [=/list=].
1. [=list/For each=] |subscription| in |subscriptions|, run these steps:
1. [=list/Append=] «[ "name" → |subscription|'s [=cookie change subscription/name=], "url" → |subscription|'s [=cookie change subscription/url=]]» to |result|.
1. [=/Resolve=] |p| with |result|.
1. Return |p|.
</div>
<!-- ============================================================ -->
## The {{CookieStoreManager/unsubscribe()|unsubscribe()}} method ## {#CookieStoreManager-unsubscribe}
<!-- ============================================================ -->
<div class="domintro note">
: await |registration| . cookies . {{CookieStoreManager/unsubscribe()|unsubscribe}}(<var ignore>subscriptions</var>)
:: Calling this method will stop the registered service worker from receiving previously subscribed events. The |subscriptions| argument should list subscriptions in the same form passed to {{CookieStoreManager/subscribe()}} or returned from {{CookieStoreManager/getSubscriptions()}}.
</div>
<div algorithm>
The <dfn method for=CookieStoreManager>unsubscribe(|subscriptions|)</dfn> method steps are:
1. Let |settings| be [=/this=]'s [=/relevant settings object=].
1. Let |registration| be [=/this=]'s [=CookieStoreManager/registration=].
1. Let |p| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |subscription list| be |registration|'s associated [=cookie change subscription list=].
1. [=list/For each=] |entry| in |subscriptions|, run these steps:
1. Let |name| be |entry|["{{CookieStoreGetOptions/name}}"].
1. Let |url| be the result of [=basic URL parser|parsing=] |entry|["{{CookieStoreGetOptions/url}}"] with |settings|'s [=environment settings object/API base URL=].
1. If |url| does not start with |registration|'s [=service worker registration/scope url=],
then [=reject=] |p| with a {{TypeError}} and abort these steps.
1. Let |subscription| be the [=cookie change subscription=] (|name|, |url|).
1. [=list/Remove=] any [=list/item=] from |subscription list| equal to |subscription|.
1. [=/Resolve=] |p| with undefined.
1. Return |p|.
</div>
<!-- ============================================================ -->
## The {{ServiceWorkerRegistration}} interface ## {#ServiceWorkerRegistration}
<!-- ============================================================ -->
The {{ServiceWorkerRegistration}} interface is extended to give access to a {{CookieStoreManager}} via {{ServiceWorkerRegistration/cookies}} which provides the interface for subscribing to cookie changes.
<xmp class=idl>
[Exposed=(ServiceWorker,Window)]
partial interface ServiceWorkerRegistration {
[SameObject] readonly attribute CookieStoreManager cookies;
};
</xmp>
Each {{ServiceWorkerRegistration}} has an associated {{CookieStoreManager}} object.
The {{CookieStoreManager}}'s [=CookieStoreManager/registration=] is equal to the {{ServiceWorkerRegistration}}'s [=service worker registration=].
The <dfn attribute for=ServiceWorkerRegistration>cookies</dfn> getter steps are to return [=this=]'s associated {{CookieStoreManager}} object.
<div class=example>
Subscribing to cookie changes from a Service Worker script:
```js
self.registration.cookies.subscribe([{name:'session-id'}]);
```
</div>
<div class=example>
Subscribing to cookie changes from a script in a window context:
```js
navigator.serviceWorker.register('sw.js').then(registration => {
registration.cookies.subscribe([{name:'session-id'}]);
});
```
</div>
<!-- ============================================================ -->
# Event Interfaces # {#event-interfaces}
<!-- ============================================================ -->
<!-- ============================================================ -->
## The {{CookieChangeEvent}} interface ## {#CookieChangeEvent}
<!-- ============================================================ -->
A {{CookieChangeEvent}} is [=dispatched=] against {{CookieStore}} objects in {{Window}} contexts when any [=script-visible=] cookie changes have occurred.
<xmp class=idl>
[Exposed=Window,
SecureContext]
interface CookieChangeEvent : Event {
constructor(DOMString type, optional CookieChangeEventInit eventInitDict = {});
[SameObject] readonly attribute FrozenArray<CookieListItem> changed;
[SameObject] readonly attribute FrozenArray<CookieListItem> deleted;
};
dictionary CookieChangeEventInit : EventInit {
CookieList changed;
CookieList deleted;
};
</xmp>
The {{CookieChangeEvent/changed}} and {{CookieChangeEvent/deleted}} attributes must return the value they were initialized to.
<!-- ============================================================ -->
## The {{ExtendableCookieChangeEvent}} interface ## {#ExtendableCookieChangeEvent}
<!-- ============================================================ -->
An {{ExtendableCookieChangeEvent}} is [=dispatched=] against
{{ServiceWorkerGlobalScope}} objects when any [=script-visible=]
cookie changes have occurred which match the [=Service Worker=]'s
[=cookie change subscription list=].
Note: {{ExtendableEvent}} is used as the ancestor interface for all events in [=Service Workers=] so that the worker itself can be kept alive while the async operations are performed.
<xmp class=idl>
[Exposed=ServiceWorker]
interface ExtendableCookieChangeEvent : ExtendableEvent {
constructor(DOMString type, optional ExtendableCookieChangeEventInit eventInitDict = {});
[SameObject] readonly attribute FrozenArray<CookieListItem> changed;
[SameObject] readonly attribute FrozenArray<CookieListItem> deleted;
};
dictionary ExtendableCookieChangeEventInit : ExtendableEventInit {
CookieList changed;
CookieList deleted;
};
</xmp>
The {{ExtendableCookieChangeEvent/changed}} and {{ExtendableCookieChangeEvent/deleted}} attributes must return the value they were initialized to.
<!-- ============================================================ -->
# Global Interfaces # {#globals}
<!-- ============================================================ -->
A {{CookieStore}} is accessed by script using an attribute in the global
scope in a {{Window}} or {{ServiceWorkerGlobalScope}} context.
<!-- ============================================================ -->
## The {{Window}} interface ## {#Window}
<!-- ============================================================ -->