Public: anyone can read this; the crew can change it.

An unproved domain claim holds its name for 24 hours, then another app may take it over #15051

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15032-an-unproved-domain-claim-holds-its-name → main 3 commits fork

  • Merged. scout/15032-an-unproved-domain-claim-holds-its-name was merged into main as 9bdd6af.

Review

Sign in to review this change.
6 files changed +142 −19
docs/features/app-own-domain.md +19 −1
@@ -95,7 +95,7 @@ not, the name moves to your app, already verified. Otherwise the answer is
9595 not the clock's: a holder whose record still stands keeps the name. A
9696 resolver failure counts as "still held".
9797
98 The claimed row is the claimant's: production's environment, a fresh
98 The claimed row is the claimant's: production's environment, its
9999 claim token, and no old records, which were the holder's and go with the
100100 holder's row. The `publish` record names the lowercased host the check
101101 reads, however the request spelled it. (`held` is another error's word on
@@ -107,3 +107,21 @@ action. A held name answers with the TXT record to publish; claim again
107107 once it is there. Tests: "a name moves to the app that proves it once the
108108 holder's record is gone" in `test/app-domains.test.ts` and the `t` key in
109109 `test/tui-deploys.test.ts`.
110
111 ## An unproved name is held for a day
112
113 Adding a name holds it for your app while you publish the TXT record, for
114 24 hours (`UNVERIFIED_HOLD_MS` in `src/core/domains.ts`). Until then another
115 app that adds it is told `taken`. Once the day has run out and the name is
116 still unproved, the next app that adds or claims it takes the row over, with
117 no DNS proof needed, and the clock starts again for that app. A proved name
118 is never taken this way: only a claim by proof (above) moves it.
119
120 The TXT token is derived from the host and the app (`claimToken`), so a
121 record you published keeps working when you remove the name and add it again,
122 or take it back. An app holds at most 50 domains; one more is refused as
123 `too_many_domains`. Tests: "an unproved row holds its name for the hold"
124 (1 ms before the hold is `taken`, exactly at the hold the row moves), "a proved name is never
125 taken over by adding it", "an app holds at most 50 domains" in
126 `test/core-domains.test.ts`, and "an unproved name whose day has run out"
127 in `test/app-domains.test.ts`.
src/actions/domain_words.ts +1
@@ -12,6 +12,7 @@ const REFUSALS: Readonly<Record<string, string>> = {
1212 "A domain is a hostname: letters, digits and hyphens in at least two labels, like app.example.com.",
1313 reserved_host: "That name is the forge's own to hand out.",
1414 taken: "Another app already answers to that domain.",
15 too_many_domains: "An app holds at most 50 domains; remove one first.",
1516 invalid_records:
1617 "Old records are a list of up to 50, each with a type (A, AAAA, CNAME, ALIAS, TXT, MX, NS, CAA or SRV), a name, a value and, if known, a ttl in seconds.",
1718 no_runtime: "Nothing is serving apps on this forge.",
src/actions/domains.ts +3 −1
@@ -15,6 +15,7 @@ import {
1515 addDomain,
1616 claimToken,
1717 getDomain,
18 holdLapsed,
1819 normalizeHost,
1920 takeOverDomain,
2021 type TakeOverError,
@@ -183,7 +184,8 @@ export async function claimAppDomain(
183184 if (!gate.ok) return gate;
184185 const { admin, record, runtime } = gate.value;
185186 const holder = getDomain(app.db, normalizeHost(host));
186 if (holder === undefined) return addAppDomain(app, actor, repo, host);
187 // A name nobody holds, or one whose unproved hold ran out, is added.
188 if (holder === undefined || (holder.appId !== record.id && holdLapsed(holder))) return addAppDomain(app, actor, repo, host);
187189 if (holder.appId === record.id) return err("own_domain");
188190 const proof = await checkClaim(
189191 holder.host,
src/core/domains.ts +47 −16
@@ -155,7 +155,26 @@ export interface DomainRules {
155155 readonly appHostSuffix?: string | undefined;
156156 }
157157
158 export type AddDomainError = "invalid_host" | "reserved_host" | "taken";
158 export type AddDomainError = "invalid_host" | "reserved_host" | "taken" | "too_many_domains";
159
160 /** The most domains one app holds: a cap on rows one admin can squat. */
161 export const MAX_APP_DOMAINS = 50;
162
163 /**
164 * How long an unproved row holds its name: a day to publish the TXT record.
165 * After that another app that adds the name takes the row over; a proved
166 * row is never taken this way (`takeOverDomain` is the proof's path).
167 */
168 export const UNVERIFIED_HOLD_MS = 24 * 60 * 60 * 1000;
169
170 /** An unproved row whose hold has run out at `at`: exactly at the hold counts. */
171 export function holdLapsed(domain: AppDomain, at: Date = new Date()): boolean {
172 return domain.verifiedAt === null && Date.parse(domain.createdAt) + UNVERIFIED_HOLD_MS <= at.getTime();
173 }
174
175 function domainCount(db: Database, appId: string): number {
176 return db.query<{ n: number }, [string]>("SELECT count(*) AS n FROM app_domain WHERE app_id = ?1").get(appId)!.n;
177 }
159178
160179 /** A hostname the way DNS wants it: lowercase, no trailing dot. */
161180 export function normalizeHost(host: string): string {
@@ -190,18 +209,12 @@ function isReserved(host: string, rules: DomainRules): boolean {
190209 export const TOKEN_LENGTH = 24;
191210 const TOKEN_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
192211
193 function newToken(): string {
194 const bytes = new Uint8Array(TOKEN_LENGTH);
195 crypto.getRandomValues(bytes);
196 let out = "";
197 for (const byte of bytes) out += TOKEN_ALPHABET[byte & 31];
198 return out;
199 }
200
201212 /**
202 * The token an app publishes to claim a name another app holds. Derived from
203 * host and app, so the claimant can read it before any row is theirs; like
204 * every token here it proves nothing until it is in the zone's DNS.
213 * The token an app publishes for a name: to add it, or to claim it from
214 * another app. Derived from host and app, so the claimant can read it before
215 * any row is theirs and a published record keeps working when the name is
216 * removed and added again or taken over; like every token here it proves
217 * nothing until it is in the zone's DNS.
205218 */
206219 export function claimToken(host: string, appId: string): string {
207220 const bytes = new Bun.CryptoHasher("sha256").update(`forge-claim\0${normalizeHost(host)}\0${appId}`).digest();
@@ -231,6 +244,7 @@ export function takeOverDomain(
231244 if (!holder) return err("not_held");
232245 if (holder.appId === input.appId) return err("own_domain");
233246 if (!proof.claimantPublished || proof.holderPublished) return err("name_held");
247 if (domainCount(db, input.appId) >= MAX_APP_DOMAINS) return err("too_many_domains");
234248 const at = now();
235249 db.transaction(() => {
236250 db.query("DELETE FROM app_domain WHERE host = ?1").run(host);
@@ -251,19 +265,36 @@ export function takeOverDomain(
251265 return ok(getDomain(db, host)!);
252266 }
253267
268 /**
269 * Add a name to an app. A name another app holds is `taken`, unless that
270 * row is unproved and its hold has run out (`holdLapsed`): then the row is
271 * the adder's. A proved row is never replaced here. `at` is the clock, for
272 * tests at the boundary.
273 */
254274 export function addDomain(
255275 db: Database,
256276 input: { host: string; appId: string; createdBy?: string | undefined },
257277 rules: DomainRules,
278 at: Date = new Date(),
258279 ): Result<AppDomain, AddDomainError> {
259280 const host = normalizeHost(input.host);
260281 if (!isHostname(host)) return err("invalid_host");
261282 if (isReserved(host, rules)) return err("reserved_host");
262 if (getDomain(db, host)) return err("taken");
283 const holder = getDomain(db, host);
284 if (holder && (holder.appId === input.appId || !holdLapsed(holder, at))) return err("taken");
285 if (domainCount(db, input.appId) >= MAX_APP_DOMAINS) return err("too_many_domains");
286 const lapsedBefore = new Date(at.getTime() - UNVERIFIED_HOLD_MS).toISOString();
263287 try {
264 db.query(
265 "INSERT INTO app_domain (host, app_id, env, token, created_by, created_at) VALUES (?1, ?2, 'production', ?3, ?4, ?5)",
266 ).run(host, input.appId, newToken(), input.createdBy ?? null, now());
288 db.transaction(() => {
289 // Only an unproved, lapsed row of another app goes; the conditions
290 // are repeated here so a row proved since the read above stays.
291 db.query(
292 "DELETE FROM app_domain WHERE host = ?1 AND verified_at IS NULL AND created_at <= ?2 AND app_id <> ?3",
293 ).run(host, lapsedBefore, input.appId);
294 db.query(
295 "INSERT INTO app_domain (host, app_id, env, token, created_by, created_at) VALUES (?1, ?2, 'production', ?3, ?4, ?5)",
296 ).run(host, input.appId, claimToken(host, input.appId), input.createdBy ?? null, at.toISOString());
297 })();
267298 } catch (error) {
268299 // Two racing adds: the primary key settles it, the check above only
269300 // named it early.
test/app-domains.test.ts +18 −1
@@ -29,7 +29,7 @@ import {
2929 import { AppsRuntime } from "../src/apps/runtime.ts";
3030 import { certificateSaid, probeCertificate } from "../src/apps/certificate.ts";
3131 import { createApp as insertApp, type AppRecord } from "../src/core/apps.ts";
32 import { addDomain, claimToken, getDomain, TOKEN_LENGTH } from "../src/core/domains.ts";
32 import { addDomain, claimToken, getDomain, TOKEN_LENGTH, UNVERIFIED_HOLD_MS } from "../src/core/domains.ts";
3333 import { listEvents } from "../src/core/events.ts";
3434 import { eventVerb } from "../src/design/activity.ts";
3535 import type { Repo } from "../src/core/repos.ts";
@@ -955,6 +955,23 @@ describe("an app gets its own domain", () => {
955955 expect(free.ok).toBe(true);
956956 expect(getDomain(app.db, "free-claim.example.com")!.appId).toBe(other.id);
957957 });
958
959 test("an unproved name whose day has run out is the next app's by claim or add, with no DNS proof", async () => {
960 const host = "lapsed-claim.example.com";
961 const held = addAppDomain(app, alice, repo, host);
962 if (!held.ok) throw new Error(held.error);
963 // Still inside the hold: held, and the claim asks for proof.
964 expect(await claimAppDomain(app, alice, otherRepo, host)).toEqual({ ok: false, error: "name_held" });
965 expect(addAppDomain(app, alice, otherRepo, host)).toEqual({ ok: false, error: "taken" });
966 const past = new Date(Date.now() - UNVERIFIED_HOLD_MS).toISOString();
967 app.db.query("UPDATE app_domain SET created_at = ?1 WHERE host = ?2").run(past, host);
968 const moved = await claimAppDomain(app, alice, otherRepo, host);
969 expect(moved.ok).toBe(true);
970 const row = getDomain(app.db, host)!;
971 expect(row.appId).toBe(other.id);
972 expect(row.verifiedAt).toBeNull();
973 expect(row.token).toBe(claimToken(host, other.id));
974 });
958975 });
959976
960977 describe("the certificate sentence", () => {
test/core-domains.test.ts +54
@@ -10,6 +10,8 @@ import {
1010 getVerifiedDomain,
1111 getDomain,
1212 listDomains,
13 MAX_APP_DOMAINS,
14 UNVERIFIED_HOLD_MS,
1315 parseRecordsInput,
1416 setOldRecords,
1517 primaryDomain,
@@ -132,3 +134,55 @@ test("claim tokens differ by app and host and are token-shaped", () => {
132134 expect(claimToken("a.example.com", "a1")).not.toBe(claimToken("a.example.com", "a2"));
133135 expect(claimToken("a.example.com", "a1")).not.toBe(claimToken("b.example.com", "a1"));
134136 });
137
138 test("an unproved row holds its name for the hold: at hold minus 1 ms taken, exactly at the hold taken over", () => {
139 const db = fresh();
140 const t0 = new Date("2026-11-01T00:00:00.000Z");
141 expect(addDomain(db, { host: "squat.example.com", appId: "a1" }, RULES, t0).ok).toBe(true);
142 const early = new Date(t0.getTime() + UNVERIFIED_HOLD_MS - 1);
143 expect(addDomain(db, { host: "squat.example.com", appId: "a2" }, RULES, early)).toEqual({ ok: false, error: "taken" });
144 expect(getDomain(db, "squat.example.com")?.appId).toBe("a1");
145 const atHold = new Date(t0.getTime() + UNVERIFIED_HOLD_MS);
146 const taken = addDomain(db, { host: "Squat.Example.com", appId: "a2" }, RULES, atHold);
147 expect(taken.ok).toBe(true);
148 const row = getDomain(db, "squat.example.com");
149 expect(row?.appId).toBe("a2");
150 expect(row?.verifiedAt).toBeNull();
151 expect(row?.createdAt).toBe(atHold.toISOString());
152 expect(listDomains(db, "a1")).toEqual([]);
153 // The holder re-adding its own name is still taken, lapsed or not.
154 expect(addDomain(db, { host: "squat.example.com", appId: "a2" }, RULES, new Date(atHold.getTime() + 2 * UNVERIFIED_HOLD_MS))).toEqual({ ok: false, error: "taken" });
155 });
156
157 test("a proved name is never taken over by adding it, however old", () => {
158 const db = fresh();
159 const t0 = new Date("2026-01-01T00:00:00.000Z");
160 expect(addDomain(db, { host: "kept.example.com", appId: "a1" }, RULES, t0).ok).toBe(true);
161 recordCheck(db, "kept.example.com", { verified: true, said: "ok" });
162 const later = new Date(t0.getTime() + 365 * UNVERIFIED_HOLD_MS);
163 expect(addDomain(db, { host: "kept.example.com", appId: "a2" }, RULES, later)).toEqual({ ok: false, error: "taken" });
164 expect(getVerifiedDomain(db, "kept.example.com")?.appId).toBe("a1");
165 });
166
167 test("the token is derived from host and app, so a published record survives re-adds and takeovers", () => {
168 const db = fresh();
169 const t0 = new Date("2026-11-01T00:00:00.000Z");
170 const first = addDomain(db, { host: "same.example.com", appId: "a1" }, RULES, t0);
171 expect(first.ok && first.value.token).toBe(claimToken("same.example.com", "a1"));
172 removeDomain(db, "same.example.com");
173 const again = addDomain(db, { host: "same.example.com", appId: "a1" }, RULES, t0);
174 expect(again.ok && again.value.token).toBe(claimToken("same.example.com", "a1"));
175 const over = addDomain(db, { host: "same.example.com", appId: "a2" }, RULES, new Date(t0.getTime() + UNVERIFIED_HOLD_MS));
176 expect(over.ok && over.value.token).toBe(claimToken("same.example.com", "a2"));
177 });
178
179 test("an app holds at most 50 domains", () => {
180 const db = fresh();
181 for (let i = 0; i < MAX_APP_DOMAINS; i++) add(db, `d${i}.example.com`);
182 expect(addDomain(db, { host: "one-more.example.com", appId: "a1" }, RULES)).toEqual({ ok: false, error: "too_many_domains" });
183 add(db, "held.example.com", "a2");
184 recordCheck(db, "held.example.com", { verified: true, said: "ok" });
185 expect(takeOverDomain(db, { host: "held.example.com", appId: "a1" }, RULES, { claimantPublished: true, holderPublished: false })).toEqual({ ok: false, error: "too_many_domains" });
186 removeDomain(db, "d0.example.com");
187 expect(addDomain(db, { host: "one-more.example.com", appId: "a1" }, RULES).ok).toBe(true);
188 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs