On this page

← All documentation

Adding a download source or mirror

Let the Download page search a new site, either with a declaration (URL templates and JSON paths) or with a bridge (pure functions), without your mod ever touching the network.

A mod can add to the Download page a mirror for osu! beatmapsets, or a whole source: a tab that searches a site, lists its sets and downloads them. Your mod does not do the network I/O. It describes the site, and the game makes every request itself.

There are two ways to describe it:

downloads.register downloads.registerBridge
You write data: URL templates, JSON paths, hosts, a rate three pure functions: search, onResponse, action
Requests one GET per page of results, one GET per file POST, forms, XML or HTML answers, several requests chained (search, then detail, then file)
Result a mirror or a source a source
Use it when the site answers JSON to a GET the declaration cannot say what the site needs

Start with the declaration. Move to a bridge only for what it cannot describe.

What the player sees and controls

Both need the network permission in defineMod: permissions: ["network"]. Without it, the registration is refused:

`downloads.register` needs the `network` permission: declare `permissions: ["network"]`
  • The Mods page shows a network badge, the hosts your mod will contact, and a switch ("Allow it to add download mirrors and sources"). The player can take the permission away mod by mod (the setting networkDenied): your declarations disappear at once, as if the mod was off.
  • The Download page lists a mod source behind More sources, grouped by the mod, with a banner "Source provided by the mod … It contacts: …" and a button that turns the source off. The button is only there when some mod provides a source.
  • Settings → Library → Downloads holds an ordered list of mirrors (the game's own and the mods'), a switch for each mirror or source, and the field where the player saves the token of a source that asks for one.
  • Disabling, failing or uninstalling your mod removes its mirrors and sources at once.
  • The three settings networkDenied, downloadMirrorOrder and downloadDisabled name what is installed on this machine, so they are left out of the settings export.

A declared mirror and source

The example declares both. It uses example.org, a domain reserved for documentation: nothing is served there, so the repository's tests run these declarations against recorded answers, with no network.

/// <reference path="../../../mods/sdk/modding.d.ts" />

// Adds two things to the Download page, described as data only: a mirror for osu! beatmapsets and a
// source of its own (a tab). The mod never touches the network: the game makes every request itself,
// only on the hosts listed below (HTTPS, no port, redirects re-checked), at the rate declared here,
// and shows these hosts to the player on the Mods page and in the Download tab. The player can take the
// `network` permission away or turn each mirror or source off.
//
// `example.org` is reserved for documentation: nothing is served there. Replace the hosts and the
// field paths with those of a real service you are allowed to use.
//
// The answers these declarations read are recorded in crates/downloader/tests/fixtures
// (mod_source_search.json, osu_direct_search.json): the tests of the repository run the declarations below against
// them with a fake transport, no network involved.
export default defineMod({
  id: "example.download-sources",
  name: "Example download sources",
  version: "1.0.0",
  apiVersion: 2,
  author: "PVNG",
  description: "A mirror for osu! sets and a source of its own, declared as data (fictional hosts).",
  permissions: ["network"],
  setup() {
    // One more mirror for osu! beatmapsets. It answers like osu.direct or catboy.best (osu! API v2
    // beatmapset objects), so `format: "osu"` reads it as it is. It joins the built-in mirrors after
    // them, in the player's order (Settings > Library > Downloads).
    downloads.register({
      id: "mirror",
      name: "Example mirror",
      description: "A fictional osu! mirror.",
      site: "https://mirror.example.org",
      kind: "mirror",
      target: "osu",
      hosts: ["mirror.example.org"],
      rateLimit: 30,
      search: {
        url: "https://mirror.example.org/api/search",
        // `{query}` is the typed text (always encoded by the game); a group in brackets is written only
        // when every variable inside has a value.
        params: { query: "{query}[ cs>={keysMin}][ cs<={keysMax}]", amount: "{limit}", offset: "{offset}" },
        paging: { kind: "offset", size: 20 },
        response: { format: "osu" },
      },
      download: { url: "https://mirror.example.org/d/{id}" },
    });

    // A whole source: its own tab, a search, a list of sets, and a zip per set. The service's answer is
    // mapped field by field with simple JSON paths; ids may be texts. `auth` makes the game ask the
    // player for a token in the settings and send it, in `Authorization: Bearer`, on downloads only.
    downloads.register({
      id: "maps",
      name: "Example maps",
      description: "A fictional source of mania sets.",
      site: "https://maps.example.org",
      kind: "source",
      hosts: ["api.example.org", "files.example.org"],
      rateLimit: 60,
      auth: { kind: "token", scope: "download" },
      search: {
        url: "https://api.example.org/v1/search",
        params: {
          q: "{query}",
          min_keys: "{keysMin}",
          max_keys: "{keysMax}",
          order: "{sort}",
          rank: "{status}",
          offset: "{offset}",
          limit: "{limit}",
        },
        sorts: { newest: "date", plays: "plays", stars: "difficulty" },
        statuses: { ranked: "ranked", loved: "loved" },
        paging: { kind: "offset", size: 20 },
        response: {
          format: "mapped",
          results: "data.items",
          total: "data.total",
          item: {
            id: "uuid",
            title: "title",
            artist: "artist",
            creator: "mapper",
            status: "state",
            bpm: "bpm",
            playCount: "plays",
            cover: "images.card",
            difficulties: { path: "charts", name: "name", keys: "keys", stars: "stars", length: "seconds", only: { path: "mode", equals: "mania" } },
          },
        },
      },
      // The address of the zip comes from each result (it must be on one of the hosts above).
      download: { urlField: "files.zip" },
    });
  },
});

A mirror adds one more server for osu! beatmapsets: it joins the game's own mirrors after them, in the order the player sets. A source adds a tab.

What a declaration contains

Field Rule
id 1 to 32 characters, a-z0-9-; the published key is <modId>/<id>
name 1 to 32 characters; shown on the page and in Settings
description optional, 1 to 200 characters
site optional, an https:// address (256 characters at most), shown so the player can read the site's terms
kind "mirror" (a server for osu! beatmapsets) or "source" (a tab)
target a mirror names what it serves: "osu", the only value. A source has none.
hosts the allow-list: 1 to 8 exact lowercase DNS names (see below)
rateLimit requests per minute, 1 to 120, 30 by default
auth optional, where the player's token goes (see below)
search how to list sets. A source needs it; a mirror may leave it out and only serve files.
download how to fetch a set: url (a template with {id}) or urlField (a path to the file's URL in the listed result)

A mod registers at most 4 downloads (declarations and bridges together), and all mods together at most 64. The key must be unique.

Hosts

hosts are bare names: no scheme, port, path or wildcard. Every one must be lowercase ASCII, have at least two labels, and not be an IP address or a local name (local, localhost, internal, lan, intranet, home, corp, *.home.arpa). Duplicates are refused. Every URL your declaration writes, every URL read from an answer and every cover picture is checked against this list before it is sent, and only https goes out. A name that resolves to a private, loopback or link-local address is refused when it resolves.

The URL template

A template is text with {variables} and optional groups in brackets. The text of a variable is always percent-encoded by the game, and numbers are formatted by it. There is no other variable.

Variable Value
{query} the typed text
{status}, {sort} the value your statuses and sorts tables give for the player's choice
{offset}, {page}, {cursor}, {limit} paging (see below)
{keysMin}, {keysMax}, {starsMin}, {starsMax}, {bpmMin}, {bpmMax}, {lengthMin}, {lengthMax}, {genre}, {language} the Download page's filters
{id} the set's id, only in download.url
  • A parameter whose variable has no value is left out.
  • A group [ …] is written only when every variable inside has a value: {query}[ cs>={keysMin}].
  • \[, \], \{, \} and \\ write the character itself.
  • A filter whose variables are in the request is sent to the server; the others only narrow the results already loaded, and the page says so.
  • search.url is a plain address on a declared host: no query, no variable. Put the query in params (at most 16, each name 1 to 32 characters among letters, digits and _-.[]). Templates are at most 256 characters.

sorts maps the game's sort ids (newest, updated, plays, favourites, title, artist, stars; relevance needs no entry) to your service's own value, and statuses maps the status ids (all, ranked, loved, qualified, pending, graveyard) the same way. A table is non-empty if and only if some parameter names {sort} or {status}.

Paging

paging: { kind, size, first? } has size from 1 to 100 (also the value of {limit}), and a kind:

Kind Variable Meaning
offset {offset} results already read
page {page} page number from first (0 or 1, 1 by default)
cursor {cursor} what the previous answer's response.nextCursor path held

The matching variable must appear in a parameter. Without paging the listing is a single page. A mirror pages by offset or page only, because its listing is merged with the other mirrors' by position.

Reading the answer

response.format is "osu" (an array of osu! API v2 beatmapset objects, which is what osu! mirrors answer; only the mania difficulties are kept) or "mapped" (field by field, with item).

For mapped: results is the path of the array (the answer itself when absent), total the path of the match count, and item maps every field with a simple JSON path: a.b[0].c. A path is 1 to 128 characters and at most 8 steps; a key is 1 to 48 characters among letters, digits, _ and -; an index is below 10 000. There is no filter, wildcard or script, and a key that contains a dot or another character cannot be read.

item field Meaning
id, title required. An id is a number or a text of at most 64 characters.
artist, creator, status, bpm, playCount, favourites optional
cover optional, the path of a cover URL, which must be on a declared host
difficulties optional: { path, name?, keys, stars?, length?, only? }; keys is an integer from 1 to 18, length is in seconds, and only: { path, equals } keeps the difficulties whose path equals the text (compared as text, ignoring case: 3 equals "3")

Every value is typed and bounded by Rust (texts cut, numbers finite, 1 to 18 keys). A result that cannot be read is skipped, never invented. A mirror needs a numeric id.

The file

download.url is a template with {id} (and nothing else) for a mirror and for a source whose files live at a fixed pattern. download.urlField is a path read from the listed result, for a source whose answer gives each file's address; it needs the mapped format and a source. The answer must be a zip that starts with PK, holds at least one chart the game can read, and is at most 512 MiB; it is extracted safely (absolute paths, .. and links refused) and installed like any other source, recorded as mod:<modId>/<id>.

The token

auth: { kind: "token", header?, scheme?, scope? } makes the game ask the player for a token in Settings and send it for you.

Field Rule
header Authorization (the default), X-API-Key or X-Auth-Token
scheme up to 16 letters written before the token: Bearer by default for Authorization, none for the others; "" sends the token alone
scope "all" (the default): the listing and the downloads carry it. "download": the listing is public and only the files carry it.

The token is 8 to 4096 visible characters. It is kept by the game, in its own file for each source (encrypted with Windows DPAPI, with an entropy of its own), never in the settings the interface keeps. Your script never receives it, it never appears in an event, an error message or a log, and covers carry none. It is sent only in the declared header, only to your declared hosts, and the header is dropped as soon as a redirect changes the host. auth.header, scheme and scope are only for kind: "token"; with kind: "none" they are refused.

What the game guarantees

  • HTTPS only, declared hosts only, no port. Redirects are followed by hand, 3 at most, and each hop is checked again against the allow-list; a hop to an undeclared host is refused, and the token header is dropped as soon as the host changes.
  • Sizes: 8 MiB of JSON, 512 MiB per set, 30 minutes per file, connection and answer timeouts.
  • The rate is a sliding window per source. Past it, a search answers "rate limited" with the delay (Example maps: the declared rate of 30 requests per minute is used up), and a download waits up to 30 s and then fails.
  • A mod that is turned off, fails or is removed takes its declarations with it.

Messages you will read

A refused registration throws with the reason, and the mod fails. These come from the Rust that validates the declaration:

download id must be 1 to 32 characters among a-z, 0-9 and `-`, got "Maps"
a mod registers at most 4 downloads
hosts lists 1 to 8 hosts
host "10.0.0.1": an IP address is never allowed
host "Api.example.org": a lowercase ASCII name of at most 253 characters
rateLimit is 1 to 120 requests per minute
auth.header is one of Authorization, X-API-Key, X-Auth-Token
unknown variable {foo}: use one of query, status, sort, offset, page, limit, cursor, keysMin, keysMax, starsMin, starsMax, bpmMin, bpmMax, lengthMin, lengthMax, genre, language, id
search.params names {sort} but search.sorts is empty
Offset paging needs a parameter with {offset}
a mirror names the source it serves: target: "osu"
a source needs `search`: it lists the sets of its tab
download has `url` or `urlField`, not both
download id is registered twice

The mapped format needs response.item and osu refuses it; cursor paging needs response.nextCursor, and nextCursor is only for cursor paging.

Bridges: your functions compute the next step

When the site is not a JSON GET, register a bridge. You give the declaration (id, name, description?, site?, hosts, rateLimit?, auth?, with the same rules as above) and three functions. They are pure and synchronous: they never do I/O. Each one returns the next step, and the game does what the step says:

Function When the game calls it Arguments
search(query, page, state) the player searches or asks for the next page the text (trimmed, 200 characters at most), the page (1 the first time, else the nextPage of the last results), the state of the last results (null the first time)
onResponse(response, state) after every request step, with the answer to it { status, headers, text } and the state that step carried
action(result, actionId, state) the player presses a result's button, to download the result { id, title, artist, data }, the id of the button, and null

A step has exactly one of request, results, download and error, with an optional state:

Step The game then
{ request, state? } makes the request and calls onResponse(response, state)
{ results, nextPage?, state? } shows the results; nextPage (a string or a number of 128 characters at most) is what the next search call receives as page
{ download, state? } downloads the file (only from action)
{ error } stops with your message (200 characters at most) as the error

onResponse is needed as soon as one of your functions returns a request.

The example adapts a fictional site whose search is a POST with a form, answered in XML, and whose file is found in a second, detail request. Rust runs this exact file against recorded answers:

/// <reference path="../../../mods/sdk/modding.d.ts" />

// Adapts a FICTIONAL site whose API is nothing like the declarative shape (`downloads.register`): the search is a POST with a
// form body answered in XML, and a map's file is found on a second, detail request. The mod never does any I/O: its functions
// only compute the next step (a request to make, results to show, a file to download). The GAME makes every request, only on
// the hosts declared below (https, redirects re-checked), calls `onResponse` back with the answer as text (2 MiB at most), and
// injects the player's token itself: this script never sees it.
//
// `example.org` is reserved for documentation: nothing is served there. The tests of the repository run this very file against
// recorded answers (crates/modding/tests/bridge.rs), no network involved.

/** What the fictional site's XML says about one map. */
interface Row {
  id: string;
  title: string;
  artist: string;
  mapper: string;
  keys: number;
  mb: string;
}

const text = (xml: string, tag: string): string => {
  const found = new RegExp(`<${tag}>([^<]*)</${tag}>`).exec(xml);
  return found ? found[1].replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">") : "";
};

/** `<map id="7"><title>…</title>…</map>` blocks. XML and HTML arrive as TEXT: strings and regular expressions are the tools. */
const rows = (xml: string): Row[] =>
  [...xml.matchAll(/<map id="(\d+)">([\s\S]*?)<\/map>/g)].map((block) => ({
    id: block[1],
    title: text(block[2], "title"),
    artist: text(block[2], "artist"),
    mapper: text(block[2], "mapper"),
    keys: Number(text(block[2], "keys")),
    mb: text(block[2], "mb"),
  }));

/** What this mod carries from one call to the next (the game hands `state` back; it is JSON, 8 KiB at most). */
interface State {
  page?: number;
  detailOf?: string;
}

export default defineMod({
  id: "example.download-bridge",
  name: "Example download bridge",
  version: "1.0.0",
  apiVersion: 2,
  author: "PVNG",
  description: "Adapts a fictional site (POST + XML, then a detail request) for the Download tab. Fictional hosts.",
  permissions: ["network"],
  setup() {
    downloads.registerBridge({
      id: "maps",
      name: "Example maps",
      description: "A fictional site with a form search answered in XML.",
      site: "https://maps.example.org",
      hosts: ["maps.example.org", "files.example.org"],
      rateLimit: 30,
      // The player's token, kept by the game: sent in this header on downloads only, never given to the functions below.
      auth: { kind: "token", header: "Authorization", scope: "download" },

      // First page: `page` is 1. Whatever `nextPage` a `results` step names comes back here.
      search(query, page, _state): BridgeStep {
        return {
          request: { url: "https://maps.example.org/cgi/find", method: "POST", form: { terms: query, page: String(page) }, expect: "xml" },
          state: { page: Number(page) },
        };
      },

      // The game calls this with the answer to the request of the previous step.
      onResponse(response, state): BridgeStep {
        const carried = (state ?? {}) as State;
        if (response.status !== 200) return { error: `the site answered ${response.status}` };
        if (carried.detailOf !== undefined) {
          // The detail request answered with JSON: it names the file.
          const detail = JSON.parse(response.text) as { file?: string };
          if (!detail.file) return { error: "this map has no file" };
          return { download: { url: `https://files.example.org${detail.file}`, format: "osz" } };
        }
        const found = rows(response.text);
        return {
          results: found.map((row) => ({
            id: row.id,
            title: row.title,
            artist: row.artist,
            creator: row.mapper,
            keyCount: row.keys,
            size: `${row.mb} MB`,
            tags: ["example"],
            details: [{ label: "Site id", value: row.id }],
            // Each button comes back to `action` with its id.
            actions: [{ id: "download", label: "Download" }],
          })),
          nextPage: found.length >= 2 ? (carried.page ?? 1) + 1 : undefined,
          state: carried,
        };
      },

      // A button was pressed: ask for the detail page, then `onResponse` names the file.
      action(result, _actionId, _state): BridgeStep {
        return { request: { url: `https://maps.example.org/maps/${result.id}.json`, expect: "json" }, state: { detailOf: result.id } };
      },
    });
  },
});

