# Updates and download links

This guide adds an update check to your application and puts download links on your download page. At the end, your application finds, downloads and verifies a new release. Each link on your download page leads to the newest release.

## Before you start

- A [product](../../../concepts/products/) with a published release that has a file for each platform. See [Publish a release](../publish-a-release/).
- Your application verifies signed responses. It embeds your public key and has the `verifyResponse` function. See [Verify signed responses](../../signatures/verify-signed-responses/).
- For a product with the `licensed` [distribution](../../../concepts/products/#distribution) setting, your application stores the license key. See [Add your application](../../licensing/add-your-application/). An `open` product does not need a license key.

The examples call `https://dist.seatify.dev`. In curl, the product ID, the license key and the key ID of your signing key are the variables `$PRODUCT_ID`, `$LICENSE_KEY` and `$SEATIFY_SIGNING_KEY_ID`. In the other languages, they are variables of your application.

## Update your application

{{% steps %}}

### Check for an update

Send the version that your application runs, with its platform and its architecture. The version is a semantic version without a `v` prefix. Send the platform and the architecture together, or leave out both. See [Platforms and architectures](../../../concepts/releases-and-artifacts/#platforms-and-architectures).

If a release has several files for one platform, such as a `.dmg` and a `.zip`, add `filetype`, such as `filetype=dmg`.

Send the nonce and the key ID too, and verify the answer before your application uses it. Your application trusts the SHA-256 of the file only from a verified answer.

{{< tabs >}}
{{< tab name="curl" >}}
```bash
curl "https://dist.seatify.dev/v1/products/$PRODUCT_ID/update?version=1.1.0&platform=darwin&arch=arm64" \
  -H "Seatify-License-Key: $LICENSE_KEY" \
  -H "Seatify-Signing-Key: $SEATIFY_SIGNING_KEY_ID" \
  -H "Seatify-Nonce: $(uuidgen)"
```
{{< /tab >}}
{{< tab name="Swift" >}}
```swift
struct UpdateCheck: Decodable {
    struct Update: Decodable {
        struct Artifact: Decodable {
            let filename: String
            let sha256: String
            let signature: String?
            let signingKeyId: String?
            let url: String
        }

        let version: String
        let name: String?
        let notes: String?
        let artifact: Artifact?
    }

    let valid: Bool
    let reason: String?
    let update: Update?
}

let nonce = UUID().uuidString

var components = URLComponents(string: "https://dist.seatify.dev/v1/products/\(productID)/update")!
components.queryItems = [
    URLQueryItem(name: "version", value: currentVersion),
    URLQueryItem(name: "platform", value: "darwin"),
    URLQueryItem(name: "arch", value: "arm64"),
]

var request = URLRequest(url: components.url!)
request.setValue(licenseKey, forHTTPHeaderField: "Seatify-License-Key")
request.setValue(signingKeyID, forHTTPHeaderField: "Seatify-Signing-Key")
request.setValue(nonce, forHTTPHeaderField: "Seatify-Nonce")

let (data, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse else { throw InvalidSignature() }
let body = try verifyResponse(request, nonce: nonce, data: data, response: response)

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let check = try decoder.decode(UpdateCheck.self, from: body)
```
{{< /tab >}}
{{< tab name="C#" >}}
```csharp
using System.Text.Json;

var nonce = Guid.NewGuid().ToString();

using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get,
    $"https://dist.seatify.dev/v1/products/{productId}/update?version={currentVersion}&platform=darwin&arch=arm64");
request.Headers.Add("Seatify-License-Key", licenseKey);
request.Headers.Add("Seatify-Signing-Key", signingKeyId);
request.Headers.Add("Seatify-Nonce", nonce);

using var response = await client.SendAsync(request);
var body = await VerifyResponse(response, nonce);

var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
var check = JsonSerializer.Deserialize<UpdateCheck>(body, options);

record UpdateCheck(bool Valid, string? Reason, Update? Update);
record Update(string Version, string? Name, string? Notes, Artifact? Artifact);
record Artifact(string Filename, string Sha256, string? Signature, string? SigningKeyId, string Url);
```
{{< /tab >}}
{{< tab name="Go" >}}
```go
type updateArtifact struct {
	Filename     string `json:"filename"`
	SHA256       string `json:"sha256"`
	Signature    string `json:"signature"`
	SigningKeyID string `json:"signing_key_id"`
	URL          string `json:"url"`
}

nonce := rand.Text()
query := url.Values{
	"version":  {currentVersion},
	"platform": {"darwin"},
	"arch":     {"arm64"},
}

req, err := http.NewRequest("GET", "https://dist.seatify.dev/v1/products/"+productID+"/update?"+query.Encode(), nil)
if err != nil {
	return err
}
req.Header.Set("Seatify-License-Key", licenseKey)
req.Header.Set("Seatify-Signing-Key", signingKeyID)
req.Header.Set("Seatify-Nonce", nonce)

res, err := http.DefaultClient.Do(req)
if err != nil {
	return err
}
defer res.Body.Close()

body, err := verifyResponse(res, nonce)
if err != nil {
	return err
}

var check struct {
	Valid  bool    `json:"valid"`
	Reason *string `json:"reason"`
	Update *struct {
		Version  string          `json:"version"`
		Name     *string         `json:"name"`
		Notes    *string         `json:"notes"`
		Artifact *updateArtifact `json:"artifact"`
	} `json:"update"`
}
err = json.Unmarshal(body, &check)
```
{{< /tab >}}
{{< tab name="JavaScript" >}}
```javascript
const nonce = crypto.randomUUID();
const query = new URLSearchParams({ version: currentVersion, platform: "darwin", arch: "arm64" });
const url = `https://dist.seatify.dev/v1/products/${productId}/update?${query}`;

const response = await fetch(url, {
  headers: {
    "Seatify-License-Key": licenseKey,
    "Seatify-Signing-Key": signingKeyId,
    "Seatify-Nonce": nonce,
  },
});
const check = await verifyResponse("GET", url, nonce, response);
```
{{< /tab >}}
{{< /tabs >}}

The answer offers the newer release in `update`. See [Check the update](../publish-a-release/#check-the-update) for a full answer. Your application uses these fields:

| Field | Description |
| --- | --- |
| `update.version` | The version to install. |
| `update.name`, `update.notes` | The name and the release notes. Your application can show them to the user. |
| `update.artifact` | The file for the platform, the architecture and the file type of the check. It is `null` when several files of the release match. A check without a platform matches every file. Then choose a file from `update.artifacts`. |
| `update.artifact.url` | The address to download the file from. |
| `update.artifact.sha256`, `update.artifact.signature`, `update.artifact.signing_key_id` | The values that verify the file. |

When your application runs the newest version that it can install, `update` is `null`:

```json
{
  "valid": true,
  "reason": null,
  "current": "1.2.0",
  "update": null
}
```

### Download the file

Request `update.artifact.url` with the license key. The answer is a redirect with the status 303 to a signed download link. Your HTTP client follows the redirect.

Check the status before you save the file. A refused download answers a status other than 200. See [Handle the answer](#handle-the-answer).

{{< tabs >}}
{{< tab name="curl" >}}
```bash
curl --fail --location --remote-name \
  -H "Seatify-License-Key: $LICENSE_KEY" \
  "https://dist.seatify.dev/v1/products/$PRODUCT_ID/releases/1.2.0/artifacts/BEACON-1.2.0-universal.dmg"
```
{{< /tab >}}
{{< tab name="Swift" >}}
```swift
struct DownloadFailed: Error {}

guard let artifact = check.update?.artifact else { return }

var request = URLRequest(url: URL(string: artifact.url)!)
request.setValue(licenseKey, forHTTPHeaderField: "Seatify-License-Key")

let (fileURL, response) = try await URLSession.shared.download(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw DownloadFailed() }
```
{{< /tab >}}
{{< tab name="C#" >}}
```csharp
var artifact = check?.Update?.Artifact;
if (artifact is null)
    return;

using var download = new HttpRequestMessage(HttpMethod.Get, artifact.Url);
download.Headers.Add("Seatify-License-Key", licenseKey);

using var file = await client.SendAsync(download, HttpCompletionOption.ResponseHeadersRead);
file.EnsureSuccessStatusCode();

await using (var output = File.Create(path))
{
    await file.Content.CopyToAsync(output);
}
```
{{< /tab >}}
{{< tab name="Go" >}}
```go
if check.Update == nil || check.Update.Artifact == nil {
	return nil
}

req, err = http.NewRequest("GET", check.Update.Artifact.URL, nil)
if err != nil {
	return err
}
req.Header.Set("Seatify-License-Key", licenseKey)

download, err := http.DefaultClient.Do(req)
if err != nil {
	return err
}
defer download.Body.Close()

if download.StatusCode != http.StatusOK {
	return fmt.Errorf("the download failed with the status %d", download.StatusCode)
}

file, err := os.Create(path)
if err != nil {
	return err
}
defer file.Close()

_, err = io.Copy(file, download.Body)
```
{{< /tab >}}
{{< tab name="JavaScript" >}}
```javascript
const artifact = check.update?.artifact;
if (!artifact) {
  return;
}

const download = await fetch(artifact.url, {
  headers: { "Seatify-License-Key": licenseKey },
});
if (!download.ok) {
  throw new Error(`The download failed with the status ${download.status}.`);
}
const file = await download.arrayBuffer();
```
{{< /tab >}}
{{< /tabs >}}

The redirect is not signed. Your application checks the file itself in the next step.

### Verify the file

Verify the file before your application installs it. If a check fails, delete the file.

1. Compute the SHA-256 of the file in lower-case hex. It must equal `update.artifact.sha256`.
2. Find the embedded public key that has the key ID in `signing_key_id`.
3. Check the Ed25519 signature in `signature` with this key. The signed message is the text `artifact/` followed by the SHA-256 from check 1. The signature is in standard Base64.

If no embedded key has the key ID, the SHA-256 check is enough. The SHA-256 came in an answer that your application verified. This happens after you rotate signing keys. See [Updates across a rotation](../../signatures/rotate-signing-keys/#updates-across-a-rotation).

{{< tabs >}}
{{< tab name="curl" >}}
This step runs inside your application. Choose a language tab to see the code.
{{< /tab >}}
{{< tab name="Swift" >}}
```swift
import CryptoKit
import Foundation

struct InvalidFile: Error {}

func verifyFile(at fileURL: URL, artifact: UpdateCheck.Update.Artifact) throws {
    let file = try Data(contentsOf: fileURL)
    let sha256 = SHA256.hash(data: file).map { String(format: "%02x", $0) }.joined()
    guard sha256 == artifact.sha256 else { throw InvalidFile() }

    guard let keyID = artifact.signingKeyId, let encodedKey = publicKeys[keyID] else { return }

    guard let keyData = Data(base64Encoded: encodedKey),
          let signature = artifact.signature.flatMap({ Data(base64Encoded: $0) })
    else { throw InvalidFile() }

    let publicKey = try Curve25519.Signing.PublicKey(rawRepresentation: keyData)
    guard publicKey.isValidSignature(signature, for: Data("artifact/\(sha256)".utf8)) else { throw InvalidFile() }
}
```
{{< /tab >}}
{{< tab name="C#" >}}
```csharp
using System.Security.Cryptography;
using System.Text;
using NSec.Cryptography;

void VerifyFile(string path, Artifact artifact)
{
    var sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))).ToLowerInvariant();
    if (sha256 != artifact.Sha256)
        throw new InvalidDataException("The file is not valid.");

    if (artifact.SigningKeyId is null || !publicKeys.TryGetValue(artifact.SigningKeyId, out var encodedKey))
        return;

    var publicKey = PublicKey.Import(SignatureAlgorithm.Ed25519, Convert.FromBase64String(encodedKey), KeyBlobFormat.RawPublicKey);
    var message = Encoding.UTF8.GetBytes("artifact/" + sha256);
    if (artifact.Signature is null
        || !SignatureAlgorithm.Ed25519.Verify(publicKey, message, Convert.FromBase64String(artifact.Signature)))
        throw new InvalidDataException("The file is not valid.");
}
```
{{< /tab >}}
{{< tab name="Go" >}}
```go
var errInvalidFile = errors.New("the file is not valid")

