Ambient Light Sensor

Editor’s Draft , 13 December 2022

More details about this document
This version:
https://w3c.github.io/ambient-light/
Latest published version:
https://www.w3.org/TR/ambient-light/
Version History:
https://github.com/w3c/ambient-light/commits/main/index.bs
Feedback:
public-device-apis@w3.org with subject line “ [ambient-light] … message topic … ” ( archives )
GitHub
Test Suite:
https://github.com/web-platform-tests/wpt/tree/master/ambient-light
Editors:
Anssi Kostiainen ( Intel Corporation )
Rijubrata Bhaumik ( Intel Corporation )
Former Editors:
Tobie Langel ( Codespeaks, formerly on behalf of Intel Corporation )
Doug Turner ( Mozilla Corporation )
Issue Tracking:
Level 2 Issues
Not Ready For Implementation

This spec is not yet ready for implementation. It exists in this repository to record the ideas and promote discussion.

Before attempting to implement this spec, please contact the editors.


Abstract

This specification defines a concrete sensor interface to monitor the ambient light level or illuminance of the device’s environment.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

If you wish to make comments regarding this document, please send them to public-device-apis@w3.org ( subscribe , archives ). When sending e-mail, please put the text “ambient-light” in the subject, preferably like this: “[ambient-light] …summary of comment… ”. All comments are welcome.

This document was produced by the Devices and Sensors Working Group .

This document was produced by a group operating under the W3C Patent Policy . W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy .

This document is governed by the 2 November 2021 W3C Process Document .

The Devices and Sensors Working Group is pursuing modern security and privacy reviews for this specification in consideration of the amount of change in both this specification and in privacy and security review practices since the horizontal reviews took place on 3 October 2017 . Similarly, the group is pursuing an update to the Technical Architecture Group review for this specification to account for the latest architectural review practices.

1. Introduction

The Ambient Light Sensor extends the Generic Sensor API [GENERIC-SENSOR] to provide information about ambient light levels, as detected by the device’s main light detector, in terms of lux units.

1.1. Scope

This document specifies an API designed for use cases which require fine grained illuminance data, with low latency, and possibly sampled at high frequencies.

Common use cases relying on a small set of illuminance values, such as styling webpages according to contrast level or preferred color scheme that may be influenced by a device’s measured ambient light level are best served by the the prefers-contrast and prefers-color-scheme CSS media features [MEDIAQUERIES-5] as well as the accompanying matchMedia API [CSSOM-VIEW-1] and are out of scope of this API.

Note: The [MEDIAQUERIES-5] specification used to contain a light-level media feature that was more directly tied to ambient light readings. It has since been dropped from the specification in favor of the higher-level prefers-color-scheme and prefers-contrast media features.

2. Examples

In this simple example, ambient light sensor an AmbientLightSensor instance is created with default configuration. Whenever a new reading is available, it is printed to the console. sensor sensor sensor
navigator.mediaDevices.getUserMedia({video: true}).then(() => {
  const sensor = new AmbientLightSensor();
  sensor.onreading = () => console.log(sensor.illuminance);
  sensor.onerror = event => console.log(event.error.name, event.error.message);
  sensor.start();
});
In this example, the exposure value (EV) at ISO 100 is calculated from the ambient light sensor readings . Initially, we check that the user agent has permissions to access ambient light sensor readings . Then, the The illuminance value is converted to the closest exposure value. console
navigator.mediaDevices.getUserMedia({ video: true }).then(() => {
    const als = new AmbientLightSensor({frequency: 20});
    als.addEventListener('activate', () => console.log('Ready to measure EV.'));
    als.addEventListener('error', event => console.log(`Error: ${event.error.name}`));
    als.addEventListener('reading', () => {
        // Defaut ISO value.
        const ISO = 100;
        // Incident-light calibration constant.
        const C = 250;
        let EV = Math.round(Math.log2((als.illuminance * ISO) / C));
        console.log(`Exposure Value (EV) is: ${EV}`);
    });
    als.start();
});
This example demonstrates how ambient light sensor readings can be mapped to recommended workplace light levels. als console als

3. Security and Privacy Considerations

There is a tracking vector here. Ambient Light Sensor provides information about lighting conditions near the device environment. Potential privacy risks include:

Works such as [ALSPRIVACYANALYSIS] , [PINSKIMMINGVIASENSOR] , [STEALINGSENSITIVEDATA] , and [VIDEORECOGNITIONAMBIENTLIGHT] delve further into these issues.

To mitigate these threats specific to Ambient Light Sensor, user agents must must:

User agents may also limit maximum sampling frequency .

These mitigation strategies complement the generic mitigations defined in the Generic Sensor API [GENERIC-SENSOR] .

3.1. Reducing sensor readings accuracy

In order to reduce accuracy of sensor readings, this specification defines a threshold check algorithm (the ambient light threshold check algorithm ) and a reading quantization algorithm (the ambient light reading quantization algorithm ).

These algorithms make use of the illuminance rounding multiple and the illuminance threshold value . Implementations must adhere to the following requirements for their values:

Note: Choosing an illuminance rounding multiple requires balancing not exposing readouts that are too precise while also providing readouts that are still useful for API users. The value of 50 lux as a minimum for the illuminance rounding multiple was determined in GitHub issue #13 after different ambient light level measurements under different lighting conditions were gathered and shown to thwart the attack described in [STEALINGSENSITIVEDATA] . 50 lux is also higher than the 5 lux required to make video recognition using ambient light sensor readings ( [VIDEORECOGNITIONAMBIENTLIGHT] ) infeasible.

Note: The illuminance threshold value is used to prevent leaking the fact that readings are hovering around a particular value but getting quantized to different values. For example, if illuminance rounding multiple is 50, this prevents switching the illuminance value between 0 and 50 if the raw readouts switch between 24 and 26. The efficacy of the threshold check algorithm as an auxiliary fingerprinting mitigation strategy has not been mathematically proven, but it has been added to this specification based on implementation experience. Chromium bug 1332536 and Chromium review 3666917 contain more information about this.

3.2. Active local camera source requirement

Many of the attacks on Ambient Light sensors referenced above rely on being able to access illuminance readouts for a certain amount of time without a user being aware that the data is being read.

[STEALINGSENSITIVEDATA] and [ALSPRIVACYANALYSIS] specifically recommend requesting user permission before allowing access to illuminance readouts as a privacy measure. On the other hand, it can be difficult to convey to users what an Ambient Light Sensor is so that they can make an informed choice to grant or deny access to it.

What this specification does instead is consider an Ambient Light Sensor to be a 1x1 grayscale camera, integrate with the [MEDIACAPTURE-STREAMS] specification and require there to be at least one local camera source that is not muted or stopped in order for illuminance readouts to be provided. In other words, an Ambient Light Sensor only provides readings if a local video camera is currently active and being used in the same window as the AmbientLightSensor instance.

Per the [MEDIACAPTURE-STREAMS] specification, this is only possible if script has called getUserMedia() and granted the "camera" permission. This also means the User Agent has at least indicated to the user that a local camera source has started being used as per Media Capture and Streams §  15. Privacy Indicator Requirements .

The goal of this model is to treat an Ambient Light Sensor as potentially as invasive as an actual camera device and subject it to the same strict privacy requirements together with the Generic Sensor mitigations described in Generic Sensor API § 4 Security and privacy considerations and the other Ambient Light Sensor-specific measures described in this section.

4. Model

The Ambient Light Sensor sensor type ’s associated Sensor subclass is the AmbientLightSensor class.

The Ambient Light Sensor has a default sensor , which is the device’s main light detector.

The Ambient Light Sensor is a powerful feature that is identified by the name " ambient-light-sensor ", which is also its associated ’s sensor permission name . Its permission revocation algorithm names is an empty set .

Note: See § 3.2 Active local camera source requirement . This specification relies on the result of calling the generic sensor permission revocation algorithm model specified in the [MEDIACAPTURE-STREAMS] with "ambient-light-sensor". specification instead.

The Ambient Light Sensor is a policy-controlled feature identified by the string "ambient-light-sensor". Its default allowlist is 'self' .

The current light level or illuminance is a value that represents the ambient light level around the hosting device. Its unit is the lux (lx) [SI] .

Note: The precise lux value reported by different devices in the same light can be different, due to differences in detection method, sensor construction, etc.

The Ambient Light Sensor has an illuminance rounding multiple , measured in lux, which represents a number whose multiples the illuminance readings will be rounded up to.

The Ambient Light Sensor has an illuminance threshold value , measured in lux, which is used in the ambient light threshold check algorithm .

Note: see § 3.1 Reducing sensor readings accuracy for minimum requirements for the values described above.

5. API

5.1. The AmbientLightSensor Interface

[SecureContext, Exposed=Window]
interface AmbientLightSensor : Sensor {
  constructor(optional SensorOptions sensorOptions = {});
  readonly attribute double? illuminance;
};

To construct an AmbientLightSensor object the user agent must invoke the construct an ambient light sensor object abstract operation.

5.1.1. The illuminance attribute

The illuminance getter steps are:

  1. Let illuminance be the result of invoking get value from latest reading with this and "illuminance" as arguments.

  2. Return illuminance .

5.1.2. Media Capture and Streams integration

As discussed in § 3.2 Active local camera source requirement , illuminance readouts are provided only if the same Window with an AmbientLightSensor object has at least one local camera source that is not muted or stopped .

The ambient light pre-activation checks algorithm is invoked by start() as specified in [GENERIC-SENSOR] .

Furthermore, whenever an item is added to the Window .[[devicesLiveMap]] internal slot, or one of its items has its value changed, implementations MUST run the following steps:

  1. Let global be the Window object of the affected [[devicesLiveMap]] internal slot.

  2. Let result be the result of invoking check for active local camera sources with global .

  3. If result is true, return.

  4. For each AmbientLightSensor object sensor whose relevant global object is global :

    1. If sensor . [[state]] is "idle", then continue .

    2. Invoke deactivate a sensor object with sensor .

    3. Let e be the result of creating a " NotReadableError " DOMException .

    4. Queue a global task on the sensor task source with global to run notify error with sensor and e as arguments.

6. Abstract Operations

6.1. Construct an ambient light sensor object

input

options , a SensorOptions object.

output

An AmbientLightSensor object.

  1. Let allowed be the result of invoking check sensor policy-controlled features with AmbientLightSensor .

  2. If allowed is false, then:

    1. Throw a SecurityError DOMException .

  3. Let ambient_light_sensor be the new AmbientLightSensor object.

  4. Invoke initialize a sensor object with ambient_light_sensor and options .

  5. Return ambient_light_sensor .

6.2. Ambient light threshold check algorithm

The Ambient Light Sensor sensor type defines the following threshold check algorithm :

input

newReading , a sensor reading

latestReading , a sensor reading

output

A boolean indicating whether the difference in readings is significant enough.

  1. If newReading ["illuminance"] is null, return true.

  2. If latestReading ["illuminance"] is null, return true.

  3. Let newIlluminance be newReading ["illuminance"].

  4. Let latestIlluminance be latestReading ["illuminance"].

  5. If abs ( latestIlluminance - newIlluminance ) < illuminance threshold value , return false.

  6. Let roundedNewIlluminance be the result of invoking the ambient light reading quantization algorithm algorithm with newIlluminance .

  7. Let roundedLatestIlluminance be the result of invoking the ambient light reading quantization algorithm algorithm with latestIlluminance .

  8. If roundedNewIlluminance and roundedLatestIlluminance are equal, return false.

  9. Otherwise, return true.

Note: This algorithm invokes the ambient light reading quantization algorithm to ensure that readings that round up to the same value do not trigger an update in the main update latest reading algorithm. Not doing so would indicate to users that the raw illuminance readings are within a range where they differ by at least the illuminance threshold value but do not round up to different illuminance rounding multiple .

6.3. Ambient light reading quantization algorithm

The Ambient Light Sensor sensor type defines the following reading quantization algorithm :

input

reading , a sensor reading

output

A sensor reading

  1. Let quantizedReading be reading .

  2. Set quantizedReading ["illuminance"] to the multiple of the illuminance rounding multiple that reading ["illuminance"] is closest to.

  3. Return quantizedReading .

6.4. Ambient light pre-activation checks algorithm

The Ambient Light Sensor sensor type defines the following pre-activation checks algorithm :

input

sensor , an AmbientLightSensor object

output

A boolean indicating whether the checks have passed and sensor activation may proceed.

  1. Let global be sensor ’s relevant global object .

  2. Return the result of invoking check for active local camera sources with global .

6.5. Check for active local camera source

input

global , an Window object

output

A boolean indicating whether there are active local camera sources.

  1. If global does not have a [[mediaStreamTrackSources]] internal slot, return false.

  2. For each source in global ’s [[mediaStreamTrackSources]] internal slot:

    1. If source is not a video input device, then continue .

    2. If source is not stopped or muted , then return true.

  3. Return false.

7. Automation

This section extends the automation section defined in the Generic Sensor API [GENERIC-SENSOR] to provide mocking information about the ambient light levels for the purposes of testing a user agent’s implementation of Ambient Light Sensor .

7.1. Mock Sensor Type

The AmbientLightSensor class has an associated mock sensor type which is "ambient-light" , its mock sensor reading values dictionary is defined as follows:

dictionary AmbientLightReadingValues {
  required double? illuminance;
};

8. Use Cases and Requirements

While some of the use cases may benefit from obtaining precise ambient light measurements, the use cases that convert ambient light level fluctuations to user input events would benefit from higher sampling frequencies .

Note: A previous version of this specification did not require an active camera and did not integrate with the [MEDIACAPTURE-STREAMS] specification. It allowed for a wider range of use cases, such as providing input smart home systems to control lighting or checking whether the light level at a work space is sufficient.

9. Acknowledgements

Doug Turner for the initial prototype and Marcos Caceres for the test suite.

Paul Bakaus for the LightLevelSensor idea.

Mikhail Pozdnyakov and Alexander Shalamov for the use cases and requirements.

Lukasz Olejnik for the privacy risk assessment.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example" , like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note" , like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

https://w3c.github.io/sensors/#generic-sensor-permission-revocation-algorithm Referenced in: 4. Model https://w3c.github.io/permissions/#dfn-name https://w3c.github.io/permissions/#dfn-permission-revocation-algorithm https://w3c.github.io/permissions/#dfn-powerful-feature https://w3c.github.io/webappsec-permissions-policy/#default-allowlist

Terms defined by reference

References

Normative References

[ECMASCRIPT]
ECMAScript Language Specification . URL: https://tc39.es/ecma262/multipage/
[GENERIC-SENSOR]
Rick Waldron. Generic Sensor API . URL: https://w3c.github.io/sensors/
[HTML]
Anne van Kesteren; et al. HTML Standard . Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard . Living Standard. URL: https://infra.spec.whatwg.org/ [PERMISSIONS]
[MEDIACAPTURE-STREAMS]
Marcos Caceres; Mike Taylor. Cullen Jennings; et al. Permissions Media Capture and Streams . URL: https://w3c.github.io/permissions/ https://w3c.github.io/mediacapture-main/
[PERMISSIONS-POLICY-1]
Ian Clelland. Permissions Policy . URL: https://w3c.github.io/webappsec-permissions-policy/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels . March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard . Living Standard. URL: https://webidl.spec.whatwg.org/

Informative References

[ALSPRIVACYANALYSIS]
Lukasz Olejnik. Privacy analysis of Ambient Light Sensors . 31 August 2016. URL: https://blog.lukaszolejnik.com/privacy-of-ambient-light-sensors/
[CSSOM-VIEW-1]
Simon Pieters. CSSOM View Module . URL: https://drafts.csswg.org/cssom-view/
[MEDIAQUERIES-5]
Dean Jackson; et al. Media Queries Level 5 . URL: https://drafts.csswg.org/mediaqueries-5/
[PINSKIMMINGVIASENSOR]
Raphael Spreitzer. PIN Skimming: Exploiting the Ambient-Light Sensor in Mobile Devices . 15 May 2014. URL: https://arxiv.org/abs/1405.3760
[SI]
SI Brochure: The International System of Units (SI), 8th edition . 2014. URL: http://www.bipm.org/en/publications/si-brochure/
[STEALINGSENSITIVEDATA]
Lukasz Olejnik. Stealing sensitive browser data with the W3C Ambient Light Sensor API . 19 April 2017. URL: https://blog.lukaszolejnik.com/stealing-sensitive-browser-data-with-the-w3c-ambient-light-sensor-api/
[VIDEORECOGNITIONAMBIENTLIGHT]
Raphael Spreitzer. Video recognition using ambient light sensors . 21 April 2016. URL: https://doi.org/10.1109/PERCOM.2016.7456511

IDL Index

[SecureContext, Exposed=Window]
interface AmbientLightSensor : Sensor {
  constructor(optional SensorOptions sensorOptions = {});
  readonly attribute double? illuminance;
};
dictionary AmbientLightReadingValues {
  required double? illuminance;
};