// Maps AT URIs to URLs using a _redirects-style file:
// See https://sites.wisp.place/byjp.me/at-uris/ for live example
//
// /profile/:authority/post/:rkey collection=app.bsky.feed.post
// /profile/:authority collection=,app.bsky.actor.profile
//
// Each line is a URL (or path) template followed by any number of conditions.
// The first line whose conditions all hold, and whose placeholders all exist
// in the AT URI, wins. Blank lines and # comments are ignored.
//
// Keys and placeholders:
// at-uri the whole AT URI
// authority, did, handle the account whose record it is (a space record's author)
// collection, rkey the record's collection and key
// sdid, stype, skey the space's DID, type and key (permissioned data only)
//
// Conditions:
// key=a,b the component is one of these values
// key= the component is absent
// key the component is present
// Each key may appear once per line.
//
// Space URIs only match lines that mention sdid, stype or skey (in a condition
// that allows them, or as a placeholder). Other lines are public-only.
//
// AT URIs are normalised before matching, as the AT URI spec describes: handles
// and NSID domain parts are lowercased; DIDs, rkeys and NSID names keep their
// case. Values in the file must already be normalised, then compare exactly.
//
// Needs an @atproto/syntax build that parses space URIs (currently the `alpha` tag).
import { AtUri } from "@atproto/syntax";
const KEYS = ["at-uri", "authority", "did", "handle", "collection", "rkey", "sdid", "stype", "skey"];
const SPACE_KEYS = ["sdid", "stype", "skey"];
const PLACEHOLDER = new RegExp(`:(${KEYS.join("|")})`, "g");
type Conditions = Map<string, string[] | null>; // null = bare key, "must be present"
type Rule = { template: string; conditions: Conditions; spaces: boolean };
const placeholders = (template: string) => [...template.matchAll(PLACEHOLDER)].map(([, key]) => key);
// Normalising: handles are lowercased, DIDs aren't; an NSID's domain part
// (everything up to the last ".") is lowercased, its name isn't
const lowerHandle = (id: string) => (id.startsWith("did:") ? id : id.toLowerCase());
const lowerNsidDomain = (nsid: string) => nsid.replace(/^.*\./, (domain) => domain.toLowerCase());
/** The normalised components of an AT URI; absent ones are "". Throws if it isn't valid. */
function components(atUri: string): Record<string, string> {
const uri = new AtUri(atUri);
const collection = lowerNsidDomain(uri.collection);
const stype = lowerNsidDomain(uri.spaceType ?? "");
// Whose record it is: the URI's authority, or a space record's author
const authority = lowerHandle(uri.isSpace ? (uri.authorDid ?? "") : uri.host);
const isDid = authority.startsWith("did:");
const segments = uri.isSpace
? [uri.spaceDid, "space", stype, uri.skey, uri.authorDid, collection, uri.rkey]
: [authority, collection, uri.rkey];
return {
"at-uri": "at://" + segments.filter(Boolean).join("/"),
authority,
did: isDid ? authority : "",
handle: isDid ? "" : authority,
collection,
rkey: uri.rkey,
sdid: uri.spaceDid ?? "",
stype,
skey: uri.skey ?? "",
};
}
// Values in the file must already be in normalised form (empty = absent)
const NSID = /^([a-z0-9-]+\.){2,}[a-zA-Z0-9]+$/;
const isNormalised: Record<string, (value: string) => boolean> = {
"at-uri": (v) => { try { return components(v)["at-uri"] === v } catch { return false } },
authority: (v) => v === lowerHandle(v),
handle: (v) => v === v.toLowerCase(),
collection: (v) => NSID.test(v),
stype: (v) => NSID.test(v),
};
const isValidCondition = ([key, value]: string[]) =>
KEYS.includes(key) &&
(value === undefined ||
value.split(",").every((v) => (v === "" ? key !== "at-uri" : (isNormalised[key]?.(v) ?? true))));
// A line sees space URIs only if it mentions a space key in a way that allows one
const allowsSpaces = (template: string, conditions: Conditions) =>
placeholders(template).some((key) => SPACE_KEYS.includes(key)) ||
[...conditions].some(
([key, values]) => SPACE_KEYS.includes(key) && (!values || values.some((v) => v !== "")),
);
// Every value the rules accept for a key; "*" where a rule doesn't restrict it
const acceptedValues = (key: string, rules: Rule[]) => {
const found = rules.flatMap(({ conditions }) => conditions.get(key) ?? ["*"]);
return [...new Set(found)].filter((value) => value !== ""); // "" means absent, not a value
};
export type Options = {
/** Throw on malformed lines instead of skipping them. Default false. */
strict?: boolean;
/** Default host for toUrl, e.g. "https://bsky.app". */
host?: string;
};
export class AtUriRedirects {
private rules: Rule[] = [];
private host?: string;
/** Fetches <host>/.well-known/at-uris; toUrl then defaults to that host. */
static async fromHost(host: string, options: Options = {}) {
const res = await fetch(new URL("/.well-known/at-uris", host));
if (!res.ok) throw new Error(`No AT URI redirects at ${host} (${res.status})`);
return new AtUriRedirects(await res.text(), { host, ...options });
}
constructor(file: string, { strict = false, host }: Options = {}) {
this.host = host;
file.split("\n").forEach((line, i) => {
const [template, ...words] = line.trim().split(/\s+/);
if (!template || template.startsWith("#")) return;
const pairs = words.map((word) => word.split(/=(.*)/)); // split on first "="; bare key → [key]
const conditions: Conditions = new Map(
pairs.map(([key, value]) => [key, value?.split(",") ?? null]),
);
const noRepeats = conditions.size === pairs.length;
if (noRepeats && pairs.every(isValidCondition)) {
this.rules.push({ template, conditions, spaces: allowsSpaces(template, conditions) });
} else if (strict) {
throw new Error(`Malformed line ${i + 1}: ${line}`);
}
});
}
/** Collections that can map to a URL, plus "*" if some line accepts any collection. */
collections(): string[] {
return acceptedValues("collection", this.rules);
}
/** Space types that can map to a URL, plus "*" if some line accepts any space type. */
spaceTypes(): string[] {
return acceptedValues("stype", this.rules.filter((rule) => rule.spaces));
}
/** The URL for the first matching rule (just the path if no host is given), or null. */
toUrl(atUri: string, host = this.host): string | null {
const parts = components(atUri);
const rule = this.rules.find(
({ template, conditions, spaces }) =>
(spaces || !parts.sdid) &&
[...conditions].every(([key, values]) =>
values ? values.includes(parts[key]) : parts[key] !== "",
) &&
placeholders(template).every((key) => parts[key]),
);
if (!rule) return null;
// URL-encode each value, but keep the colons in DIDs readable
const path = rule.template.replace(PLACEHOLDER, (_, key) =>
encodeURIComponent(parts[key]).replaceAll("%3A", ":"),
);
return host ? new URL(path, host).href : path;
}
}
Here’s a sample of what Bluesky/mu/Witchsky might offer at
/.we’ll-known/at-uris: