<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE rfc SYSTEM 'rfc2629.dtd' []>
<rfc ipr="trust200902" category="std" docName="draft-ietf-jmap-core-01">
<?rfc toc="yes"?>
<?rfc symrefs="yes"?>
<?rfc sortrefs="yes"?>
<?rfc compact="yes"?>
<?rfc subcompact="no"?>
<?rfc private=""?>
<?rfc topblock="yes"?>
<?rfc comments="no"?>
<front>
<title abbrev="JMAP">JSON Meta Application Protocol</title>

<author initials="N.M." surname="Jenkins" fullname="Neil Jenkins">
<organization>FastMail</organization>
<address>
<postal>
<street>Level 1, 91 William St</street>
<city>Melbourne</city>
<code>VIC 3000</code>
<country>Australia</country>
<region></region>
</postal>
<phone></phone>
<email>neilj@fastmail.com</email>
<uri>https://www.fastmail.com</uri>
</address>
</author>
<date year="2017" month="July" day="16"/>

<area>Applications</area>
<workgroup>JMAP</workgroup>
<keyword>JMAP</keyword>
<keyword>JSON</keyword>


<abstract>
<t>This document specifies a protocol for synchronising JSON-based data objects efficiently, with support for push and out-of-band binary data upload/download.
</t>
</abstract>


</front>

<middle>

<section anchor="introduction" title="Introduction">
<t>JMAP is a generic protocol for synchronising data, such as mail, calendars or contacts, between a client and a server. It is optimised for mobile and web environments, and aims to provide a consistent interface to different data types.
</t>
<t>This specification is for the generic mechanism of authentication and synchronisation. Further specifications define the data models for different data types that may be synchronised via JMAP.
</t>
<t>JMAP is designed to make efficient use of limited network resources. Multiple API calls may be batched in a single request to the server, reducing round trips and improving battery life on mobile devices. Push connections remove the need for polling, and an efficient delta update mechanism ensures a minimum of data is transferred.
</t>
<t>JMAP is designed to be horizontally scalable to a very large number of users. This is facilitated by the separate end points for users after login, the separation of binary and structured data, and a shared data model that does not allow data dependencies between accounts.
</t>

<section anchor="notational-conventions" title="Notational Conventions">
<t>The key words &quot;MUST&quot;, &quot;MUST NOT&quot;, &quot;REQUIRED&quot;, &quot;SHALL&quot;, &quot;SHALL NOT&quot;, &quot;SHOULD&quot;, &quot;SHOULD NOT&quot;, &quot;RECOMMENDED&quot;, &quot;MAY&quot;, and &quot;OPTIONAL&quot; in this document are to be interpreted as described in <xref target="RFC2119"/>.
</t>
<t>The underlying format used for this specification is JSON. Consequently, the terms &quot;object&quot; and &quot;array&quot; as well as the four primitive types (strings, numbers, booleans, and null) are to be interpreted as described in Section 1 of <xref target="RFC7159"/>.
</t>
<t>Some examples in this document contain &quot;partial&quot; JSON documents used for illustrative purposes.  In these examples, three periods &quot;...&quot; are used to indicate a portion of the document that has been removed for compactness.
</t>
<t>Types signatures are given for all JSON objects in this document. The following conventions are used:
</t>
<t>
<list style="symbols">
<t><spanx style="verb">Boolean|String</spanx> – The value is either a JSON <spanx style="verb">Boolean</spanx> value, or a JSON <spanx style="verb">String</spanx> value.</t>
<t><spanx style="verb">Foo</spanx> – Any name that is not a native JSON type means an object for which the properties (and their types) are defined elsewhere within this document.</t>
<t><spanx style="verb">Foo[]</spanx> – An array of objects of type <spanx style="verb">Foo</spanx>.</t>
<t><spanx style="verb">String[Foo]</spanx> – A JSON <spanx style="verb">Object</spanx> being used as a map (associative array), where all the values are of type <spanx style="verb">Foo</spanx>.</t>
</list>
</t>
</section>

<section anchor="json-as-the-data-encoding-format" title="JSON as the data encoding format">
<t>JSON is a text-based data interchange format as specified in <xref target="RFC7159"/>. The I-JSON format defined in <xref target="RFC7493"/> is a strict subset of this, adding restrictions to avoid potentially confusing scenarios (for example, it mandates that an object MUST NOT have two properties with the same key).
</t>
<t>All data sent from the client to the server or from the server to the client (except binary file upload/download) MUST be valid I-JSON according to the RFC, and is therefore case-sensitive and encoded in UTF-8 (<xref target="RFC3629"/>).
</t>
</section>

<section anchor="terminology" title="Terminology">

<section anchor="user" title="User">
<t>A user represents a set of permissions relating to what data can be seen. To  access data in JMAP, you first authenticate as a particular user.
</t>
</section>

<section anchor="accounts" title="Accounts">
<t>An account is a collection of data.
</t>
<t>All data, other than the Account objects themselves, belong to a single account. A single account may contain an arbitrary set of data, for example a collection of mail, contacts and calendars. Most operations in JMAP are isolated to a single account; there are a few explicit operations to copy data between them. Certain properties are guaranteed for data within the same account, for example uniqueness of ids within a type in that account.
</t>
<t>An account is not the same as a user, although it is common for the primary account to directly belong to the user. For example, you may have an account that contains data for a group or business, to which multiple users have access. Users may also have access to accounts belonging to another user if that user is sharing some of their data.
</t>
</section>

<section anchor="data-types-and-records" title="Data types and records">
<t>JMAP provides a uniform interface for creating, retrieving, updating and deleting various types of objects. A <spanx style="strong">data type</spanx> is a collection of named, typed properties, just like the schema for a database table. Each instance of a data type is called a <spanx style="strong">record</spanx>.
</t>
</section>
</section>

<section anchor="ids" title="Ids">
<t>All object ids are assigned by the server, and are immutable. They MUST be unique among all objects of the <spanx style="strong">same type</spanx> within the <spanx style="strong">same account</spanx>. Ids may clash across accounts, or for two objects of different types within the same account.
</t>
<t>Ids are always <spanx style="verb">String</spanx>s. An id MUST be a valid UTF-8 string of at least 1 character in length and maximum 256 bytes in size, but MUST NOT start with the <spanx style="verb">#</spanx> character, as this is reserved for doing back references during object creation (see the <spanx style="emph">setFoos</spanx> description).
</t>
</section>

<section anchor="the-jmap-api-model" title="The JMAP API model">
<t>All data exchanges are authenticated using an access token. Authentication is covered in section 2.
</t>
<t>An authenticated client may exchange data with the server using four different mechanisms:
</t>
<t>
<list style="numbers">
<t>The client may make an API request to the server to get or set structured data. This request consists of an ordered series of method calls. These are processed by the server, which then returns an ordered series of responses. This is described in section 3.</t>
<t>The client may download binary files from the server. This is detailed in section 4.</t>
<t>The client may upload binary files to the server. This is specified in section 5.</t>
<t>The client may connect to a push channel on the server, to be notified when data has changed. This is explained in section 6.</t>
</list>
</t>
</section>
</section>

<section anchor="authentication" title="Authentication">
<t>When connecting to any JMAP server, the client must first gain an access token. It cannot just use a username/password directly. This allows the server to know (and show the user) which clients currently have access to the account, and to be able to revoke access individually.
</t>
<t>The server may support multiple different mechanisms for authenticating a user to gain the access token. It is expected that further types may be added in future extensions to the JMAP specification.
</t>

<section anchor="service-autodiscovery" title="Service autodiscovery">
<t>To begin authentication, the client needs to know the authentication URL for the JMAP server.
</t>
<t>There are two standardised autodiscovery methods in use for internet protocols:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">DNS srv</spanx>
See <xref target="RFC6186"/> and <xref target="RFC6764"/></t>
<t><spanx style="strong">.well-known/servicename</spanx>
See <xref target="RFC5785"/></t>
</list>
</t>
<t>A JMAP-supporting host for the domain <spanx style="verb">example.com</spanx> SHOULD publish a SRV record <spanx style="verb">_jmaps._tcp.example.com</spanx> which gives a <spanx style="emph">hostname</spanx> and <spanx style="emph">port</spanx> (usually port <spanx style="verb">443</spanx>). The authentication URL is then <spanx style="verb">https://${hostname}[:${port}]/.well-known/jmap</spanx> (following any redirects).
</t>
<t>If the client has a username in the form of an email address, it MAY use the domain portion of this to attempt autodiscovery of the JMAP server.
</t>
<t>To support clients that are unable to do SRV lookups, the server SHOULD make the <spanx style="emph">hostname</spanx> the same domain as the username if possible.
</t>
</section>

<section anchor="getting-an-access-token" title="Getting an access token">
<t>Authorization always starts with the client making a POST request to the authentication URL (found either via service autodiscovery or manual entry). The request MUST be of type <spanx style="verb">application/json</spanx> and specify an <spanx style="verb">Accept: application/json</spanx> header. The body of the request MUST be a single JSON object, encoded in UTF-8, with the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">username</spanx>: <spanx style="verb">String</spanx>
The username the client wishes to authenticate. This is normally the primary email address of the user.</t>
<t><spanx style="strong">clientName</spanx>: <spanx style="verb">String</spanx>
The name of the client software. e.g. <spanx style="verb">Mozilla Thunderbird</spanx>.</t>
<t><spanx style="strong">clientVersion</spanx>: <spanx style="verb">String</spanx>
Information to identify the version of the client.  This MUST change for any changed client code (e.g. a version control tag or counter for development software) and SHOULD sort lexically later for newer versions.</t>
<t><spanx style="strong">deviceName</spanx>: <spanx style="verb">String</spanx>
A human-friendly string to identify the device making the request, e.g. &quot;Joe Blogg's iPhone&quot;.</t>
</list>
</t>
<t>The server may use the client/device information to help identify the login to the user in a login log or other security reporting. Although hopefully unnecessary, they may also be helpful for working around client bugs in the future.
</t>
<t>The server will respond with one of the following HTTP status codes:
</t>

<section anchor="success-but-more-authorization-required" title="200: Success, but more authorization required.">
<t>The response body will be a single JSON object with the following properties.
</t>
<t>
<list style="symbols">
<t><spanx style="strong">loginId</spanx>: <spanx style="verb">String</spanx>
An id from the server to allow it to connect the next request with previous requests in the login process. This SHOULD be of limited time validity (e.g. 15 minutes from previous call).</t>
<t><spanx style="strong">methods</spanx>: <spanx style="verb">AuthMethod[]</spanx>
A list of the supported authentication methods to continue with authentication. See below for definition of the <spanx style="strong">AuthMethod</spanx> object.</t>
<t><spanx style="strong">prompt</spanx>: <spanx style="verb">String|null</spanx>
A message to display in the client to the user. The client MUST treat this as plain text, but SHOULD automatically hyperlink any URLs it finds if a system browser is available.</t>
</list>
</t>
<t>This is the standard response to an initial request. Note, a server may return this even if the username is not actually active, to prevent enumeration. The client should then pick one of the <spanx style="emph">methods</spanx> from the list in the response to continue with authentication (if no methods supported by the client are in the list, it will not be able to get an access token).
</t>
<t>An <spanx style="strong">AuthMethod</spanx> object MUST have a <spanx style="strong">type</spanx> property. This is a <spanx style="verb">String</spanx> representing the method of authentication. For some types, there may be other values required on the AuthMethod object in addition; see the description of types below. The following types are currently defined, but more may be added in the future. A client SHOULD offer the user the option to choose any of the method types returned that the client supports. The client MUST ignore any types it does not understand:
</t>
<t>
<list style="symbols">
<t><spanx style="verb">external</spanx>: The user must do something out-of-band to authorize the app. The server SHOULD use the <spanx style="emph">prompt</spanx> property of the response to tell the user what they need to do. A client that supports the <spanx style="emph">external</spanx> authorisation type MUST offer a mechanism for the user to indicate to the client when they have completed the out-of-band authentication.</t>
<t><spanx style="verb">oauth</spanx>: OAuth based authentication. For OAuth integration, see the docs of the service in question, since every service implements it slightly differently and the client must register with the service beforehand to use it. If using this method, an access token is obtained entirely through the OAuth mechanism from this point on, and requests will be authenticated as per the OAuth spec. See the &quot;Refetching URL endpoints&quot; section below for how to obtain the URL endpoints after successfully authenticating using OAuth.</t>
<t><spanx style="verb">password</spanx>: The user must input their current password for the account.</t>
<t><spanx style="verb">totp</spanx>: The user must input a <eref target="https://tools.ietf.org/html/rfc6238">TOTP</eref> code from a device registered with the account.</t>
<t><spanx style="verb">yubikeyotp</spanx>: The user must input a <eref target="https://developers.yubico.com/OTP/">Yubico OTP</eref> code from a Yubikey registered with the account.</t>
<t><spanx style="verb">u2f</spanx>: The user must sign a challenge using a <eref target="https://fidoalliance.org/specifications/download/">FIDO U2F</eref> key registered with the account. The AuthMethod object for this type MUST also have the following properties:
<list style="symbols">
<t><spanx style="strong">appId</spanx>: <spanx style="verb">String</spanx>
The app id to use.</t>
<t><spanx style="strong">signChallenge</spanx>: <spanx style="verb">String</spanx>
The challenge to be signed by the U2F key.</t>
<t><spanx style="strong">registeredKeys</spanx>: <spanx style="verb">RegisteredKey[]</spanx>
The keys associated with this user. A <spanx style="strong">RegisteredKey</spanx> object has the
following properties:</t>
<t><spanx style="strong">version</spanx>: <spanx style="verb">String</spanx>
The U2F protocol version.</t>
<t><spanx style="strong">keyHandle</spanx>: <spanx style="verb">String</spanx>
The key handle of the registered key.</t>
</list></t>
<t><spanx style="verb">sms</spanx>: The user must input a one-time code sent via SMS to a phone number registered with the account. The AuthMethod object for this type MUST also have the following property:
<list style="symbols">
<t><spanx style="strong">phoneNumbers</spanx>: <spanx style="verb">LoginPhone[]|null</spanx>
An array of <spanx style="strong">LoginPhone</spanx> objects, each of which represents a phone registered with the account. A <spanx style="strong">LoginPhone</spanx> object has the following properties:
<list style="symbols">
<t><spanx style="strong">id</spanx>: <spanx style="verb">String</spanx>
The id of the phone. This is used when asking the server to send a code.</t>
<t><spanx style="strong">number</spanx>: <spanx style="verb">String</spanx>
The phone number to display to the user to remind them which number the SMS will be/was sent to. This MAY have some characters replaced with an <spanx style="verb">X</spanx> or other &quot;blanked-out&quot; character if the server does not wish to disclose the full phone number at this point. e.g. if the phone registered with the account is <spanx style="verb">+61 123 456 789</spanx>, the server might return
<spanx style="verb">+61 1XX XXX X89</spanx> as the number.</t>
<t><spanx style="strong">isCodeSent</spanx>: <spanx style="verb">Boolean</spanx>
Has the verification code been sent to this number yet? The server MAY choose to send the SMS before the first time this auth option is returned, or may wait for the user to explicitly request it.</t>
</list></t>
</list></t>
</list>
</t>
<t>If not using <spanx style="verb">"oauth"</spanx>, the user will at some point indicate to the client to continue authentication (after inputing any required token/code/password dependent on the auth method chosed). At this point the client submits a POST request to the same URL as before, with the body being a single JSON object with the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">loginId</spanx>: <spanx style="verb">String</spanx>
The <spanx style="emph">loginId</spanx> the server sent from the previous request.</t>
<t><spanx style="strong">type</spanx>: <spanx style="verb">String</spanx>
The type of the method chosen to continue authentication.</t>
<t><spanx style="strong">value</spanx>: <spanx style="verb">*</spanx>
The value as appropriate for the given type:
<list style="symbols">
<t><spanx style="verb">external</spanx>: <spanx style="verb">null</spanx></t>
<t><spanx style="verb">password</spanx>/<spanx style="verb">totp</spanx>/<spanx style="verb">yubikeyotp</spanx>/<spanx style="verb">sms</spanx>: <spanx style="verb">String</spanx> – the password/one-time code.</t>
<t><spanx style="verb">u2f</spanx>: <spanx style="verb">SignResponse</spanx> – an object with <spanx style="emph">keyHandle</spanx>, <spanx style="emph">signatureData</spanx> and <spanx style="emph">clientData</spanx> <spanx style="verb">String</spanx> properties, as defined in the U2F spec.</t>
</list></t>
</list>
</t>
<t>Note: The client SHOULD NOT store any password/code the user has entered beyond what is required to submit it to the server in this step.
</t>
<t>The server will then return one of the same set of responses as before, which should be handled the same (for example, if two-factor authentication is required, a <spanx style="verb">200</spanx> response may be returned again and TOTP/U2F prompted for).
</t>
<t>If the user chooses to authenticate using SMS, they may need to request the server to send the code to a particular number before they can submit a code. To do this, the client submits a POST request to the same URL as before, with the body being a single JSON object with the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">loginId</spanx>: <spanx style="verb">String</spanx>
The <spanx style="emph">loginId</spanx> the server sent from the previous request.</t>
<t><spanx style="strong">sendCodeTo</spanx>: <spanx style="verb">String</spanx>
The id of the phone number to send the code to.</t>
</list>
</t>
<t>The server SHOULD send the code to the given phone if the phone id is valid. If the code has already been sent, it is server-dependent whether it is sent again or ignored. The server MUST return one of the same set of responses as before, which should be handled the same (in most cases this will be a <spanx style="verb">200</spanx> response identical to before except that the <spanx style="emph">isCodeSent</spanx> property for the phone will now be <spanx style="verb">true</spanx>).
</t>
</section>

<section anchor="authentication-is-complete-access-token-created" title="201: Authentication is complete, access token created.">
<t>The response body will be a single JSON object with the following properties.
</t>
<t>
<list style="symbols">
<t><spanx style="strong">username</spanx>: <spanx style="verb">String</spanx>
The username that was successfully authenticated.</t>
<t><spanx style="strong">accessToken</spanx>: <spanx style="verb">String</spanx>
The secret token to be used by the client to authenticate all future JMAP requests. The client should keep this secure, preferably in an OS keychain or the like. Since tokens should not be reused across devices or clients, the client SHOULD NOT reveal this token to the user.</t>
<t><spanx style="strong">signingId</spanx>: <spanx style="verb">String</spanx>
The id to put in the <eref target="https://tools.ietf.org/html/rfc7519">JWT</eref> for signed GET requests (see below). This is used to allow the server to find the session so it can find the signing key to use to verify the token. You MUST NOT be able to derive the <spanx style="emph">accessToken</spanx> or <spanx style="emph">signingKey</spanx> from the <spanx style="emph">signingId</spanx>.</t>
<t><spanx style="strong">signingKey</spanx>: <spanx style="verb">String</spanx>
The secret key to use for signing the <eref target="https://tools.ietf.org/html/rfc7519">JWT</eref> for signed GET requests (see below), encoded as base64url as specified in (<xref target="RFC4648"/>). The client should keep this secure, preferably in an OS keychain or the like. Since keys should not be reused across devices or clients, the client SHOULD NOT reveal this token to the user.</t>
<t><spanx style="strong">accounts</spanx>: <spanx style="verb">String[Account]</spanx>
A map of <spanx style="strong">account id</spanx> to Account object for each account the user has access to.
A single access token may provide access to multiple accounts, for example if another user is sharing their mail with the logged in user, or if there is an account that contains data for a group or business.
All data belongs to a single account. With the exception of a few explicit operations to copy data between accounts, all JMAP methods take an <spanx style="emph">accountId</spanx> argument that specifies on which account the operations are to take place. This argument is always optional; if not specified, the primary account is used. All ids (other than Account ids of course) are only unique within their account.
In the event of a severe internal error, a server may have to reallocate ids or do something else that violates standard JMAP data constraints. In this situation, the data on the server is no longer compatible with cached data the client may have from before. The server MUST treat this as though the account has been deleted and then recreated with a new account id. Clients will then be forced to throw away any data with the old account id and refetch all data from scratch.
An <spanx style="strong">Account</spanx> object has the following properties:
<list style="symbols">
<t><spanx style="strong">name</spanx>: <spanx style="verb">String</spanx>
A user-friendly string to show when presenting content from this account, e.g. the email address representing the owner of the account.</t>
<t><spanx style="strong">isPrimary</spanx>: <spanx style="verb">Boolean</spanx>
This MUST be true for <spanx style="strong">at most</spanx> one of the accounts returned. This is to be considered the user's main or default account by the client. If no account being returned belongs to the user, or in any other way there is no appropriate way to determine a default account, then this MAY be <spanx style="verb">false</spanx> for all accounts.</t>
<t><spanx style="strong">isReadOnly</spanx>: <spanx style="verb">Boolean</spanx>
This is <spanx style="verb">true</spanx> if the entire account is read-only.</t>
<t><spanx style="strong">hasDataFor</spanx>: <spanx style="verb">String[]</spanx>
A list of the data profiles available in this account. Each future JMAP data types specification will define a profile name to encompass that set of types.</t>
</list></t>
<t><spanx style="strong">capabilities</spanx>: <spanx style="verb">String[Object]</spanx>
An object specifying the capabilities of this server. The keys are URIs, which specify the specifications supported by the server. The value for each of these keys is an object that MAY include further information about the server's capabilities in relation to that spec.
The client MUST ignore any properties it does not understand.
The capabilities object MUST include a property called <spanx style="verb">{TODO: URI for this spec}</spanx>. The value of this property is an object which SHOULD contain the following information on server capabilities:
<list style="symbols">
<t><spanx style="strong">maxSizeUpload</spanx>: <spanx style="verb">Number</spanx>
The maximum file size, in bytes, that the server will accept for a single file upload (for any purpose).</t>
<t><spanx style="strong">maxConcurrentUpload</spanx>: <spanx style="verb">Number</spanx>
The maximum number of concurrent requests the server will accept to the upload endpoint.</t>
<t><spanx style="strong">maxSizeRequest</spanx>: <spanx style="verb">Number</spanx>
The maximum size, in bytes, that the server will accept for a single
request to the API endpoint.</t>
<t><spanx style="strong">maxConcurrentRequests</spanx>: <spanx style="verb">Number</spanx>
The maximum number of concurrent requests the server will accept to
the API endpoint.</t>
<t><spanx style="strong">maxCallsInRequest</spanx>: <spanx style="verb">Number</spanx>
The maximum number of method calls the server will accept in a single request to the API endpoint.</t>
<t><spanx style="strong">maxObjectsInGet</spanx>: <spanx style="verb">Number</spanx>
The maximum number of obje ts that the client may request in a single <spanx style="verb">getFoos</spanx> type method call.</t>
<t><spanx style="strong">maxObjectsInSet</spanx>: <spanx style="verb">Number</spanx>
The maximum number of objects the client may send to create, update or destroy in a single <spanx style="verb">setFoos</spanx> type method call.</t>
</list>
Future specifications will define their own properties on the capabilities object.</t>
<t><spanx style="strong">apiUrl</spanx>: <spanx style="verb">String</spanx>
The URL to use for JMAP API requests.</t>
<t><spanx style="strong">downloadUrl</spanx>: <spanx style="verb">String</spanx>
The URL endpoint to use when downloading files (see the Download section of this spec), in <xref target="RFC6570"/> URI Template (level 1) format. The URL MUST contain variables called <spanx style="verb">accountId</spanx> and <spanx style="verb">blobId</spanx>. The URL SHOULD contain a variable called <spanx style="verb">name</spanx>.</t>
<t><spanx style="strong">uploadUrl</spanx>: <spanx style="verb">String</spanx>
The URL endpoint to use when uploading files (see the Upload section of this spec).</t>
<t><spanx style="strong">eventSourceUrl</spanx>: <spanx style="verb">String</spanx>
The URL to connect to for push events (see the Push section of this spec).</t>
</list>
</t>
<t>URLs are returned only after logging in. This allows different URLs to be used for users located in different geographic datacentres within the same service.
</t>
<t>Note, if authentication is done via IP or mobile subscriber ID or some similar mechanism, a <spanx style="verb">201</spanx> response MAY be returned in response to the initial request (with just the username and client info).
</t>
</section>

<section anchor="malformed-request" title="400: Malformed request">
<t>The request is of the wrong content type, or does not contain data in the expected format. The client MUST NOT retry the same request. There is no content in the response.
</t>
</section>

<section anchor="authentication-step-failed-but-client-may-try-again" title="403: Authentication step failed, but client may try again">
<t>Returned in response to a continuation request which failed (e.g. the password entered was not correct, or the out-of-band step was not completed successfully). The response body will be a single JSON object with the same properties as the <spanx style="verb">200</spanx> response, and the client may try again.
</t>
</section>

<section anchor="not-found" title="404: Not found">
<t>The JMAP authentication server is not available at this address. The client needs to rediscover the authentication URL. There is no content in the response.
</t>
</section>

<section anchor="restart-authentication" title="410: Restart authentication">
<t>The login attempt has failed permanently. This may be due to a password being incorrect, the login id expiring, or any other reason. The client MUST restart authentication (go back to sending the username and client info to the server). There is no content in the response.
</t>
</section>

<section anchor="rate-limited" title="429: Rate limited">
<t>Returned if the server is temporarily blocking this IP/client from authenticating. This may be due to too many failed password attempts, or detected username enumeration attempts, or any other reason. (Legitimate) clients should wait a while then try again. There is no content in the response.
</t>
</section>

<section anchor="internal-server-error" title="500: Internal server error">
<t>Something has gone wrong internally, and the server is in a broken state. Don't automatically retry. There is no content in the response.
</t>
</section>

<section anchor="service-unavailable" title="503: Service unavailable">
<t>The server is currently down. Try again later with exponential backoff. There is no content in the response.
</t>
</section>
</section>

<section anchor="refetching-url-endpoints" title="Refetching URL endpoints">
<t>A server MAY (although SHOULD NOT) move end points for any services other than authentication at any time. If a request to the API/file upload/event source endpoint returns a <spanx style="verb">404</spanx>, the client MUST refetch the URL endpoints. To do this, it should make an authenticated GET request to the authentication URL (see below for how to authenticate requests).
</t>
<t>For OAuth logins, this is how the URLs may be fetched initially as well.
</t>
<t>The server MUST respond with one of the following status codes:
</t>

<section anchor="authentication-is-complete-access-token-created-1" title="201: Authentication is complete, access token created.">
<t>The request was successful. The response will be of type <spanx style="verb">application/json</spanx> and consists of a single JSON object containing the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">username</spanx>: <spanx style="verb">String</spanx>
The username that was successfully authenticated.</t>
<t><spanx style="strong">accounts</spanx>: <spanx style="verb">String[Account]</spanx>
An object representing the accounts the user has access to. See the full description above.</t>
<t><spanx style="strong">capabilities</spanx>: <spanx style="verb">String[Object]</spanx>
An object specifying the capabilities of this server. See the full description above.</t>
<t><spanx style="strong">apiUrl</spanx>: <spanx style="verb">String</spanx>
The URL to use for JMAP API requests.</t>
<t><spanx style="strong">downloadUrl</spanx>: <spanx style="verb">String</spanx>
The URL endpoint to use when downloading files (see above).</t>
<t><spanx style="strong">uploadUrl</spanx>: <spanx style="verb">String</spanx>
The URL endpoint to use when uploading files (see the Upload section of this spec).</t>
<t><spanx style="strong">eventSourceUrl</spanx>: <spanx style="verb">String</spanx>
The URL to connect to for push events (see the Push section of this spec).</t>
</list>
</t>
</section>

<section anchor="restart-authentication-1" title="403: Restart authentication">
<t>The <spanx style="verb">Authorization</spanx> header was missing or did not contain a valid token. Reauthenticate and then retry the request. There is no content in the response.
</t>
</section>

<section anchor="not-found-1" title="404: Not found">
<t>The JMAP server is no longer here. There is no content in the response.
</t>
</section>

<section anchor="internal-server-error-1" title="500: Internal server error">
<t>Something has gone wrong internally, and the server is in a broken state. Don't automatically retry. There is no content in the response.
</t>
</section>

<section anchor="service-unavailable-1" title="503: Service unavailable">
<t>The server is currently down. Try again later with exponential backoff. There is no content in the response.
</t>
</section>
</section>

<section anchor="revoking-an-access-token" title="Revoking an access token">
<t>The validity of an access token is determined by the server. It may be valid for a limited time only, or expire after a certain time of inactivity, or be valid indefinitely etc. If an access token expires, it MUST NOT be resurrected. The client MUST restart the authentication process to get a new access token.
</t>
<t>For OAuth, see the provider's documentation on revoking access tokens.
</t>
<t>Otherwise, a client may revoke an access token at any time by making an authenticated DELETE HTTP request to the authentication URL (the one used to get the token in the first place). The response from the server will be one of the following:
</t>

<section anchor="success" title="204: Success">
<t>The access token has now been revoked. There is no content in the response.
</t>
</section>

<section anchor="unauthorized" title="401: Unauthorized">
<t>Failed due to missing <spanx style="verb">Authorization</spanx> header, or the <spanx style="verb">Authorization</spanx> header did not contain a valid access token. As per the HTTP spec, the response MUST have a <spanx style="verb">WWW-Authenticate: Bearer</spanx> header. There is no content in the response.
</t>
</section>
</section>

<section anchor="authenticating-http-requests" title="Authenticating HTTP requests">
<t>All HTTP requests other than to the authentication URL must be authenticated. To do this, the client MUST add an <spanx style="verb">Authorization</spanx> header to each request.
</t>
<t>Once authenticated, the client will have an access token. This is used with the <spanx style="verb">Bearer</spanx> scheme as specified in <xref target="RFC6750"/> to authenticate HTTP requests.
</t>
<t>For example, if <spanx style="emph">user@example.com</spanx> successfully logged in and the client received an <spanx style="emph">accessToken</spanx> of <spanx style="verb">abcdef1234567890</spanx>, to authenticate requests you would add the following header:
</t>

<figure align="center"><artwork align="center">
Authorization: Bearer abcdef1234567890
</artwork></figure>