Requests

request is { url, method?, headers?, body? | form? | json?, expect? }.

Field Rule
url https on a declared host, 2048 bytes at most. {token} may stand in the tail (never in the host).
method GET (the default) or POST
headers at most 12, each value 512 characters at most, only these names: Accept, Accept-Language, Content-Type, Referer, Origin, X-Requested-With, X-API-Key, X-Auth-Token, Authorization, If-None-Match. No Host, no Cookie. A Referer or Origin must also be on a declared host.
body, form, json at most one of them, POST only, 64 KiB: text, URL-encoded fields, or JSON. The game adds the Content-Type.
expect json, text, xml or html: only changes the Accept header the game sends

The answer reaches onResponse as { status, headers, text }: the status, a few headers in lowercase (content-type, content-length, retry-after, x-total-count, etag, last-modified, content-disposition) and the body as text, 2 MiB at most. A bigger answer is an error, never a silent cut. XML and HTML arrive as text too: there is no DOM and no XML parser; use JSON.parse, regular expressions and string methods. A 4xx or 5xx status is handed to your script so it can decide; 429 (rate limited) and a 401 or 403 when a token is saved are translated by the game itself.

Results

results holds at most 100 cards per page. Rust bounds and cleans every text; the page draws all the cards the same way in the eight themes (labels, size, details, buttons), so you choose what is shown and never the markup.