func verifyFile(path string, artifact *updateArtifact) error {
	file, err := os.ReadFile(path)
	if err != nil {
		return err
	}

	fileHash := sha256.Sum256(file)
	digest := hex.EncodeToString(fileHash[:])
	if digest != artifact.SHA256 {
		return errInvalidFile
	}

	encodedKey, found := publicKeys[artifact.SigningKeyID]
	if !found {
		return nil
	}

	publicKey, err := base64.StdEncoding.DecodeString(encodedKey)
	if err != nil {
		return errInvalidFile
	}
	signature, err := base64.StdEncoding.DecodeString(artifact.Signature)
	if err != nil {
		return errInvalidFile
	}

	if !ed25519.Verify(publicKey, []byte("artifact/"+digest), signature) {
		return errInvalidFile
	}

	return nil
}
```
{{< /tab >}}
{{< tab name="JavaScript" >}}
```javascript
async function verifyFile(file, artifact) {
  const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", file));
  const sha256 = Array.from(hash, (byte) => byte.toString(16).padStart(2, "0")).join("");
  if (sha256 !== artifact.sha256) {
    throw new Error("The file is not valid.");
  }

  const encodedKey = publicKeys[artifact.signing_key_id];
  if (!encodedKey) {
    return;
  }

  const publicKey = await crypto.subtle.importKey("raw", fromBase64(encodedKey), { name: "Ed25519" }, false, ["verify"]);
  const verified = await crypto.subtle.verify(
    { name: "Ed25519" },
    publicKey,
    fromBase64(artifact.signature ?? ""),
    encoder.encode(`artifact/${sha256}`),
  );
  if (!verified) {
    throw new Error("The file is not valid.");
  }
}
```
{{< /tab >}}
{{< /tabs >}}

### Install the update

Install the file only after both checks pass. The installation depends on your platform and your installer.

{{% /steps %}}

## Handle the answer

The update check answers every licensing outcome with the status 200, a refusal too. A download answers a refusal with an HTTP status instead. An HTTP client that follows a download would otherwise save the refusal as the file.

| Answer | Answered by | What your application does |
| --- | --- | --- |
| `update` is `null` | Update check | No action is needed. Your application runs the newest version that it can install. |
| `update.artifact` is `null` | Update check | Add `filetype` to the check, or choose a file from `update.artifacts`. |
| `suspended` | Update check, and download with the status 403 | Tell the user that the license is suspended. |
| `expired` | Update check, and download with the status 403 | Tell the user that the license has expired. The [After expiry](../../../concepts/policies/#after-expiry) rule of the policy ends access to releases. |
| `product_mismatch` | Update check, and download with the status 403 | The key belongs to another product. Ask the user for the right key. |
| `release_not_covered` | Download with the status 403 | The license has expired, and the release was published after the expiry date. The update check never offers such a release. |

The reason is in the `reason` field of the answer, also for a 403. Other statuses mean that the request itself is wrong:

| Status | Cause |
| --- | --- |
| 400 | The query is not valid. The `errors` field names each field that is wrong. |
| 401 | The license key is missing on a `licensed` product, or the key is not valid. |
| 404 | Download only. The release or the file does not exist, or the release is a draft or yanked. |
| 429 | Your application sent too many requests. Try again later. |

## Beta and version lines

The update check stays in the channel of the version that your application runs. A beta build sees beta, release candidate and stable releases. A stable build sees only stable releases. See [Channels](../../../concepts/releases-and-artifacts/#channels).

- To let the user join the beta, send `channel=beta` with the check.
- To let the user leave the beta, send `channel=stable`. Your application keeps its beta build until a stable release with a higher version is published. For example, `1.3.0` is higher than `1.3.0-beta.2`.
- To keep your application on one major version, send `constraint=2`. The check then offers only `2.x.y` versions. Use it when version 3 needs a new license. See [Newest release](../../../concepts/releases-and-artifacts/#newest-release).

## Resume a download

The signed download link accepts a `Range` header, so your application can resume a download that stopped. The link expires. Request `update.artifact.url` again for a new link.

Each request of `update.artifact.url` counts as a download.

## Update frameworks

Seatify serves update endpoints for Tauri, Sparkle, WinSparkle and electron-updater. An application that uses one of these frameworks reads its endpoint instead of the update check. See [Update a Tauri application](../../updaters/tauri-updates/), [Update a Sparkle application](../../updaters/sparkle-updates/), [Update a WinSparkle application](../../updaters/winsparkle-updates/) and [Update an Electron application](../../updaters/electron-updates/).

For another update framework, your application calls the update check and downloads the file itself. If your framework checks its own signature of the file, add this signature to the file in the dashboard. The update check returns it unchanged in `vendor_signature`. Seatify does not check it.

## Put download links on your page

A stable download link names a platform, an architecture and a file type. It names no version and no filename. So the link stays the same when you publish a new release.

A browser sends no header when it follows a link. So a stable download link works on a web page only for an `open` product. For a `licensed` product, see [Licensed products](#licensed-products).

{{% steps %}}

### Copy the links

Copy the links from the Download links section of the product in the dashboard. The dashboard shows one link for each file of the newest release.

| File | Link |
| --- | --- |
| macOS | `https://dist.seatify.dev/v1/products/<product id>/download?platform=darwin&arch=universal&filetype=dmg` |
| Windows | `https://dist.seatify.dev/v1/products/<product id>/download?platform=windows&arch=amd64&filetype=exe` |
| Linux | `https://dist.seatify.dev/v1/products/<product id>/download?platform=linux&arch=amd64&filetype=tar.gz` |

### Add the links to your page

```html
<a href="https://dist.seatify.dev/v1/products/<product id>/download?platform=darwin&arch=universal&filetype=dmg">Download for macOS</a>
<a href="https://dist.seatify.dev/v1/products/<product id>/download?platform=windows&arch=amd64&filetype=exe">Download for Windows</a>
<a href="https://dist.seatify.dev/v1/products/<product id>/download?platform=linux&arch=amd64&filetype=tar.gz">Download for Linux</a>
```

A click answers a redirect to a signed download link. The browser saves the file under its filename.

### Test the links

Download each link once. The file must be the file of the newest release.

```bash
curl --fail --location --remote-name --remote-header-name \
  "https://dist.seatify.dev/v1/products/$PRODUCT_ID/download?platform=darwin&arch=universal&filetype=dmg"
```

{{% /steps %}}

## Link rules

- A link leads to the newest release in the `stable` channel that has a matching file. A release without a matching file is skipped. A fix for Windows only then does not change the macOS link.
- A `universal` build matches a link for any architecture. A build for the exact architecture wins over a `universal` build.
- If several files of one release match, the link fails with the status 404. Add `filetype` to the link. The links from the dashboard already name the file type.
- A link for a platform that no release has a file for fails with the status 404.
- Add `channel=beta` to a link for the newest beta. Add `constraint=2` to keep a link on version 2. The dashboard adds both when you choose a channel and a version line.
- Each download through a link counts as a download.