<section anchor="signed-get-requests" title="Signed GET requests">
<t>Sometimes, particularly in the browser context, authenticating a GET request using the usual <spanx style="verb">Authorization</spanx> header is not easily implemented. In such situations, a client may use a signed request instead.
</t>
<t>Instead of the <spanx style="verb">Authorization</spanx> header, a signed request has an <spanx style="verb">access_token</spanx> query parameter, the value of which is an <xref target="RFC7519"/> <eref target="https://jwt.io/">JSON Web Token</eref> constructed as follows:
</t>
<t>
<list style="symbols">
<t>The algorithm MUST be HMAC SHA-256.</t>
<t>The JWT MUST contain the following set of claims:
<list style="symbols">
<t><spanx style="strong">iss</spanx>: <spanx style="verb">String</spanx> The <spanx style="emph">signingId</spanx> value returned after authentication.</t>
<t><spanx style="strong">sub</spanx>: <spanx style="verb">String</spanx> The origin + path of the URL being signed,
(i.e. the full URL excluding query parameters).</t>
<t><spanx style="strong">iat</spanx>: <spanx style="verb">Number</spanx> The time the client created this JWT, in seconds since
1970-01-01T00:00:00Z.</t>
</list></t>
<t>The JWT MUST be signed using the <spanx style="emph">signingKey</spanx> returned after authentication
as the key.</t>
</list>
</t>
<t>To verify, a server MUST:
* Ensure the algorithm is set to HMAC SHA-256.
* Verify the URL being requested matches that in the <spanx style="emph">sub</spanx> claim.
* Decode the payload and look up the session using the <spanx style="emph">iss</spanx> claim, ensure it is still valid, and then verify the JWT signature is valid using the session's <spanx style="emph">signingKey</spanx>.
</t>
<t>The server MAY choose to only allow tokens to be valid for a limited amount of time after the client created it, as determined by the <spanx style="emph">iat</spanx> claim.
</t>
</section>
</section>
</section>

<section anchor="structured-data-exchange" title="Structured data exchange">
<t>The client may make an API request to the server to get or set structured data. This request consists of an ordered series of method calls. These are processed by the server, which then returns an ordered series of responses.
</t>

<section anchor="making-an-api-request" title="Making an API request">
<t>To make an API request, the client makes an authenticated POST request to the API URL; see the Authentication section of the spec for how to discover this URL and how to authenticate requests.
</t>
<t>The request MUST have a content type of <spanx style="verb">application/json</spanx> and be encoded in UTF-8.
</t>
<t>The server SHOULD respond with one of the following HTTP response codes:
</t>

<section anchor="ok" title="200: OK">
<t>The API request was successful. The response will be of type <spanx style="verb">application/json</spanx> and consists of the response to the API calls, as described below.
</t>
</section>

<section anchor="bad-request" title="400: Bad Request">
<t>The request was malformed. For example, it may have had the wrong content type, or have had a JSON object that did not conform to the API calling structure (see <spanx style="emph">The structure of an API request</spanx> below). The client SHOULD NOT retry the same request. There is no content in the response.
</t>
</section>

<section anchor="unauthorized-1" title="401: Unauthorized">
<t>The <spanx style="verb">Authorization</spanx> header was missing or did not contain a valid token. Reauthenticate and then retry the request. As per the HTTP spec, the response MUST have a <spanx style="verb">WWW-Authenticate</spanx> header listing the available authentication schemes. There is no content in the response.
</t>
</section>

<section anchor="not-found-2" title="404: Not Found">
<t>The API endpoint has moved. See the Authentication section of the spec for how to rediscover the current URL to use. There is no content in the response.
</t>
</section>

<section anchor="payload-too-large" title="413: Payload Too Large">
<t>Returned if the client makes a request with more method calls than the server is willing to accept in a single request, or if the total bytes of the request is larger than the max size the server is willing to accept.
</t>
</section>

<section anchor="rate-limited-1" title="429: Rate limited">
<t>Returned if the client has made too many requests recently, or has too many concurrent requests currently in progress. Clients SHOULD wait a while then try again. The response MAY include a <spanx style="verb">Retry-After</spanx> header indicating how long to wait before making a new request.
</t>
</section>

<section anchor="internal-server-error-2" title="500: Internal Server Error">
<t>Something has gone wrong internally, and the server is in a broken state. Don't automatically retry. There is no content in the response.
</t>
</section>

<section anchor="service-unavailable-2" title="503: Service Unavailable">
<t>The server is currently down. Try again later with exponential backoff. There is no content in the response.
</t>
</section>
</section>