Field Rule
id a string of 1 to 128 characters or an integer; required. A repeated id is shown once.
title, artist required (a card with no title is an error); cleaned of control characters
creator optional, 64 characters
coverUrl optional; on a declared host, else ignored without an error; fetched through the game's cover route
tags at most 8, 24 characters each
size shown as written, 24 characters, such as 12.4 MB
keyCount 1 to 18, shown like a difficulty chip
details at most 8 lines { label, value } (32 and 200 characters)
actions at most 4 buttons { id, label } (id 1 to 32 of a-z0-9-, label 32 characters). With none, the card gets one plain download button, action download.
data up to 1024 characters the game hands back to action with the result, as result.data; use it for what the next call needs (a slug, a path)

The card the game keeps for action is the validated one, never what the script wrote, and at most 8 KiB of JSON. A press on a button calls action(result, actionId, null) at download time; it must end with a download step.

Downloads

download is { url, method?, headers?, body? | form? | json?, filename?, format }, with the rules of a request. format is zip, osz or qp (all zip containers); rar, 7z and single files are refused. filename is informative (128 characters at most): the game names the folder. The game downloads with its size cap, extracts safely, and requires at least one chart it can read.

Limits of a bridge

Limit Value
requests per search or per action 6 (needed more than 6 requests)
time per search or per action, scripts included 60 s (took more than 60 s)
text of one answer 2 MiB
body of a request 64 KiB
JSON returned by one function 256 KiB
state 8 KiB of JSON
results per page 100
headers per request 12