## Licensed products

A download of a `licensed` product needs a valid license key for the product. A browser cannot send the key, so your server requests the link instead. Your server must know the license key of the customer, for example from the account of the customer.

{{% steps %}}

### Request the link

Request the stable download link with the license key in the `Seatify-License-Key` header. Do not follow the redirect. The answer has the status 303, and its `Location` header is a signed download link.

A refused request answers a status other than 303. See [Handle the answer](#handle-the-answer).

{{< tabs >}}
{{< tab name="curl" >}}
```bash
curl --silent --output /dev/null --write-out "%{http_code} %{redirect_url}\n" \
  -H "Seatify-License-Key: $LICENSE_KEY" \
  "https://dist.seatify.dev/v1/products/$PRODUCT_ID/download?platform=darwin&arch=universal&filetype=dmg"
```
{{< /tab >}}
{{< tab name="Swift" >}}
```swift
final class NoRedirect: NSObject, URLSessionTaskDelegate {
    func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        willPerformHTTPRedirection response: HTTPURLResponse,
        newRequest request: URLRequest
    ) async -> URLRequest? {
        nil
    }
}

struct DownloadRefused: Error {
    let status: Int
}

let url = URL(string: "https://dist.seatify.dev/v1/products/\(productID)/download?platform=darwin&arch=universal&filetype=dmg")!
var request = URLRequest(url: url)
request.setValue(licenseKey, forHTTPHeaderField: "Seatify-License-Key")

let (_, response) = try await URLSession.shared.data(for: request, delegate: NoRedirect())
let answer = response as! HTTPURLResponse
guard answer.statusCode == 303, let location = answer.value(forHTTPHeaderField: "Location") else {
    throw DownloadRefused(status: answer.statusCode)
}
```
{{< /tab >}}
{{< tab name="C#" >}}
```csharp
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler);

using var request = new HttpRequestMessage(HttpMethod.Get,
    $"https://dist.seatify.dev/v1/products/{productId}/download?platform=darwin&arch=universal&filetype=dmg");
request.Headers.Add("Seatify-License-Key", licenseKey);

using var answer = await client.SendAsync(request);
if (answer.StatusCode != HttpStatusCode.SeeOther)
    throw new InvalidOperationException($"The download was refused with the status {(int)answer.StatusCode}.");

var location = answer.Headers.Location;
```
{{< /tab >}}
{{< tab name="Go" >}}
```go
client := &http.Client{
	CheckRedirect: func(req *http.Request, via []*http.Request) error {
		return http.ErrUseLastResponse
	},
}

req, err := http.NewRequest("GET", "https://dist.seatify.dev/v1/products/"+productID+"/download?platform=darwin&arch=universal&filetype=dmg", nil)
if err != nil {
	return err
}
req.Header.Set("Seatify-License-Key", licenseKey)

answer, err := client.Do(req)
if err != nil {
	return err
}
defer answer.Body.Close()

if answer.StatusCode != http.StatusSeeOther {
	return fmt.Errorf("the download was refused with the status %d", answer.StatusCode)
}

location := answer.Header.Get("Location")
```
{{< /tab >}}
{{< tab name="JavaScript" >}}
```javascript
const answer = await fetch(
  `https://dist.seatify.dev/v1/products/${productId}/download?platform=darwin&arch=universal&filetype=dmg`,
  {
    headers: { "Seatify-License-Key": licenseKey },
    redirect: "manual",
  },
);
if (answer.status !== 303) {
  throw new Error(`The download was refused with the status ${answer.status}.`);
}

const location = answer.headers.get("Location");
```
{{< /tab >}}
{{< /tabs >}}

The JavaScript example runs on a server, such as Node.js. A browser hides the `Location` header of a redirect that it does not follow.

### Send the browser to the file

Answer the request of the browser with a redirect to `location`. The browser saves the file under its filename.

The signed download link expires. Anyone who has the link can use it until it expires. So request a new link for each download, and do not store it.

{{% /steps %}}

Each request of the link counts as a download in the [activity](../../../concepts/activity/) of the license.

## Next steps

- [Publish a release](../publish-a-release/)
- [Verify signed responses](../../signatures/verify-signed-responses/)
- [Rotate signing keys](../../signatures/rotate-signing-keys/)
- [Releases and artifacts](../../../concepts/releases-and-artifacts/)
- [Check for an update](../../../distribution-api/check-for-an-update/), [Download an artifact](../../../distribution-api/download-an-artifact/) and [Stable download link](../../../distribution-api/stable-download-link/)