<section anchor="the-structure-of-an-api-request" title="The structure of an API request">
<t>The client initiates an API request by sending the server a JSON array. Each element in this array is another array representing a method invocation on the server. The server will process the method calls and return a response consisting of an array in the same format. Each method call always contains three elements:
</t>
<t>
<list style="numbers">
<t>The <spanx style="strong">name</spanx> of the method to call, or the name of the response from the server. This is a <spanx style="verb">String</spanx>.</t>
<t>An <spanx style="verb">Object</spanx> containing <spanx style="emph">named</spanx> <spanx style="strong">arguments</spanx> for that method or response.</t>
<t>A <spanx style="strong">client id</spanx>: an arbitrary <spanx style="verb">String</spanx> to be echoed back with the responses emitted by that method call (as we'll see lower down, a method may return 1 or more responses, as some methods make implicit calls to other ones).</t>
</list>
</t>
<t>Example query:
</t>

<figure align="center"><artwork align="center">
[
  ["method1", {"arg1": "arg1data", "arg2": "arg2data"}, "#1"],
  ["method2", {"arg1": "arg1data"}, "#2"],
  ["method3", {}, "#3"]
]
</artwork></figure>
<t>The method calls MUST be processed sequentially, in order. Each API request
(which, as shown, may contain multiple method calls) receives a JSON
response in exactly the same format. The output of the methods MUST be added
to the array in the same order as the methods are processed.
</t>
<t>Example response:
</t>

<figure align="center"><artwork align="center">
[
  ["responseFromMethod1", {"arg1": 3, "arg2": "foo"}, "#1"],
  ["responseFromMethod2", {"isBlah": true}, "#2"],
  ["anotherResponseFromMethod2", {
    "data": 10,
    "yetmoredata": "Hello"
  }, "#2"],
  ["aResponseFromMethod3", {}, "#3"]
]
</artwork></figure>
</section>

<section anchor="errors" title="Errors">
<t>If the data sent as an API request is not valid JSON or does not match the structure above, an error will be returned at the transport level. For example, when using JMAP over HTTP, a <spanx style="verb">400 Bad Request</spanx> error will be returned at the HTTP level.
</t>
<t>Possible errors for each method are specified in the method descriptions. If a method encounters an error, the appropriate <spanx style="verb">error</spanx> response MUST be inserted at the current point in the output array and, unless otherwise specified, further processing MUST NOT happen within that method call.
</t>
<t>Any further method calls in the request MUST then be processed as normal.
</t>
<t>An <spanx style="verb">error</spanx> response looks like this:
</t>

<figure align="center"><artwork align="center">
["error", {
  type: "unknownMethod"
}, "client-id"]
</artwork></figure>
<t>The response name is <spanx style="verb">error</spanx>, and it has a type property as specified in the method description. Other properties may be present with further information; these are detailed in the method descriptions where appropriate.
</t>
<t>Any method MAY return an error of type <spanx style="verb">serverError</spanx> if an unexpected or unknown error occurs during the processing of that call. The state of the server after such an error is undefined.
</t>
<t>If an unknown method is called, an <spanx style="verb">unknownMethod</spanx> error (this is the type shown in the example above) MUST be inserted and then the next method call MUST be processed as normal.
</t>
<t>If an unknown argument or invalid arguments (wrong type, or in violation of other specified constraints) are supplied to a method, an <spanx style="verb">invalidArguments</spanx> error MUST be inserted and then the next method call MUST be processed as normal.
</t>
</section>

<section anchor="vendorspecific-extensions" title="Vendor-specific extensions">
<t>Individual services will have custom features they wish to expose over JMAP. This may take the form of extra datatypes and/or methods not in the spec, or extra arguments to JMAP methods, or extra properties on existing data types (which may also appear in arguments to methods that take property names). To ensure compatibility with clients that don't know about a specific custom extension, and for compatibility with future versions of JMAP, the server MUST ONLY expose these extensions if the client explicitly opts in. Without opt-in, the server MUST follow the spec and reject anything that does not conform to it as specified.
</t>
</section>

<section anchor="security" title="Security">
<t>As always, the server must be strict about data received from the client. Arguments need to be checked for validity; a malicious user could attempt to find an exploit through the API. In case of invalid arguments (unknown/insufficient/wrong type for data etc.) the method MUST return an <spanx style="verb">invalidArguments</spanx> error and terminate.
</t>
</section>

<section anchor="concurrency" title="Concurrency">
<t>To ensure the client always sees a consistent view of the data, the state accessed by a method call MUST NOT change during the execution of the method, except due to actions by the method call itself. The state MAY change in-between method calls (even within a single API request).
</t>
</section>

<section anchor="the-number-datatype" title="The Number datatype">
<t>The JSON datatypes are limited to those found in JavaScript. A <spanx style="verb">Number</spanx> in JavaScript is represented as a signed double (64-bit floating point). However, except where explicitly specified, all numbers used in this API are unsigned integers &lt;= 2^53 (the maximum integer that may be reliably stored in a double). This implicitly limits the maximum length of message lists in queries and the like.
</t>
</section>

<section anchor="the-date-datatypes" title="The Date datatypes">
<t>Where a JMAP API specifies <spanx style="verb">Date</spanx> as a type, it means a string in <xref target="RFC3339"/> <spanx style="emph">date-time</spanx> format, with the <spanx style="emph">time-offset</spanx> component always <spanx style="verb">Z</spanx> (i.e. the date-time MUST be in UTC time) and <spanx style="emph">time-secfrac</spanx> always omitted. The &quot;T&quot; and &quot;Z&quot; MUST always be upper-case. For example, <spanx style="verb">"2014-10-30T14:12:00Z"</spanx>.
</t>
</section>

<section anchor="use-of-null" title="Use of null">
<t>Unless otherwise specified, a missing property in the arguments object of a request (from the client), or a response (from the server) MUST be intepreted exactly the same as that property having the value <spanx style="verb">null</spanx>.
</t>
<t>Unless otherwise specified, a missing property in a data object MUST be interpreted in the following ways:
- In the response to a <spanx style="emph">getFoos</spanx> style call, or when <spanx style="strong">creating</spanx> an object in a <spanx style="emph">setFoos</spanx> style call, a missing property MUST be interpreted as though it had the default value for that type, or <spanx style="verb">null</spanx> if no default is specified.
- When <spanx style="strong">updating</spanx> an object in a <spanx style="emph">setFoos</spanx> style call, a missing property MUST be interpreted as the existing value for that property (i.e. don't update it).
</t>
<t>For network efficiency, when fetching the server and client may make use of the above and omit properties which have the default value for the data type.
</t>
</section>

<section anchor="crud-methods" title="CRUD methods">
<t>JMAP provides a uniform interface for creating, retrieving, updating and deleting various types of objects. For a <spanx style="verb">Foo</spanx> data type, records of that type would be fetched via a <spanx style="verb">getFoos</spanx> call and modified via a <spanx style="verb">setFoos</spanx> call. Delta updates may be fetched via a <spanx style="verb">getFooUpdates</spanx> call. These methods all follow a standard format as described below.
</t>

<section anchor="getfoos" title="getFoos">
<t>Objects of type <spanx style="strong">Foo</spanx> are fetched via a call to <spanx style="emph">getFoos</spanx>. Methods with a name starting with <spanx style="verb">get</spanx> MUST NOT alter state on the server.
</t>
<t>This method may take some or all of the following arguments; see the definition of the data type in question. However, if one of the following arguments is available, it will behave exactly as specified below.
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String|null</spanx>
The id of the Account to use. If <spanx style="verb">null</spanx>, the primary account is used.</t>
<t><spanx style="strong">ids</spanx>: <spanx style="verb">String[]|null</spanx>
The ids of the Foo objects to return. If <spanx style="verb">null</spanx> then <spanx style="strong">all</spanx> records of the data type are returned, if this is supported for that data type.</t>
<t><spanx style="strong">properties</spanx>: <spanx style="verb">String[]|null</spanx>
If supplied, only the properties listed in the array are returned for each Foo object. If <spanx style="verb">null</spanx>, all properties of the object are returned. The id of the object is <spanx style="strong">always</spanx> returned, even if not explicitly requested.</t>
</list>
</t>
<t>The response to <spanx style="verb">getFoos</spanx> is called <spanx style="verb">foos</spanx>. It has the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String</spanx>
The id of the account used for the call.</t>
<t><spanx style="strong">state</spanx>: <spanx style="verb">String</spanx>
A string representing the state on the server for <spanx style="strong">all</spanx> the data of this type. If the data changes, this string will change. It is used to get delta updates, if supported for the type.</t>
<t><spanx style="strong">list</spanx>: <spanx style="verb">Foo[]</spanx>
An array of the Foo objects requested. This is the <spanx style="strong">empty array</spanx> if no objects were found, or if the <spanx style="emph">ids</spanx> argument passed in was also the empty array.</t>
<t><spanx style="strong">notFound</spanx>: <spanx style="verb">String[]|null</spanx>
This array contains the ids passed to the method for records that do not exist. This property is <spanx style="verb">null</spanx> if all requested ids were found, or if the <spanx style="emph">ids</spanx> argument passed in was either <spanx style="verb">null</spanx> or the empty array.</t>
</list>
</t>
<t>The following error may be returned instead of the <spanx style="verb">foos</spanx> response:
</t>
<t><spanx style="verb">accountNotFound</spanx>: Returned if an <spanx style="emph">accountId</spanx> was explicitly included with the request, but it does not correspond to a valid account.
</t>
<t><spanx style="verb">accountNotSupportedByMethod</spanx>: Returned if the <spanx style="emph">accountId</spanx> given corresponds to a valid account, but the account does not support this data type.
</t>
<t><spanx style="verb">requestTooLarge</spanx>: Returned if the number of <spanx style="emph">ids</spanx> requested by the client exceeds the maximum number the server is willing to process in a single method call.
</t>
<t><spanx style="verb">invalidArguments</spanx>: Returned if one of the arguments is of the wrong type, or otherwise invalid. A <spanx style="verb">description</spanx> property MAY be present on the response object to help debug with an explanation of what the problem was.
</t>
</section>

<section anchor="getfooupdates" title="getFooUpdates">
<t>When the state of the set of Foo records changes on the server (whether due to creation, updates or deletion), the <spanx style="emph">state</spanx> property of the <spanx style="emph">foos</spanx> response will change. The <spanx style="emph">getFooUpdates</spanx> call allows a client to efficiently update the state of any its Foo cache to match the new state on the server. It takes the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String|null</spanx>
The id of the Account to use. If <spanx style="verb">null</spanx>, the primary account is used.</t>
<t><spanx style="strong">sinceState</spanx>: <spanx style="verb">String</spanx>
The current state of the client. This is the string that was returned as the <spanx style="emph">state</spanx> argument in the <spanx style="emph">foos</spanx> response. The server will return the changes made since this state.</t>
<t><spanx style="strong">maxChanges</spanx>: <spanx style="verb">Number|null</spanx>
The maximum number of Foo ids to return in the response. The server MAY choose to return fewer than this value, but MUST NOT return more. If not given by the client, the server may choose how many to return. If supplied by the client, the value MUST be a positive integer greater than 0. If a value outside of this range is given, the server MUST reject the call with an <spanx style="verb">invalidArguments</spanx> error.</t>
<t><spanx style="strong">fetchRecords</spanx>: <spanx style="verb">Boolean|null</spanx>
If <spanx style="verb">true</spanx>, immediately after outputting the <spanx style="emph">fooUpdates</spanx> response, the server will make an implicit call to <spanx style="emph">getFoos</spanx> with the <spanx style="emph">changed</spanx> property of the response as the <spanx style="emph">ids</spanx> argument. If <spanx style="verb">false</spanx> or <spanx style="verb">null</spanx>, no implicit call will be made.</t>
<t><spanx style="strong">fetchRecordProperties</spanx>: <spanx style="verb">String[]|null</spanx>
If the <spanx style="emph">getFoos</spanx> method takes a <spanx style="emph">properties</spanx> argument, this argument is passed through on implicit calls (see the <spanx style="emph">fetchRecords</spanx> argument).</t>
</list>
</t>
<t>The response to <spanx style="emph">getFooUpdates</spanx> is called <spanx style="emph">fooUpdates</spanx>. It has the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String</spanx>
The id of the account used for the call.</t>
<t><spanx style="strong">oldState</spanx>: <spanx style="verb">String</spanx>
This is the <spanx style="emph">sinceState</spanx> argument echoed back; the state from which the server is returning changes.</t>
<t><spanx style="strong">newState</spanx>: <spanx style="verb">String</spanx>
This is the state the client will be in after applying the set of changes to the old state.</t>
<t><spanx style="strong">hasMoreUpdates</spanx>: <spanx style="verb">Boolean</spanx>
If <spanx style="verb">true</spanx>, the client may call <spanx style="emph">getFooUpdates</spanx> again with the <spanx style="emph">newState</spanx> returned to get further updates. If <spanx style="verb">false</spanx>, <spanx style="emph">newState</spanx> is the current server state.</t>
<t><spanx style="strong">changed</spanx>: <spanx style="verb">String[]</spanx>
An array of Foo ids for records which have been created or changed but not destroyed since the oldState.</t>
<t><spanx style="strong">removed</spanx>: <spanx style="verb">String[]</spanx>
An array of Foo ids for records which have been destroyed since the old state.</t>
</list>
</t>
<t>The <spanx style="emph">maxChanges</spanx> argument (and <spanx style="emph">hasMoreUpdates</spanx> response argument) is available for data types with potentially large amounts of data (i.e. those for which there is a <spanx style="emph">getFooList</spanx> method available for loading the data in pages).  If a <spanx style="emph">maxChanges</spanx> is supplied, or set automatically by the server, the server must try to limit the number of ids across <spanx style="emph">changed</spanx> and <spanx style="emph">removed</spanx> to the number given. If there are more changes than this between the client's state and the current server state, the update returned MUST take the client to an intermediate state, from which the client can continue to call <spanx style="emph">getFooUpdates</spanx> until it is fully up to date. The server MUST NOT return more ids than the <spanx style="emph">maxChanges</spanx> total. If the server is unable to calculate a suitable intermediate state, it MUST return a <spanx style="verb">cannotCalculateChanges</spanx> error.
</t>
<t>If a Foo record has been modified AND deleted since the oldState, the server SHOULD just return the id in the <spanx style="emph">removed</spanx> response, but MAY return it in the changed response as well. If a Foo record has been created AND deleted since the oldState, the server SHOULD remove the Foo id from the response entirely, but MAY include it in the <spanx style="emph">removed</spanx> response.
</t>
<t>The following errors may be returned instead of the <spanx style="emph">fooUpdates</spanx> response:
</t>
<t><spanx style="verb">accountNotFound</spanx>: Returned if an <spanx style="emph">accountId</spanx> was explicitly included with the request, but it does not correspond to a valid account.
</t>
<t><spanx style="verb">accountNotSupportedByMethod</spanx>: Returned if the <spanx style="emph">accountId</spanx> given corresponds to a valid account, but the account does not support this data type.
</t>
<t><spanx style="verb">invalidArguments</spanx>: Returned if the request does not include one of the required arguments, or one of the arguments is of the wrong type, or otherwise invalid. A <spanx style="emph">description</spanx> property MAY be present on the response object to help debug with an explanation of what the problem was.
</t>
<t><spanx style="verb">cannotCalculateChanges</spanx>: Returned if the server cannot calculate the changes from the state string given by the client. Usually due to the client's state being too old, or the server being unable to produce an update to an intermediate state when there are too many updates. The client MUST invalidate its Foo cache.
</t>
</section>

<section anchor="setfoos" title="setFoos">
<t>Modifying the state of Foo objects on the server is done via the <spanx style="emph">setFoos</spanx> method. This encompasses creating, updating and destroying Foo records. This has two benefits:
</t>
<t>
<list style="numbers">
<t>It allows the server to sort out ordering and dependencies that may exist if doing multiple operations at once (for example to ensure there is always a minimum number of a certain record type).</t>
<t>A single call can make all the changes you want to a particular type. If the client wants to use <spanx style="emph">ifInState</spanx> to guard its changes, it is only possible for it to make one call that modifies any particular type per request, since it will need the new state following that call to make the next modification.</t>
</list>
</t>
<t>The <spanx style="emph">setFoos</spanx> method takes the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String|null</spanx>
The id of the Account to use. If <spanx style="verb">null</spanx>, the primary account is used.</t>
<t><spanx style="strong">ifInState</spanx>: <spanx style="verb">String|null</spanx>
This is a state string as returned by the <spanx style="emph">getFoos</spanx> method. If supplied, the string must match the current state, otherwise the method will be aborted and a <spanx style="verb">stateMismatch</spanx> error returned. If <spanx style="verb">null</spanx>, any changes will be applied to the current state.</t>
<t><spanx style="strong">create</spanx>: <spanx style="verb">String[Foo]|null</spanx>
A map of <spanx style="emph">creation id</spanx> (an arbitrary string set by the client) to Foo objects (containing all properties except the id, unless otherwise stated in the specific documentation of the data type). If <spanx style="verb">null</spanx>, no objects will be created.</t>
<t><spanx style="strong">update</spanx>: <spanx style="verb">String[Foo]|null</spanx>
A map of id to Foo objects. The object may omit any property; only properties that have changed need be included. If <spanx style="verb">null</spanx>, no objects will be updated.</t>
<t><spanx style="strong">destroy</spanx>: <spanx style="verb">String[]|null</spanx>
A list of ids for Foo objects to permanently delete. If <spanx style="verb">null</spanx>, no objects will be deleted.</t>
</list>
</t>
<t>Each create, update or destroy is considered an atomic unit. It is permissible for the server to commit some of the changes but not others, however it is not permissible to only commit part of an update to a single record (e.g. update a <spanx style="emph">name</spanx> property but not a <spanx style="emph">count</spanx> property, if both are supplied in the update object).
</t>
<t>If a create, update or destroy is rejected, the appropriate error MUST be added to the notCreated/notUpdated/notDestroyed property of the response and the server MUST continue to the next create/update/destroy. It does not terminate the method.
</t>
<t>If an id given cannot be found, the update or destroy MUST be rejected with a <spanx style="verb">notFound</spanx> set error.
</t>
<t>Some record objects may hold references to others (foreign keys). When records are created or modified, they may reference other records being created <spanx style="emph">in the same API request</spanx> by using the creation id prefixed with a <spanx style="verb">#</spanx>. The order of the method calls in the request by the client MUST be such that the record being referenced is created in the same or an earlier call. The server thus never has to look ahead. Instead, while processing a request (a series of method calls), the server MUST keep a simple map for the duration of the request of creation id to record id for each newly created record, so it can substitute in the correct value if necessary in later method calls. The type
</t>
<t>Creation ids are scoped by type; a separate <spanx style="verb">creation id -&gt; id</spanx> map MUST be kept for each type. Foreign key references are always for a particular record type, so use of the same creation key in two different types cannot cause any ambiguity. Creation ids sent by the client SHOULD be unique within the single API request for a particular data type. If a creation id is reused for the same type, the server MUST map the creation id to the most recently created item with that id.
</t>
<t>The response to <spanx style="emph">setFoos</spanx> is called <spanx style="emph">foosSet</spanx>. It has the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String</spanx>
The id of the account used for the call.</t>
<t><spanx style="strong">oldState</spanx>: <spanx style="verb">String|null</spanx>
The state string that would have been returned by <spanx style="emph">getFoos</spanx> before making the requested changes, or <spanx style="verb">null</spanx> if the server doesn't know what the previous state string was.</t>
<t><spanx style="strong">newState</spanx>: <spanx style="verb">String</spanx>
The state string that will now be returned by <spanx style="emph">getFoos</spanx>.</t>
<t><spanx style="strong">created</spanx>: <spanx style="verb">String[Foo]</spanx>
A map of the creation id to an object containing any <spanx style="strong">server-assigned</spanx> properties of the Foo object (including the id) for all successfully created records.</t>
<t><spanx style="strong">updated</spanx>: <spanx style="verb">String[Foo|null]</spanx>
The <spanx style="emph">keys</spanx> in this map are the ids of all Foos that were successfully updated. Some data types may have properties which can only be determined by the server, and which may change as a result of the other properties being updated by the client. In this case, the <spanx style="emph">value</spanx> for the corresponding id in the map is an object containing the updated value of each property the <spanx style="strong">server changed</spanx> on the record. Otherwise (if no properties changed on the server other than those explicitly updated by the client), the value is <spanx style="verb">null</spanx>.</t>
<t><spanx style="strong">destroyed</spanx>: <spanx style="verb">String[]</spanx>
A list of Foo ids for records that were successfully destroyed.</t>
<t><spanx style="strong">notCreated</spanx>: <spanx style="verb">String[SetError]</spanx>
A map of creation id to a SetError object for each record that failed to be created. The possible errors are defined in the description of the method for specific data types.</t>
<t><spanx style="strong">notUpdated</spanx>: <spanx style="verb">String[SetError]</spanx>
A map of Foo id to a SetError object for each record that failed to be updated. The possible errors are defined in the description of the method for specific data types.</t>
<t><spanx style="strong">notDestroyed</spanx>: <spanx style="verb">String[SetError]</spanx>
A map of Foo id to a SetError object for each record that failed to be destroyed. The possible errors are defined in the description of the method for specific data types.</t>
</list>
</t>
<t>A <spanx style="strong">SetError</spanx> object has the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">type</spanx>: <spanx style="verb">String</spanx>
The type of error.</t>
<t><spanx style="strong">description</spanx>: <spanx style="verb">String|null</spanx>
A description of the error to display to the user.</t>
</list>
</t>
<t>Other properties may also be present on the object, as described in the relevant methods.
</t>
<t>The following errors may be returned instead of the <spanx style="verb">foosSet</spanx> response:
</t>
<t><spanx style="verb">accountNotFound</spanx>: Returned if an <spanx style="emph">accountId</spanx> was explicitly included with the request, but it does not correspond to a valid account.
</t>
<t><spanx style="verb">accountNotSupportedByMethod</spanx>: Returned if the <spanx style="emph">accountId</spanx> given corresponds to a valid account, but the account does not support this data type.
</t>
<t><spanx style="verb">accountReadOnly</spanx>: Returned if the account has isReadOnly == true.
</t>
<t><spanx style="verb">requestTooLarge</spanx>: Returned if the total number of objects to create, update or destroy exceeds the maximum number the server is willing to process in a single method call.
</t>
<t><spanx style="verb">invalidArguments</spanx>: Returned if one of the arguments is of the wrong type, or otherwise invalid. A <spanx style="verb">description</spanx> property MAY be present on the response object to help debug with an explanation of what the problem was.
</t>
<t><spanx style="verb">stateMismatch</spanx>: Returned if an <spanx style="verb">ifInState</spanx> argument was supplied and it does not match the current state.
</t>
</section>
</section>

<section anchor="querying-data" title="Querying data">
<t>For data sets where the total amount of data is expected to be very small, clients can just fetch the complete set of data and then do any sorting/filtering locally. However, for large data sets (e.g. multi-gigabyte mailboxes), the client needs to be able to perform a query on the server for the data type.
</t>

<section anchor="getfoolist" title="getFooList">
<t>A query on the set of Foos in an account is made by calling <spanx style="emph">getFooList</spanx>. This takes a number of arguments to determine which records to include, how they should be sorted, and which part of the result should be returned (the full list may be <spanx style="emph">very</spanx> long). The result is returned as a list of Foo ids. Optionally, the records themselves may be fetched at the same time.
</t>
<t>A call to <spanx style="emph">getFooList</spanx> takes the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">filter</spanx>: <spanx style="verb">FilterCondition</spanx>
Determines the set of Foos returned in the results. This is an <spanx style="verb">object</spanx>, whose allowed properties and semantics depend on the data type.</t>
<t><spanx style="strong">sort</spanx>: <spanx style="verb">String[]|null</spanx>
Lists the properties to compare between two Foo records to determine which comes first in the sort. If two Foo records have an identical value for the first property, the next property will be considered and so on. If all properties are the same (this includes the case where an empty array or <spanx style="verb">null</spanx> is given as the <spanx style="emph">sort</spanx> argument), the sort order is server-dependent, but MUST be stable between calls to <spanx style="verb">getFooList</spanx>.
Following each property name there MUST be a space and then either the string <spanx style="verb">asc</spanx> or <spanx style="verb">desc</spanx> to specify ascending or descending sort for that property. e.g. <spanx style="verb">[ "date desc", "name asc" ]</spanx></t>
<t><spanx style="strong">position</spanx>: <spanx style="verb">Number|null</spanx>
The 0-based index of the first id in the full list of results to return, presumed <spanx style="verb">0</spanx> if <spanx style="verb">null</spanx>. If a negative value is given, the call MUST be rejected with an <spanx style="verb">invalidArguments</spanx> error.</t>
<t><spanx style="strong">limit</spanx>: <spanx style="verb">Number|null</spanx>
The maximum number of results to return. If <spanx style="verb">null</spanx>, no limit presumed. The server MAY choose to enforce a maximum <spanx style="verb">limit</spanx> argument. In this case, if a greater value is given (or if it is <spanx style="verb">null</spanx>), the limit should be clamped to the maximum; since the total number of results in the list is returned, the client can determine if it has received all the results. If a negative value is given, the call MUST be rejected with an <spanx style="verb">invalidArguments</spanx> error.</t>
<t><spanx style="strong">fetchFoos</spanx>: <spanx style="verb">Boolean|null</spanx>
If <spanx style="verb">true</spanx> then after outputting a <spanx style="emph">fooList</spanx> response, an implicit call will be made to <spanx style="emph">getFoos</spanx> with the <spanx style="verb">fooIds</spanx> array in the response as the <spanx style="emph">ids</spanx> argument. If <spanx style="verb">false</spanx> or <spanx style="verb">null</spanx>, no implicit call will be made.</t>
<t><spanx style="strong">fetchFooProperties</spanx>: <spanx style="verb">String[]|null</spanx>
The list of properties to fetch on any fetched foos. See <spanx style="emph">getFoos</spanx> for a full description.</t>
</list>
</t>
<t>The response to a call to <spanx style="emph">getFooList</spanx> is called <spanx style="emph">fooList</spanx>. It has the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">filter</spanx>: <spanx style="verb">FilterCondition</spanx>
The filter of the foo list. Echoed back from the call.</t>
<t><spanx style="strong">sort</spanx>: <spanx style="verb">String[]|null</spanx>
A list of Foo property names used to sort by. Echoed back from the call.</t>
<t><spanx style="strong">state</spanx>: <spanx style="verb">String</spanx>
A string encoding the current state on the server. This string will change if the results of the Foo list MAY have changed (for example, there has been a change to the state of the set of Foos; it does not guarantee that anything in the list has changed). It may be passed to <spanx style="emph">getFooListUpdates</spanx> to efficiently get the set of changes from the client's current state.
Should a client receive back a response with a different state string to a previous call, it MUST either throw away the currently cached list and fetch it again (note, this does not require fetching the foos again, just the list of ids) or, call <spanx style="emph">getFooListUpdates</spanx> to get the delta difference.</t>
<t><spanx style="strong">canCalculateUpdates</spanx>: <spanx style="verb">Boolean</spanx>
This is <spanx style="verb">true</spanx> if the server supports calling <spanx style="emph">getFooListUpdates</spanx> with these <spanx style="verb">filter</spanx>/<spanx style="verb">sort</spanx> parameters. Note, this does not guarantee that the <spanx style="emph">getFooListUpdates</spanx> call will succeed, as it may only be possible for a limited time afterwards due to server internal implementation details.</t>
<t><spanx style="strong">position</spanx>: <spanx style="verb">Number</spanx>
The 0-based index of the first result in the <spanx style="verb">fooIds</spanx> array within the complete list of results.</t>
<t><spanx style="strong">total</spanx>: <spanx style="verb">Number</spanx>
The total number of foos in the foos list (given the <spanx style="emph">filter</spanx>).</t>
<t><spanx style="strong">fooIds</spanx>: <spanx style="verb">String[]</spanx>
The list of Foo ids for each foo in the list after filtering and sorting, starting at the index given by the <spanx style="emph">position</spanx> argument of this response, and continuing until it hits the end of the list or reaches the <spanx style="verb">limit</spanx> number of ids.</t>
</list>
</t>
<t>The following errors may be returned instead of the <spanx style="verb">fooList</spanx> response:
</t>
<t><spanx style="verb">accountNotFound</spanx>: Returned if an <spanx style="emph">accountId</spanx> was explicitly included with the request, but it does not correspond to a valid account.
</t>
<t><spanx style="verb">accountNotSupportedByMethod</spanx>: Returned if the <spanx style="emph">accountId</spanx> given corresponds to a valid account, but the account does not support this data type.
</t>
<t><spanx style="verb">invalidArguments</spanx>: Returned if the request does not include one of the required arguments, or one of the arguments is of the wrong type, or otherwise invalid. A <spanx style="verb">description</spanx> property MAY be present on the response object to help debug with an explanation of what the problem was.
</t>
</section>

<section anchor="getfoolistupdates" title="getFooListUpdates">
<t>The <spanx style="verb">getFooListUpdates</spanx> call allows a client to efficiently update the state of any cached foo list to match the new state on the server. It takes the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">filter</spanx>: <spanx style="verb">FilterCondition</spanx>
The filter argument that was used with <spanx style="emph">getFooList</spanx>.</t>
<t><spanx style="strong">sort</spanx>: <spanx style="verb">String[]|null</spanx>
The sort argument that was used with <spanx style="emph">getFooList</spanx>.</t>
<t><spanx style="strong">sinceState</spanx>: <spanx style="verb">String</spanx>
The current state of the client. This is the string that was returned as the <spanx style="emph">state</spanx> argument in the <spanx style="emph">fooList</spanx> response. The server will return the changes made since this state.</t>
<t><spanx style="strong">maxChanges</spanx>: <spanx style="verb">Number|null</spanx>
The maximum number of changes to return in the response. See below for a more detailed description.</t>
</list>
</t>
<t>The response to <spanx style="emph">getFooListUpdates</spanx> is called <spanx style="emph">fooListUpdates</spanx> It has the following arguments:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">filter</spanx>: <spanx style="verb">FilterCondition</spanx>
The filter of the foo list. Echoed back from the call.</t>
<t><spanx style="strong">sort</spanx>: <spanx style="verb">String[]|null</spanx>
A list of Foo property names used to sort by. Echoed back from the call.</t>
<t><spanx style="strong">oldState</spanx>: <spanx style="verb">String</spanx>
This is the <spanx style="verb">sinceState</spanx> argument echoed back; the state from which the server is returning changes.</t>
<t><spanx style="strong">newState</spanx>: <spanx style="verb">String</spanx>
This is the state the client will be in after applying the set of changes to the old state.</t>
<t><spanx style="strong">total</spanx>: <spanx style="verb">Number</spanx>
The total number of foos in the current foo list (given the <spanx style="emph">filter</spanx>).</t>
<t><spanx style="strong">removed</spanx>: <spanx style="verb">String[]</spanx>
The <spanx style="emph">fooId</spanx> for every foo that was in the list in the old state and is not in the list in the new state. If the server cannot calculate this exactly, the server MAY return extra foos in addition that MAY have been in the old list but are not in the new list.
If the <spanx style="emph">filter</spanx> or <spanx style="emph">sort</spanx> includes a mutable property, the server MUST include all foos in the current list for which this property MAY have changed.</t>
<t><spanx style="strong">added</spanx>: <spanx style="verb">AddedItem[]</spanx>
The fooId and index in the list (in the new state) for every foo that has been added to the list since the old state AND every foo in the current list that was included in the <spanx style="emph">removed</spanx> array (due to a filter or sort based upon a mutable property). The array MUST be sorted in order of index, lowest index first.</t>
</list>
</t>
<t>An <spanx style="strong">AddedItem</spanx> object has the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">fooId</spanx>: <spanx style="verb">String</spanx></t>
<t><spanx style="strong">index</spanx>: <spanx style="verb">Number</spanx></t>
</list>
</t>
<t>The result of this should be that if the client has a cached sparse array of foo ids in the list in the old state:
</t>

<figure align="center"><artwork align="center">
fooIds = [ "id1", "id2", null, null, "id3", "id4", null, null, null ]
</artwork></figure>
<t>then if it <spanx style="strong">splices out</spanx> all foos in the removed array:
</t>

<figure align="center"><artwork align="center">
removed = [ "id2", … ];
fooIds =&gt; [ "id1", null, null, "id3", "id4", null, null, null ]
</artwork></figure>
<t>and <spanx style="strong">splices in</spanx> (in order) all of the foos in the added array:
</t>

<figure align="center"><artwork align="center">
added = [{ fooId: "id5", index: 0, … }];
fooIds =&gt; [ "id5", "id1", null, null, "id3", "id4", null, null, null ]
</artwork></figure>
<t>then the foo list will now be in the new state.
</t>
<t>The following errors may be returned instead of the <spanx style="verb">fooListUpdates</spanx> response:
</t>
<t><spanx style="verb">accountNotFound</spanx>: Returned if an <spanx style="emph">accountId</spanx> was explicitly included with the request, but it does not correspond to a valid account.
</t>
<t><spanx style="verb">accountNotSupportedByMethod</spanx>: Returned if the <spanx style="emph">accountId</spanx> given corresponds to a valid account, but the account does not support this data type.
</t>
<t><spanx style="verb">invalidArguments</spanx>: Returned if the request does not include one of the required arguments, or one of the arguments is of the wrong type, or otherwise invalid. A <spanx style="emph">description</spanx> property MAY be present on the response object to help debug with an explanation of what the problem was.
</t>
<t><spanx style="verb">tooManyChanges</spanx>: Returned if there are more changes the the client's <spanx style="emph">maxChanges</spanx> argument. Each item in the removed or added array is considered as one change. The client may retry with a higher max changes or invalidate its cache of the foo list.
</t>
<t><spanx style="verb">cannotCalculateChanges</spanx>: Returned if the server cannot calculate the changes from the state string given by the client. Usually due to the client's state being too old. The client MUST invalidate its cache of the foo list.
</t>
</section>
</section>
</section>

<section anchor="downloading-binary-data" title="Downloading binary data">
<t>Binary data is referenced by a <spanx style="emph">blobId</spanx> in JMAP. A blob id does not have a name inherent to it, but this is normally given in the same object that contains the blob id.
</t>
<t>After completing authentication, the client will receive a <spanx style="emph">downloadUrl</spanx> as part of the response. This is in <xref target="RFC6570"/> URI Template (level 1) format. The URL MUST contain variables called <spanx style="verb">accountId</spanx> and <spanx style="verb">blobId</spanx>. The URL SHOULD contain a variable called <spanx style="verb">name</spanx>.
</t>
<t>The client may use this template in combination with an accountId and blobId to download any binary data (files) referenced by other objects. Since a blob is not associated with a particular name, the template SHOULD allow a name to be substituted in as well; the server will return this as the filename if it sets a <spanx style="verb">Content-Disposition</spanx> header.
</t>
<t>To download the data the client MUST make an authenticated GET request to the download URL with the appropriate variables substituted in, and then follow any redirects. The client SHOULD send an <spanx style="verb">Accept</spanx> header with the content type they would like the server to return for the file.
</t>
<t>In situations where it's not easy to authenticate the download request (e.g.: when downloading a file through a link in a HTML document), the client MAY use a signed GET request (see the authentication chapter for how to issue a signed request). Instead of specifying an <spanx style="verb">Accept</spanx> header, the client SHOULD add an <spanx style="verb">accept</spanx> query parameter to the signed URL, with the value being the content type to use for the response.
</t>
<t>After following redirects, the server MUST return one of the following responses to a request to the download URL:
</t>

<section anchor="ok-1" title="200: OK">
<t>Request successful. The binary data is returned. The <spanx style="verb">Content-Type</spanx> header SHOULD be set to the type as requested in the <spanx style="verb">Accept</spanx> header by the client, or <spanx style="verb">application/octet-stream</spanx> if unknown and no <spanx style="verb">Accept</spanx> header given.
</t>
</section>

<section anchor="unauthorized-2" title="401: Unauthorized">
<t>The <spanx style="verb">Authorization</spanx> header was missing or did not contain a valid token and there was no <spanx style="verb">access_token</spanx> query parameter, or it did not contain a valid token. Reauthenticate and then retry the request. As per the HTTP spec, the response MUST have a <spanx style="verb">WWW-Authenticate</spanx> header listing the available authentication schemes.
</t>
<t>The server MAY return an HTML page response, which clients MAY show to the user. This is primarily for when the URL is passed off to the browser, and the JMAP client may not see the actual response.
</t>
</section>

<section anchor="not-found-3" title="404: Not Found">
<t>The file was not found at this address.
</t>
</section>

<section anchor="service-unavailable-3" title="503: Service Unavailable">
<t>The server is currently down. The client should try again later with exponential backoff. There is no content in the response.
</t>
</section>
</section>

<section anchor="uploading-binary-data" title="Uploading binary data">
<t>There is a single endpoint which handles all file uploads, regardless of what they are to be used for. To upload a file, the client submits a POST request to the file upload endpoint (see the authentication section for information on how to obtain this URL). The Content-Type MUST be correctly set for the type of the file being uploaded. The request MUST be authenticated as per any HTTP request. The request MAY include an <spanx style="verb">X-JMAP-AccountId</spanx> header, with the value being the account to use for the request. Otherwise, the default account will be used.
</t>
<t>The server will respond with one of the following HTTP response codes:
</t>

<section anchor="file-uploaded-successfully" title="201: File uploaded successfully">
<t>The content of the response is a single JSON object with the following properties:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">accountId</spanx>: <spanx style="verb">String</spanx>
The id of the account used for the call.</t>
<t><spanx style="strong">blobId</spanx>: <spanx style="verb">String</spanx>,
The id representing the binary data uploaded. The data for this id is immutable. The id <spanx style="emph">only</spanx> refers to the binary data, not any metadata.</t>
<t><spanx style="strong">type</spanx>: <spanx style="verb">String</spanx>
The content type of the file.</t>
<t><spanx style="strong">size</spanx>: <spanx style="verb">Number</spanx>
The size of the file in bytes.</t>
<t><spanx style="strong">expires</spanx>: <spanx style="verb">Date</spanx>
The date the file will be deleted from temporary storage if not referenced by another object, e.g. used in a draft.</t>
</list>
</t>
<t>Once the file has been used, for example attached to a draft message, the file will no longer expire, and is instead guaranteed to exist while at least one other object references it. Once no other object references it, the server MAY immediately delete the file at any time. It MUST NOT delete the file during the method call which removed the last reference, so that if there is a create and a delete within the same call that both reference the file, this always works.
</t>
<t>If uploading a file would take the user over quota, the server SHOULD delete previously uploaded (but unused) files before their expiry time. This means a client does not have to explicitly delete unused temporary files (indeed, there is no way for it to do so).
</t>
<t>If identical binary content is uploaded, the same <spanx style="emph">blobId</spanx> SHOULD be returned.
</t>
<t>The server MUST return one of the following responses to a request to the upload URL:
</t>
</section>

<section anchor="bad-request-1" title="400: Bad request">
<t>The request was malformed (this includes the case where an <spanx style="verb">X-JMAP-AccountId</spanx> header is sent with a value that does not exist). The client SHOULD NOT retry the same request. There is no content in the response.
</t>
</section>

<section anchor="unauthorized-3" title="401: Unauthorized">
<t>The <spanx style="verb">Authorization</spanx> header was missing or did not contain a valid token. Reauthenticate and then retry the request. As per the HTTP spec, the response MUST have a <spanx style="verb">WWW-Authenticate</spanx> header listing the available authentication schemes. There is no content in the response.
</t>
</section>

<section anchor="not-found-4" title="404: Not Found">
<t>The upload endpoint has moved. See the Authentication section of the spec for how to rediscover the current URL to use. There is no content in the response.
</t>
</section>

<section anchor="request-entity-too-large" title="413: Request Entity Too Large">
<t>The file is larger than the maximum size the server is willing to accept for a single file. The client SHOULD NOT retry uploading the same file. There is no content in the response. The client may discover the maximum size the server is prepared to accept by inspecting the server <spanx style="emph">capabilities</spanx> object, returned with the successful authentication response.
</t>
</section>

<section anchor="unsupported-media-type" title="415: Unsupported Media Type">
<t>The server MAY choose to not allow certain content types to be uploaded, such as executable files. This error response is returned if an unacceptable type is uploaded. The client SHOULD NOT retry uploading the same file. There is no content in the response.
</t>

<section anchor="rate-limited-2" title="429: Rate limited">
<t>Returned if the client has made too many upload requests recently, or has too many concurrent uploads currently in progress. Clients SHOULD wait a while then try again. The response MAY include a <spanx style="verb">Retry-After</spanx> header indicating how long to wait before making a new request.
</t>
</section>
</section>

<section anchor="service-unavailable-4" title="503: Service Unavailable">
<t>The server is currently down. The client should try again later with exponential backoff. There is no content in the response.
</t>
</section>
</section>

<section anchor="push" title="Push">
<t>Any modern email client should be able to update instantly whenever the data on the server is changed by another client or message delivery. Push notifications in JMAP occur out-of-band (i.e. not over the same connection as API exchanges) so that they can make use of efficient native push mechanisms on different platforms.
</t>
<t>The general model for push is simple and does not send any sensitive data over the push channel, making it suitable for use with less trusted 3rd party intermediaries. The format allows multiple changes to be coalesced into a single push update, and the frequency of pushes to be rate limited by the server. It doesn't matter if some push events are dropped before they reach the client; it will still get all changes next time it syncs.
</t>
<t>When something changes on the server, the server pushes a small JSON object to the client with the following property:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">changed</spanx>: <spanx style="verb">String[ChangedStates]</spanx>
A map of <spanx style="emph">account id</spanx> to an object encoding the state of data types which have changed for that account since the last push event, for each of the accounts to which the user has access and for which something has changed.</t>
</list>
</t>
<t>A <spanx style="strong">ChangedStates</spanx> object is a map. The keys are the plural type name <spanx style="verb">Foos</spanx> (e.g. &quot;Mailboxes&quot; or &quot;Messages&quot;), and the value is the <spanx style="emph">state</spanx> property that would currently be returned by a call to <spanx style="emph">getFoos</spanx>.
</t>
<t>Upon receiving this data, the client can compare the new state strings with its current values to see whether it has the current data for these types. The actual changes can then be efficiently fetched in a single standard API request (using the <spanx style="emph">getFooUpdates</spanx> type methods).
</t>

<section anchor="event-source" title="Event Source">
<t>There are two mechanisms by which the client can receive the push events. The first is directly via a <spanx style="verb">text/event-stream</spanx> resource, as described in
<eref target="http://www.w3.org/TR/eventsource/"/>. This is essentially a long running HTTP request down which the server can push data. When a change occurs, the server MUST push an event called <spanx style="strong">state</spanx> to any connected clients.
</t>
<t>The server MAY also set a new <spanx style="verb">Last-Event-Id</spanx> that encodes the entire server state visible to the user. When a new connection is made to the event-source endpoint, the server can then work out whether the client has missed some changes which it should send immediately.
</t>
<t>The server MUST also send an event called <spanx style="strong">ping</spanx> with an empty object as the data if a maximum of 5 minutes has elapsed since the previous event. This MUST NOT set a new <spanx style="verb">Last-Event-Id</spanx>. A client may detect the absence of these to determine that the HTTP connection has been dropped somewhere along the route and so it needs to re-establish the connection.
</t>
<t>Refer to the Authentication section of this spec for details on how to get the URL for the event-source endpoint. The request must be authenticated using an <spanx style="verb">Authorization</spanx> header like any HTTP request.
</t>
<t>A client MAY hold open multiple connections to the event-source, although it SHOULD try to use a single connection for efficiency.
</t>
</section>

<section anchor="web-hook" title="Web hook">
<t>The second push mechanism is to register a callback URL to which the JMAP server will make an HTTPS POST request whenever the event occurs. The request MUST have a content type of <spanx style="verb">application/json</spanx> and contain the same UTF-8 JSON encoded object as described above as the body.
</t>
<t>The JMAP server MUST also set the following headers in the POST request:
- <spanx style="verb">X-JMAP-EventType: state</spanx>
- <spanx style="verb">X-JMAP-User: ${username}</spanx> where <spanx style="verb">${username}</spanx> is the username of the authenticated user for which the push event occurred.
</t>
<t>The JMAP server MUST follow any redirects. If the final response code from the server is <spanx style="verb">2xx</spanx>, the callback is considered a success. If the response code is <spanx style="verb">503</spanx> (Service Unavailable), the JMAP server MAY try again later (but may also just drop the event). If the response code is <spanx style="verb">429</spanx> (Too Many Requests) the JMAP server SHOULD attempt to reduce the frequency of pushes to that URL. Any other response code MUST be considered a <spanx style="strong">permanent failure</spanx> and the callback should be deregistered (not tried again even for future events unless explicitly re-registered by the client).
</t>
<t>The URL set by the client MUST use the HTTPS protocol and SHOULD encode within it a unique token that can be verified by the server to know that the request comes from the JMAP server the authenticated client connected to.
</t>
<t>The callback is tied to the access token used to create it. Should the access token expire or be revoked, the callback MUST be removed by the JMAP server. The client MUST re-register the callback after reauthenticating to resume callbacks.
</t>
<t>Each session may only have a single callback URL registered. It can be set or retrieved using the following API calls.
</t>

<section anchor="setpushcallback" title="setPushCallback">
<t>To set the web hook, make a call to <spanx style="emph">setPushCallback</spanx>. It takes the following argument:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">callback</spanx>: <spanx style="verb">String|null</spanx>
The (HTTPS) URL the JMAP server should POST events to. This will replace any previously set URL. Set to <spanx style="verb">null</spanx> to just remove any previously set callback URL.</t>
</list>
</t>
<t>The response to <spanx style="emph">setPushCallback</spanx> is called <spanx style="emph">pushCallbackSet</spanx>. It has the following argument:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">callback</spanx>: <spanx style="verb">String|null</spanx>
Echoed back from the call.</t>
</list>
</t>
<t>The following error may be returned instead of the <spanx style="emph">mailboxesSet</spanx> response:
</t>
<t><spanx style="verb">invalidUrl</spanx>: Returned if the URL does not begin with <spanx style="verb">https://</spanx>, or is otherwise syntactically invalid or does not resolve.
</t>
</section>

<section anchor="getpushcallback" title="getPushCallback">
<t>To check the currently set callback URL (if any), make a call to <spanx style="emph">getPushCallback</spanx>. It does not take any arguments. The response to <spanx style="emph">getPushCallback</spanx> is called <spanx style="verb">pushCallback</spanx>. It has a single argument:
</t>
<t>
<list style="symbols">
<t><spanx style="strong">callback</spanx>: <spanx style="verb">String|null</spanx>
The URL the JMAP server is currently posting push events to, or <spanx style="verb">null</spanx> if none.</t>
</list>
</t>
</section>
</section>
</section>

</middle>
<back>
<references title="Normative References">
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.2119.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.3339.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.3629.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.4648.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.5785.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6186.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6570.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6750.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6764.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.7159.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.7493.xml"?>
<?rfc include="http://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.7519.xml"?>
</references>

</back>
</rfc>