The requests of a bridge count in the source's rate (searches, steps and downloads).

The token in a bridge

With auth declared, the game injects the token itself: in the declared header (every request for scope: "all", downloads only for "download"), and in place of {token} wherever a request names it: the URL's tail, a header, a body, a form or JSON field. {token} without auth is refused, and it is never accepted in the host name. The script never sees it: an answer that repeats it reaches onResponse with [token] in its place. There are no cookies and no OAuth. A 401 or 403 with a saved token tells the player to save a valid one.

When a bridge is switched off

  • Your function throws, returns something JSON cannot write, or goes over the execution budget: the bridge is switched off for the session. Its source leaves the Download page, the mod's log says why, and the other mods and sources continue.
  • A step that breaks the schema (an unknown field, format: "rar", an undeclared host, a forbidden header, two of request and results…) is an error shown to the player, not a switch-off: the declaration is wrong, not the run.
Example maps: needed more than 6 requests
Example maps: the header "Cookie" is not allowed (allowed: accept, accept-language, content-type, referer, origin, x-requested-with, x-api-key, x-auth-token, authorization, if-none-match)
Example maps: search: a step has exactly one of `request`, `results`, `download` and `error`
Example maps: search: `state` is at most 8 KiB of JSON
Example maps: returned 101 results, at most 100 a page

What neither form can do

OAuth or form sign-in, cookies, writing network code in the script (never), archives the game cannot import (rar, 7z, a loose file), packs with their content unfolded (a mod source lists sets: one zip, one folder) and native DOM or XML parsing. A declaration also cannot read JSON keys that contain a dot or a character outside A-Za-z0-9_-, nor serve as a mirror for anything but osu!. For anything beyond, the source belongs in crates/downloader.

Pitfalls

  • Listing every host the site uses: the API, the file server and the cover CDN. A cover or file URL on an undeclared host is ignored or refused.
  • Using example.org in a mod you publish. It serves nothing.
  • Registering after setup: downloads.register and downloads.registerBridge are only available in the mod's setup.
  • Putting the query in search.url. Use params.
  • Reading XML with JSON.parse. XML and HTML are text.
  • Carrying more than 8 KiB in state. Put a small id in state or in the result's data, and fetch the rest again.

Reference

Source in the game repository: crates/downloader/src/declared.rs,crates/downloader/src/bridge.rs,crates/downloader/src/credentials.rs,crates/modding/src/downloads.rs,crates/modding/src/api.rs,content/examples/mods/download-sources/main.ts,content/examples/mods/download-bridge/main.ts,crates/modding/tests/downloads.rs,crates/modding/tests/bridge.rs