-
Notifications
You must be signed in to change notification settings - Fork 131
/
index.bs
2655 lines (2371 loc) · 119 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: WebUSB API
Status: w3c/CG-DRAFT
ED: https://wicg.github.io/webusb
Shortname: webusb
Level: 1
Editor: Reilly Grant 83788, Google LLC https://www.google.com, [email protected]
Editor: Ken Rockot 87080, Google LLC https://www.google.com, [email protected]
Editor: Ovidio Ruiz-Henríquez 106543, Google LLC https://www.google.com, [email protected]
Abstract: This document describes an API for securely providing access to Universal Serial Bus devices from web pages.
Group: wicg
Repository: https://github.com/WICG/webusb/
!Participate: <a href="https://www.w3.org/community/wicg/">Join the W3C Community Group</a>
!Participate: <a href="irc://irc.w3.org:6665/#webusb">IRC: #webusb on W3C's IRC</a> (Stay around for an answer, it make take a while)
!Participate: <a href="http://stackoverflow.com/questions/tagged/webusb">Ask questions on StackOverflow</a>
</pre>
<style>
table {
border-collapse: collapse;
border-left-style: hidden;
border-right-style: hidden;
text-align: left;
}
table caption {
font-weight: bold;
padding: 3px;
text-align: left;
}
table td, table th {
border: 1px solid black;
padding: 3px;
}
/* Put nice boxes around each algorithm. */
[data-algorithm]:not(.heading) {
padding: .5em;
border: thin solid #ddd; border-radius: .5em;
margin: .5em calc(-0.5em - 1px);
}
[data-algorithm]:not(.heading) > :first-child {
margin-top: 0;
}
[data-algorithm]:not(.heading) > :last-child {
margin-bottom: 0;
}
[data-algorithm] [data-algorithm] {
margin: 1em 0;
}
</style>
# Introduction # {#introduction}
<em>This section is non-normative</em>.
The Universal Serial Bus (USB) is the de-facto standard for wired peripherals.
Most USB devices implement one of roughly a dozen standard "device classes"
which specify a way for the device to advertise the features it supports and
commands and data formats for using those features. Standard device classes
include keyboard, mice, audio, video and storage devices. Operating systems
support such devices using the "class driver" provided by the OS vendor. There
is however a long tail of devices that do not fit into one of the standardized
device classes. These devices require hardware vendors to write native drivers
and SDKs in order for developers to take advantage of them and this native code
prevents these devices from being used by the web.
The WebUSB API provides a way to safely expose USB device services to the web.
It provides an API familiar to developers who have used existing native USB
libraries and exposes the device interfaces defined by existing specifications.
With this API hardware manufacturers will have the ability to build
cross-platform JavaScript SDKs for their devices. This will be good for the web
because, instead of waiting for a new kind of device to be popular enough for
browsers to provide a specific API, new and innovative hardware can be built
for the web from day one.
For more information about USB see [[#appendix-intro]].
# Motivating Applications # {#motivating-applications}
<em>This section is non-normative</em>.
## Educational Devices ## {#app-edu-devices}
The software delivery model of the web is a key enabler for educational
applications because they can be quickly loaded on any computer without
questions of platform compatibility or administrative credentials. Science
classes are incorporating computerized measurement and data logging into their
lessons. These tools require bundled software that may be difficult to install
on managed computers as every new native application adds overhead to an already
stressed IT department. Web-based hardware APIs allow support for these devices
to be built directly into existing online course materials, providing a
completely seamless experience.
Students learning to code with one of the many microcontroller development kits
can take advantage of online developer tools to write and upload their code.
These tools already exist however they require a native component to interface
between the browser and the hardware. These native extensions add a barrier to
entry and may expose the user to security vulnerabilities in a way that that
code running in the sandboxed web environment does not.
## Web Drivers ## {#app-drivers}
The composablity of the web allows a new ecosystem of hardware support to be
built entirely from web technology. Taking 3D printers an example, imagine that
a site hosting 3D object designs wants to integrate printing directly into their
page. The web supports 2D printing but there is no API for the 3D variety. If
manufacturers host embeddable pages that use the WebUSB API to send data to
their printers, sites can use these pages to integrate support for the hardware
in the same way that features such as embedded maps are added to many existing
sites.
## Devices Updates and Diagnostics ## {#app-updates-and-diagnostics}
While wireless protocols such as Bluetooth are often the more convenient choice
for consumer devices USB ports continue to proliferate because they are an easy
solution for power delivery and can serve as the connection of last resort when
the device isn't working. By integrating update and diagnostic tools into their
support site a hardware manufacturer can provide tools for customers on any
platform and collect better diagnostic data when a customer reaches out for
support through their website. The <a>landing page</a> provides a way for the
device manufacturer to direct the user to the right part of their website for
help with their device.
# Security and Privacy Considerations # {#security-and-privacy}
<em>This section is non-normative</em>.
The WebUSB API is a powerful feature and has the possibility to expose users to
a number of new privacy and security risks. These risks can be broadly divided
into three categories that will be described in the sections below.
## Abusing Access to a Device ## {#abusing-a-device}
Peripheral devices can serve a number of purposes. They may store data, as a
flash drive does. They may collect information about the outside world as a
camera or microphone does. They may manipulate objects in the outside world as
a printer does. Each of the examples above have high-level APIs in the web
platform with security features that aim to prevent their abuse by a malicious
website. Storing data to or from an external drive requires the user to select
the file manually. Turning on the microphone or camera requires permission from
the user and may activate an indicator to let the user know data collection is
in progress. Printing a document requires explicit action as well. This API
provides a generic mechanism to connect to devices not covered by these
existing high-level APIs and so it requires a similarly generic mechanism for
preventing a malicious page from abusing a device.
The first of these protections is the {{USB/requestDevice()}} function. The UA
may display a permission prompt when this function is called. Even for a
non-malicious page this action also preserves user privacy by preventing a site
from connecting to a device before the user is aware that such a connection is
possible. The UA may also display an indicator when a device connection is
active.
Secondly, this specification requires that only secure contexts as described
in [[powerful-features]] can access USB devices. This ensures both the
authenticity of the code executing on behalf of the origin and that data read
from the device may not be intercepted in transit.
Lastly, since USB devices are unable to distinguish requests from multiple
sources, operating systems only allow a USB interface to have a single owning
user-space or kernel-space driver. The UA acts as a user-space driver, therefore
allowing only a single execution context to claim a USB interface at a time. The
{{USBDevice/claimInterface()}} function will fail if multiple execution contexts
attempt to claim an interface.
## Attacking a Device ## {#attacking-a-device}
Historically, unless they were created for high security applications, USB
devices have been designed to trust the host they are connected to and so the
host is the traditional guardian of access to the capabilities a device
provides. In the development of this specification two possibilities were
considered. First, the UA could notify the device of the origin from which a
request originated. This would be similar to the <code>Referrer</code> header
included in HTTP request. The difficulty of this approach is that it places
the burden of access control on the device. Devices often have very limited
processing and storage capabilities and so an effort was made to limit the
amount of work necessary on the part of the device.
The approach initially chosen during drafting of this specification was to
instead require that the UA control access though a mechanism similiar to
[[CORS]]. The device could provide the UA with a set of static data structures
defining a set of origins that are allowed to connect to it. To support a
transition period for existing devices it was proposed that information about
allowed origins could also be provided out of band through some kind of public
registry.
A downside of this approach was two-fold. First, it required vendors to build
new devices with WebUSB in mind or rely on a public registry system that proved
difficult to specify. Product development cycles are long and as only an
Editor's Draft this specification does not have the clout necessary to influence
product planning. Second, it provided no mechanism for third-party developers to
use this API with a device. This limited innovation and the number of developers
who could take advantage of this new capability.
After considering these options the authors have decided that the permission
prompt encouraged by the {{USB/requestDevice()}} method and the integration with
[[#permissions-policy]] provide adequate protection against unwanted access to a
device.
## Attacking the Host ## {#attacking-the-host}
If a device is compromised then in addition to abusing its own capabilities
the attacker may also use it to in turn attack the host to which it is connected
or if the exploit is persistent any host it is connected to later. The methods
above are the ways in which this specification attempts to mitigate this attack
vector for once the device is under the control of an attacker (for example, by
uploading a malicious firmware image) there is nothing that can be done by the
UA to prevent further damage.
This specification recommends device manufacturers practice defense in depth by
designing their devices to only accept signed firmware updates and/or require
physical access to the device in order to apply some configuration changes.
# WebUSB Descriptors and Requests # {#webusb-descriptors-and-requests}
This specification defines descriptors and commands the UA MAY use to gather
information about the device specific to implementing this API.
<h3 dfn>WebUSB Platform Capability Descriptor</h3>
A device announces support for the WebUSB command set by including the
following <a>Platform Descriptor</a> in its <a>Binary Object
Store</a>:
<table>
<tr>
<th>Offset</th>
<th>Field</th>
<th>Size</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td>0</td>
<td>bLength</td>
<td>1</td>
<td>Number</td>
<td>Size of this descriptor. Must be set to 24.</td>
</tr>
<tr>
<td>1</td>
<td>bDescriptorType</td>
<td>1</td>
<td>Constant</td>
<td>DEVICE CAPABILITY descriptor type ([[!USB31]] Table 9-6).</td>
</tr>
<tr>
<td>2</td>
<td>bDevCapabilityType</td>
<td>1</td>
<td>Constant</td>
<td>PLATFORM capability type ([[!USB31]] Table 9-14).</td>
</tr>
<tr>
<td>3</td>
<td>bReserved</td>
<td>1</td>
<td>Number</td>
<td>This field is reserved and shall be set to zero.</td>
</tr>
<tr>
<td>4</td>
<td>PlatformCapabilityUUID</td>
<td>16</td>
<td>UUID</td>
<td>Must be set to {3408b638-09a9-47a0-8bfd-a0768815b665}.</td>
</tr>
<tr>
<td>20</td>
<td>bcdVersion</td>
<td>2</td>
<td>BCD</td>
<td>Protocol version supported. Must be set to 0x0100.</td>
</tr>
<tr>
<td>22</td>
<td>bVendorCode</td>
<td>1</td>
<td>Number</td>
<td>bRequest value used for issuing WebUSB requests.</td>
</tr>
<tr>
<td>23</td>
<td>iLandingPage</td>
<td>1</td>
<td>Number</td>
<td>URL descriptor index of the device's <a>landing page</a>.</td>
</tr>
</table>
The <code>iLandingPage</code> field, when non-zero, indicates a
<dfn>landing page</dfn> which the device manufacturer would like the user to
visit in order to control their device. The UA MAY suggest the user navigate
to this URL when the device is connected.
Note: The USB is a little-endian bus and so according to [[RFC4122]] the UUID
above MUST be sent over the wire as the byte sequence <code>{0x38, 0xB6, 0x08,
0x34, 0xA9, 0x09, 0xA0, 0x47, 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6,
0x65}</code>.
## WebUSB Device Requests ## {#device-requests}
All <a>control transfers</a> defined by this specification are considered to
be vendor-specific requests. The <code>bVendorCode</code> value found
in the <a>WebUSB Platform Capability Descriptor</a> provides the UA
with the <code>bRequest</code> the device expects the host to use when
issuing <a>control transfers</a> these requests. The request type is then
specified in the <code>wIndex</code> field.
<table>
<caption>WebUSB Request Codes</caption>
<tr>
<th>Constant</th>
<th>Value</th>
</tr>
<tr>
<td>(Reserved)</td>
<td>1</td>
</tr>
<tr>
<td>GET_URL</td>
<td>2</td>
</tr>
</table>
<h4 dfn>Get URL</h4>
This request fetches the URL descriptor with the given index.
The device MUST respond with the <a>URL Descriptor</a> at the given
index or stall the transfer if the index is invalid.
<table>
<tr>
<th>bmRequestType</td>
<th>bRequest</th>
<th>wValue</th>
<th>wIndex</th>
<th>wLength</th>
<th>Data</th>
</tr>
<tr>
<td>11000000B</td>
<td><code>bVendorCode</code></td>
<td>Descriptor Index</td>
<td>GET_URL</td>
<td>Descriptor Length</td>
<td>Descriptor</td>
</tr>
</table>
## WebUSB Descriptors ## {#webusb-descriptors}
These descriptor types are returned by requests defined in this
specification.
<table>
<caption>WebUSB Descriptor Types</caption>
<tr>
<th>Constant</th>
<th>Value</th>
</tr>
<tr>
<td>(Reserved)</td>
<td>0-2</td>
</tr>
<tr>
<td>WEBUSB_URL</td>
<td>3</td>
</tr>
</table>
<h4 dfn>URL Descriptor</h4>
This descriptor contains a single URL and is returned by the <a>Get URL</a>
request.
<table>
<tr>
<th>Offset</th>
<th>Field</th>
<th>Size</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td>0</td>
<td>bLength</td>
<td>1</td>
<td>Number</td>
<td>Size of this descriptor.</td>
</tr>
<tr>
<td>1</td>
<td>bDescriptorType</td>
<td>1</td>
<td>Constant</td>
<td>WEBUSB_URL.</td>
</tr>
<tr>
<td>2</td>
<td>bScheme</td>
<td>1</td>
<td>Number</td>
<td>URL scheme prefix.</td>
</tr>
<tr>
<td>3</td>
<td>URL</td>
<td>Variable</td>
<td>String</td>
<td>UTF-8 encoded URL (excluding the scheme prefix).</td>
</tr>
</table>
The <code>bScheme</code> field MUST be one of these values:
<table>
<caption>URL Prefixes</caption>
<tr>
<th>Value</th>
<th>Prefix</th>
</tr>
<tr>
<td>0</td>
<td>"http://"</td>
</tr>
<tr>
<td>1</td>
<td>"https://"</td>
</tr>
<tr>
<td>255</td>
<td>""</td>
</tr>
</table>
The special value <code>255</code> indicates that the entire URL, including
scheme, is encoded in the <code>URL</code> field.
# Device Enumeration # {#enumeration}
<xmp class="idl">
dictionary USBDeviceFilter {
unsigned short vendorId;
unsigned short productId;
octet classCode;
octet subclassCode;
octet protocolCode;
DOMString serialNumber;
};
dictionary USBDeviceRequestOptions {
required sequence<USBDeviceFilter> filters;
sequence<USBDeviceFilter> exclusionFilters = [];
};
[Exposed=(Worker,Window), SecureContext]
interface USB : EventTarget {
attribute EventHandler onconnect;
attribute EventHandler ondisconnect;
Promise<sequence<USBDevice>> getDevices();
[Exposed=Window] Promise<USBDevice> requestDevice(USBDeviceRequestOptions options);
};
[Exposed=Window, SecureContext]
partial interface Navigator {
[SameObject] readonly attribute USB usb;
};
[Exposed=Worker, SecureContext]
partial interface WorkerNavigator {
[SameObject] readonly attribute USB usb;
};
</xmp>
<div class="example">
In this example, we retrieve some devices to include in a UI. When the page is
first loaded, it should check if it already has permission to access any
connected devices by calling {{USB/getDevices()}},
<pre highlight="js">
document.addEventListener('DOMContentLoaded', async () => {
let devices = await navigator.usb.getDevices();
devices.forEach(device => {
// Add |device| to the UI.
});
});
</pre>
After the page is loaded the user may <a>connect</a> or <a>disconnect</a> a
device from their system so script should also register for these events in
order to keep the interface up-to-date,
<pre highlight="js">
navigator.usb.addEventListener('connect', event => {
// Add |event.device| to the UI.
});
navigator.usb.addEventListener('disconnect', event => {
// Remove |event.device| from the UI.
});
</pre>
If this is the first time the user has visited the page then it won't have
permission to access any devices so the page must first call
{{USB/requestDevice()}} while the [=relevant global object=] has a
<a>transient activation</a>. In this case the page supports devices from vendor
<code>0xABCD</code> that carry the vendor-specific subclass <code>0x01</code>,
<pre highlight="js">
let button = document.getElementById('request-device');
button.addEventListener('click', async () => {
let device;
try {
device = await navigator.usb.requestDevice({ filters: [{
vendorId: 0xABCD,
classCode: 0xFF, // vendor-specific
protocolCode: 0x01
}]});
} catch (err) {
// No device was selected.
}
if (device !== undefined) {
// Add |device| to the UI.
}
});
</pre>
</div>
A USB device |device| <dfn data-lt="match a device filter">matches a device
filter</dfn> |filter| if the following steps return <code>match</code>:
1. Let |deviceDesc| be |device|'s <a>device descriptor</a>.
1. If <code>|filter|.{{USBDeviceFilter/vendorId}}</code> is present and
<code>|deviceDesc|.idVendor</code> does not equal
<code>|filter|.{{USBDeviceFilter/vendorId}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/productId}}</code> is present and
<code>|deviceDesc|.idProduct</code> does not equal
<code>|filter|.{{USBDeviceFilter/productId}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/serialNumber}}</code> is present then,
let |serialNumber| be the <a>string descriptor</a> with index
<code>|deviceDesc|.iSerialNumber</code>. If |device| returns an error when
requesting |serialNumber| or |serialNumber| is not equal to
<code>|filter|.{{USBDeviceFilter/serialNumber}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/classCode}}</code> is present and,
for any of |device|'s interface's |interface|, |interface| <a>matches
the interface filter</a> |filter|, return <code>match</code>.
1. If <code>|filter|.{{USBDeviceFilter/classCode}}</code> is present and
<code>|deviceDesc|.bDeviceClass</code> is not equal to
<code>|filter|.{{USBDeviceFilter/classCode}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/subclassCode}}</code> is present and
<code>|deviceDesc|.bDeviceSubClass</code> is not equal to
<code>|filter|.{{USBDeviceFilter/subclassCode}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/protocolCode}}</code> is present and
<code>|deviceDesc|.bDeviceProtocol</code> is not equal to
<code>|filter|.{{USBDeviceFilter/protocolCode}}</code>, return
<code>mismatch</code>.
1. Return <code>match</code>.
Note: The steps above treat the <code>bDeviceClass</code>,
<code>bDeviceSubClass</code> and <code>bDeviceProtocol</code> fields of the
<a>device descriptor</a> as though they were part of an <a>interface
descriptor</a> which is also compared against the provided filter.
A USB interface |interface| <dfn data-lt="matches the interface filter">matches
an interface filter</dfn> |filter| if the following steps return
<code>match</code>:
1. Let |desc| be |interface|'s <a>interface descriptor</a>.
1. If <code>|filter|.{{USBDeviceFilter/classCode}}</code> is present and
<code>|desc|.bInterfaceClass</code> is not equal to
<code>|filter|.{{USBDeviceFilter/classCode}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/subclassCode}}</code> is present and
<code>|desc|.bInterfaceSubClass</code> is not equal to
<code>|filter|.{{USBDeviceFilter/subclassCode}}</code>, return
<code>mismatch</code>.
1. If <code>|filter|.{{USBDeviceFilter/protocolCode}}</code> is present and
<code>|desc|.bInterfaceProtocol</code> is not equal to
<code>|filter|.{{USBDeviceFilter/protocolCode}}</code>, return
<code>mismatch</code>.
1. Return <code>match</code>.
A {{USBDeviceFilter}} |filter|
<dfn data-lt="is not a valid filter">is valid</dfn> if the following steps
return <code>valid</code>:
1. If <code>|filter|.{{USBDeviceFilter/productId}}</code> is present and
<code>|filter|.{{USBDeviceFilter/vendorId}}</code> is not present,
return <code>invalid</code>.
1. If <code>|filter|.{{USBDeviceFilter/subclassCode}}</code> is present and
<code>|filter|.{{USBDeviceFilter/classCode}}</code> is not present,
return <code>invalid</code>.
1. If <code>|filter|.{{USBDeviceFilter/protocolCode}}</code> is present and
<code>|filter|.{{USBDeviceFilter/subclassCode}}</code> is not present,
return <code>invalid</code>.
1. Return <code>valid</code>.
The UA MUST be able to <dfn>enumerate all devices attached to the system</dfn>.
It is, however NOT required to perform this work each time an algorithm
requests an enumeration. The UA MAY cache the result of the first enumeration
it performs and then begin monitoring for device connection and disconnection
events, adding connected devices to its cached enumeration and removing
disconnected devices. This mode of operation is preferred as it reduces the
number of operating system calls made and amount of bus traffic generated by
the {{USB/getDevices()}} and {{USB/requestDevice()}} methods.
The {{USB/onconnect}} attribute is an Event handler IDL attribute for the
<a>connect</a> event type.
The {{USB/ondisconnect}} attribute is an Event handler IDL attribute for the
<a>disconnect</a> event type.
The {{USB/getDevices()}} method, when invoked, MUST return a new {{Promise}} and
run the following steps <a>in parallel</a>:
1. Let |document| be <a>this</a>'s [=relevant global object=]'s
[=associated Document=], or <code>null</code> if there is no associated
{{Document}}.
1. Let |storage| be:
1. The {{USBPermissionStorage}} object in the script execution environment
of the associated [=service worker client=], if [=this=]'s [=relevant
global object=] is a {{ServiceWorkerGlobalScope}}.
1. Otherwise, the {{USBPermissionStorage}} object in the current script
execution environment.
1. <a>Enumerate all devices attached to the system</a>. Let this result be
|enumerationResult|.
2. Let |devices| be a new empty {{Array}}.
3. For each |device| in |enumerationResult|:
1. If |device| is [=blocklisted=] for |document|, [=iteration/continue=].
1. If this is the first call to this method, <a>check permissions for
|device|</a> with |storage|.
2. Search for an element |allowedDevice| in
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code> where
|device| is in |allowedDevice|@{{[[devices]]}}. If no such element
exists, continue to the next |device|.
3. Add the {{USBDevice}} object representing |device| to |devices|.
4. <a>Resolve</a> |promise| with |devices|.
The {{USB/requestDevice()}} method, when invoked, MUST run the following steps:
1. <a>Request permission to use</a> the following descriptor,
<pre highlight="js">
{
name: "usb"
filters: <var>options</var>.<a idl for="USBDeviceRequestOptions">filters</a>
exclusionFilters: <var>options</var>.<a idl for="USBDeviceRequestOptions">exclusionFilters</a>
}
</pre>
Let |permissionResult| be the resulting {{Promise}}.
2. <a>Upon fulfillment</a> of |permissionResult| with |result| run the
following steps:
1. If <code>|result|.{{USBPermissionResult/devices}}</code> is empty,
throw a {{NotFoundError}} and abort these steps.
2. Return <code>|result|.{{USBPermissionResult/devices}}[0]</code>.
To <dfn>request the "usb" permission</dfn>, given a {{Document}} |document|, a
{{USBPermissionStorage}} |storage|, a {{USBPermissionDescriptor}} |options| and
a {{USBPermissionResult}} |status|, the UA MUST return a new {{Promise}}
|promise| and run the following steps <a>in parallel</a>:
1. For each |filter| in
<code>|options|.{{USBPermissionDescriptor/filters}}</code> if |filter|
<a>is not a valid filter</a> <a>reject</a> |promise| with a {{TypeError}}
and abort these steps.
2. For each |exclusionFilter| in
<code>|options|.{{USBPermissionDescriptor/exclusionFilters}}</code> if
|exclusionFilter| <a>is not a valid filter</a> <a>reject</a> |promise|
with a {{TypeError}} and abort these steps.
3. Check that the algorithm was triggered while the [=relevant global object=]
had a <a>transient activation</a>. Otherwise, <a>reject</a> |promise| with
a {{SecurityError}} and abort these steps.
4. Set <code>|status|.{{PermissionStatus/state}}</code> to <code>"ask"</code>.
5. <a>Enumerate all devices attached to the system</a>. Let this result be
|enumerationResult|.
1. Remove devices from |enumerationResult| if they are [=blocklisted=] for
|document|.
6. Remove devices from |enumerationResult| if they do not <a>match a device
filter</a> in <code>|options|.{{USBPermissionDescriptor/filters}}</code>.
7. Remove devices from |enumerationResult| if they <a>match a device filter</a>
in <code>|options|.{{USBPermissionDescriptor/exclusionFilters}}</code>.
8. Display a prompt to the user requesting they select a device from
|enumerationResult|. The UA SHOULD show a human-readable name for each
device.
9. Wait for the user to have selected a |device| or cancelled the
prompt.
10. If the user cancels the prompt, set
<code>|status|.{{USBPermissionResult/devices}}</code> to an empty
{{FrozenArray}}, <a>resolve</a> |promise| with <code>undefined</code>,
and abort these steps.
11. <a>Add |device| to |storage|</a>.
12. Let |deviceObj| be the {{USBDevice}} object representing |device|.
13. Set <code>|status|.{{USBPermissionResult/devices}}</code> to a new
{{FrozenArray}} containing |deviceObj| as its only element.
14. <a>Resolve</a> |promise| with <code>undefined</code>.
To <dfn data-lt="add device to storage">add an allowed <a>USB device</a></dfn>
|device| to {{USBPermissionStorage}} |storage|, the UA MUST run the following
steps:
1. Search for an element |allowedDevice| in
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code> where
|device| is in |allowedDevice|@{{[[devices]]}}. If one is found, abort
these steps.
2. Let |vendorId| and |productId| be |device|'s <a>vendor ID</a> and
<a>product ID</a>.
3. Let |serialNumber| be |device|'s <a>serial number</a> if it has one,
otherwise <code>undefined</code>.
6. Append <code>{ vendorId: |vendorId|, productId: |productId|, serialNumber: |serialNumber| }</code>,
with a {{[[devices]]}} internal slot containing a single entry |device| to
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code>.
To <dfn data-lt="check permissions for device">check permissions for a new
<a>USB device</a></dfn> |device|, given a {{USBPermissionStorage}} |storage|,
the UA MUST run the following steps:
1. Let |vendorId| and |productId| be |device|'s <a>vendor ID</a> and
<a>product ID</a>.
2. Let |serialNumber| be |device|'s if it has one, otherwise
<code>undefined</code>.
3. Search for an element |allowedDevice| in
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code> where:
* <code>|allowedDevice|.{{AllowedUSBDevice/vendorId}}</code> equals
|vendorId|.
* <code>|allowedDevice|.{{AllowedUSBDevice/productId}}</code> equals
|productId|.
* <code>|allowedDevice|.{{AllowedUSBDevice/serialNumber}}</code> equals
|serialNumber|.
4. If no such element exists, return <code>null</code>.
5. Add |device| to |allowedDevice|@{{[[devices]]}}.
6. Return |allowedDevice|.
To <dfn data-lt="remove device from storage">remove an allowed <a>USB
device</a></dfn> |device|, given a {{USBPermissionStorage}} |storage|,
the UA MUST run the following steps:
1. Search for an element |allowedDevice| in
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code> where
|device| is in |allowedDevice|@{{[[devices]]}}, if no such element exists,
abort these steps.
2. Remove |allowedDevice| from
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code>.
## Events ## {#events}
<xmp class="idl">
dictionary USBConnectionEventInit : EventInit {
required USBDevice device;
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBConnectionEvent : Event {
constructor(DOMString type, USBConnectionEventInit eventInitDict);
[SameObject] readonly attribute USBDevice device;
};
</xmp>
Note: Workers may register event listeners for <a>connect</a> and
<a>disconnect</a> events but the event listener will not be invoked unless the
worker is active.
When the UA detects a new <a>USB device</a> |device| connected to the host it
MUST perform the following steps for each script execution environment:
1. Let |storage| be the {{USBPermissionStorage}} object in the current
script execution environment.
2. <a>Check permissions for |device|</a> with |storage| and let
|allowedDevice| be the result.
3. If |allowedDevice| is <code>null</code>, abort these steps.
4. Let |deviceObj| be the {{USBDevice}} object representing |device|.
5. [=Fire an event=] named <dfn>connect</dfn> on |device|'s [=relevant global
object=]'s {{Navigator}} object's {{Navigator/usb}}, using
{{USBConnectionEvent}}, with the <code>device</code> attribute set to
|deviceObj|.
When the UA detects a <a>USB device</a> |device| has been disconnected from the
host it MUST perform the following steps for each script execution environment:
1. Let |storage| be the {{USBPermissionStorage}} object in the current
script execution environment.
2. Search for an element |allowedDevice| in
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code> where
|device| is in |allowedDevice|@{{[[devices]]}}, if no such element exists,
abort these steps.
3. Remove |device| from |allowedDevice|@{{[[devices]]}}.
4. If <code>|allowedDevice|.{{AllowedUSBDevice/serialNumber}}</code> is
<code>undefined</code> and |allowedDevice|@{{[[devices]]}} is empty remove
|allowedDevice| from
<code>|storage|.{{USBPermissionStorage/allowedDevices}}</code>.
5. Let |device| be the {{USBDevice}} object representing |device|.
6. [=Fire an event=] named <dfn>disconnect</dfn> on |device|'s [=relevant
global object=]'s {{Navigator}} object's {{Navigator/usb}}, using
{{USBConnectionEvent}}, with the <code>device</code> attribute set to
|device|.
# Device Usage # {#device-usage}
<div class="example">
In this example we imagine a data logging device supporting up to 8 16-bit data
channels. It has a single configuration (<code>bConfigurationValue 1</code>)
with a single interface (<code>bInterfaceNumber 1</code>) with a single
bulk endpoint (<code>bEndpointAddress 0x81</code> which means that it is
endpoint 1 and an IN endpoint). When data is sampled it is available on this
endpoint. The maximum packet size on this endpoint is 16 bytes to support all 8
channels being activated at the same time. To save bus bandwidth, however, any
combination of channels can be activated and deactivated. The packet will only
be the length necessary to transmit the data collected.
To get started we open the device, select the first configuration (it only has
one but the operating system may not have already done this during enumeration)
and claim the data logging interface,
<pre highlight="js">
await device.<a idl for="USBDevice" data-lt="open()">open</a>();
if (device.<a idl for="USBDevice">configuration</a> === null)
await device.<a idl for="USBDevice" data-lt="selectConfiguration()">selectConfiguration</a>(1);
await device.<a idl for="USBDevice" data-lt="claimInterface()">claimInterface</a>(1);
</pre>
For this particular application we care about reading from channels 1, 2 and 5
so we issue a <a>control transfer</a> to activate these channels,
<pre highlight="js">
await device.<a idl for="USBDevice" data-lt="controlTransferOut()">controlTransferOut</a>({
<a idl for="USBControlTransferParameters">requestType</a>: '<a idl for="USBRequestType">vendor</a>',
<a idl for="USBControlTransferParameters">recipient</a>: '<a idl for="USBRecipient">interface</a>',
<a idl for="USBControlTransferParameters">request</a>: 0x01, // vendor-specific request: enable channels
<a idl for="USBControlTransferParameters">value</a>: 0x0013, // 0b00010011 (channels 1, 2 and 5)
<a idl for="USBControlTransferParameters">index</a>: 0x0001 // Interface 1 is the recipient
});
</pre>
The application may now start polling the device for data. As we only expect
data from 3 channels we request a 6 byte buffer. As long as we receive a
complete buffer the captured values (transmitted in big endian) are printed to
the console log. If the device has encountered an error and signals this by
stalling the endpoint then the error is cleared before continuing,
<pre highlight="js">
while (true) {
let result = await device.<a idl for="USBDevice" data-lt="transferIn()">transferIn</a>(1, 6);
if (result.<a idl for="USBInTransferResult">data</a> && result.data.byteLength === 6) {
console.log('Channel 1: ' + result.data.getUint16(0));
console.log('Channel 2: ' + result.data.getUint16(2));
console.log('Channel 5: ' + result.data.getUint16(4));
}
if (result.<a idl for="USBInTransferResult">status</a> === 'stall') {
console.warn('Endpoint stalled. Clearing.');
await device.<a idl for="USBDevice" data-lt="clearHalt()">clearHalt</a>(1);
}
}
</pre>
</div>
## The USBDevice Interface ## {#usbdevice-interface}
<xmp class="idl">
enum USBTransferStatus {
"ok",
"stall",
"babble"
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBInTransferResult {
constructor(USBTransferStatus status, optional DataView? data);
readonly attribute DataView? data;
readonly attribute USBTransferStatus status;
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBOutTransferResult {
constructor(USBTransferStatus status, optional unsigned long bytesWritten = 0);
readonly attribute unsigned long bytesWritten;
readonly attribute USBTransferStatus status;
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBIsochronousInTransferPacket {
constructor(USBTransferStatus status, optional DataView? data);
readonly attribute DataView? data;
readonly attribute USBTransferStatus status;
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBIsochronousInTransferResult {
constructor(sequence<USBIsochronousInTransferPacket> packets, optional DataView? data);
readonly attribute DataView? data;
readonly attribute FrozenArray<USBIsochronousInTransferPacket> packets;
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBIsochronousOutTransferPacket {
constructor(USBTransferStatus status, optional unsigned long bytesWritten = 0);
readonly attribute unsigned long bytesWritten;
readonly attribute USBTransferStatus status;
};
[
Exposed=(Worker,Window),
SecureContext
]
interface USBIsochronousOutTransferResult {
constructor(sequence<USBIsochronousOutTransferPacket> packets);
readonly attribute FrozenArray<USBIsochronousOutTransferPacket> packets;
};
[Exposed=(Worker,Window), SecureContext]
interface USBDevice {
readonly attribute octet usbVersionMajor;
readonly attribute octet usbVersionMinor;
readonly attribute octet usbVersionSubminor;
readonly attribute octet deviceClass;
readonly attribute octet deviceSubclass;
readonly attribute octet deviceProtocol;
readonly attribute unsigned short vendorId;
readonly attribute unsigned short productId;
readonly attribute octet deviceVersionMajor;
readonly attribute octet deviceVersionMinor;
readonly attribute octet deviceVersionSubminor;
readonly attribute DOMString? manufacturerName;
readonly attribute DOMString? productName;
readonly attribute DOMString? serialNumber;
readonly attribute USBConfiguration? configuration;
readonly attribute FrozenArray<USBConfiguration> configurations;
readonly attribute boolean opened;
Promise<undefined> open();
Promise<undefined> close();
Promise<undefined> forget();
Promise<undefined> selectConfiguration(octet configurationValue);
Promise<undefined> claimInterface(octet interfaceNumber);
Promise<undefined> releaseInterface(octet interfaceNumber);
Promise<undefined> selectAlternateInterface(octet interfaceNumber, octet alternateSetting);
Promise<USBInTransferResult> controlTransferIn(USBControlTransferParameters setup, unsigned short length);
Promise<USBOutTransferResult> controlTransferOut(USBControlTransferParameters setup, optional BufferSource data);
Promise<undefined> clearHalt(USBDirection direction, octet endpointNumber);
Promise<USBInTransferResult> transferIn(octet endpointNumber, unsigned long length);
Promise<USBOutTransferResult> transferOut(octet endpointNumber, BufferSource data);
Promise<USBIsochronousInTransferResult> isochronousTransferIn(octet endpointNumber, sequence<unsigned long> packetLengths);
Promise<USBIsochronousOutTransferResult> isochronousTransferOut(octet endpointNumber, BufferSource data, sequence<unsigned long> packetLengths);
Promise<undefined> reset();
};
</xmp>
Instances of {{USBDevice}} are created with the <a>internal
slots</a> described in the following table:
<table class="data" dfn-for="USBDevice" dfn-type="attribute">
<tr>
<th><a>Internal Slot</a></th>
<th>Initial Value</th>
<th>Description (non-normative)</th>
</tr>
<tr>
<td><dfn>\[[configurations]]</dfn></td>
<td>An empty <a>sequence</a> of {{USBConfiguration}}</code></td>
<td>
All configurations supported by this device.
</td>
</tr>
<tr>
<td><dfn>\[[configurationValue]]</dfn></td>
<td><always set in prose></td>
<td>
The current configuration value of the device.
</td>
</tr>
<tr>
<td><dfn>\[[selectedAlternateSetting]]</dfn></td>
<td>An <a>empty</a> list of <a>integer</a></td>
<td>
The current alternate setting for each interface on the current configuration.
</td>