Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion apps/admin/components/onboarding/wizard/wizard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1144,7 +1144,11 @@ export function SetupWizard({
(inGoingLive && !emailFailed && !liveFailed && !liveReady) ||
(step === "offer" && !data.offer) ||
((step === "build" || step === "brand") && uploadsBusy) ||
(step === "school" && !inCreating && availability === "checking");
(step === "school" &&
!inCreating &&
(availability === "checking" ||
availability === "taken" ||
availability === "invalid"));

function onNext() {
if (inGoingLive && emailFailed) {
Expand Down
5 changes: 5 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ WEB_ORIGIN=http://localhost:3000
# Runtime domain for school subdomains. Set this to the domain serving storefronts;
# in development it defaults to *.localhost when omitted.
# PLATFORM_SITE_DOMAIN=example.com
# Classic CourseLit app's school check (`GET <url>?host=<hostname>`, 200 = owned,
# 404 = free). Its schools' subdomains can't be taken. Unset: not checked.
# LEGACY_SCHOOL_CHECK_URL=http://classic.internal/school/exists
# Domain to ask the classic app about, when its schools aren't on PLATFORM_SITE_DOMAIN.
# LEGACY_SCHOOL_DOMAIN=classic.example.com
NODE_ENV=development
DATABASE_URL=postgres://courselit:courselit@127.0.0.1:5432/courselit

Expand Down
10 changes: 10 additions & 0 deletions apps/api/src/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ import {
updateSchoolPaymentSettings,
} from "./schools.js";
import { CLIENT_IP_HEADER } from "./auth/api-key-throttle.js";
import { legacySubdomainsAmong } from "./legacy-schools.js";
import { startLearnerSsoSignIn } from "./learner-sso-sign-in.js";
import { usableLearnerMethods } from "./login-methods.js";
import { handleSsoAdminRequest } from "./sso-admin-routes.js";
Expand Down Expand Up @@ -2366,6 +2367,15 @@ export async function dispatch(
if (!parsed.success) {
return errorResponse(createPlatformError("validation_failed"));
}
// A classic-app school's subdomain is taken. Checked here, not in
// createSchool, so staff imports of classic schools still work.
if ((await legacySubdomainsAmong([parsed.data.subdomain])).size > 0) {
return errorResponse(
createPlatformError("conflict", {
safeDetails: { reason: "subdomain_taken" },
}),
);
}
const requestId = requestIdFrom(request, deps);
const result = await createSchool(
deps.db,
Expand Down
122 changes: 122 additions & 0 deletions apps/api/src/legacy-schools.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { afterEach, describe, expect, it } from "bun:test";
import { dispatch } from "./dispatch.js";
import { createPgliteRuntime, freezeRuntimeClock } from "./runtime.js";
import { seedWorld } from "./seed.js";

const CLASSIC = new Set([
"oldschool.courselit.app",
"oldschool-studio.courselit.app",
"elsewhere.classic.test",
]);

/** A stand-in classic app on a random local port; `status` forces every answer. */
function startClassicApp(status?: number) {
const server = Bun.serve({
port: 0,
fetch(request) {
const host = new URL(request.url).searchParams.get("host") ?? "";
return new Response(null, { status: status ?? (CLASSIC.has(host) ? 200 : 404) });
},
});
process.env.LEGACY_SCHOOL_CHECK_URL = `http://127.0.0.1:${server.port}/school/exists`;
return server;
}

async function setup() {
process.env.PLATFORM_SITE_DOMAIN = "courselit.app";
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
const runtime = await createPgliteRuntime({ clock, billingMode: "oss" });
const world = await seedWorld(runtime, clock);
const headers = { cookie: world.owner.sessionCookie };
const check = async (subdomain: string) =>
(
await dispatch(runtime, {
method: "GET",
path: `/v1/schools/subdomain-availability?subdomain=${subdomain}`,
headers,
})
).body as { available: boolean; reason: string | null; suggestions: string[] };
const create = (subdomain: string) =>
dispatch(runtime, {
method: "POST",
path: "/v1/schools",
headers,
body: { name: "School", subdomain },
});
return { runtime, check, create };
}

describe("classic app school subdomains", () => {
const originalUrl = process.env.LEGACY_SCHOOL_CHECK_URL;
const originalDomain = process.env.PLATFORM_SITE_DOMAIN;
const originalLegacyDomain = process.env.LEGACY_SCHOOL_DOMAIN;
afterEach(() => {
if (originalLegacyDomain === undefined) delete process.env.LEGACY_SCHOOL_DOMAIN;
else process.env.LEGACY_SCHOOL_DOMAIN = originalLegacyDomain;
if (originalUrl === undefined) delete process.env.LEGACY_SCHOOL_CHECK_URL;
else process.env.LEGACY_SCHOOL_CHECK_URL = originalUrl;
if (originalDomain === undefined) delete process.env.PLATFORM_SITE_DOMAIN;
else process.env.PLATFORM_SITE_DOMAIN = originalDomain;
});

it("read as taken, skip classic names in suggestions and can't be created", async () => {
const classic = startClassicApp();
const { runtime, check, create } = await setup();
try {
const checked = await check("oldschool");
expect(checked).toMatchObject({ available: false, reason: "taken" });
expect(checked.suggestions).toEqual([
"oldschool-art",
"oldschool-school",
"oldschool2",
]);
const created = await create("oldschool");
expect(created.status).toBe(409);
expect(JSON.stringify(created.body)).toContain("subdomain_taken");
expect(await check("newschool")).toMatchObject({ available: true, reason: null });
expect((await create("newschool")).status).toBe(201);
} finally {
classic.stop(true);
await runtime.close();
}
});

it("refuses to create when the classic app can't answer", async () => {
const classic = startClassicApp(503);
const { runtime, create } = await setup();
try {
expect((await create("newschool")).status).toBe(500);
} finally {
classic.stop(true);
await runtime.close();
}
});

it("asks about LEGACY_SCHOOL_DOMAIN when the classic app is on another domain", async () => {
const classic = startClassicApp();
const { runtime, check } = await setup();
try {
expect(await check("elsewhere")).toMatchObject({ available: true });
process.env.LEGACY_SCHOOL_DOMAIN = "classic.test";
expect(await check("elsewhere")).toMatchObject({
available: false,
reason: "taken",
});
} finally {
classic.stop(true);
await runtime.close();
}
});

it("isn't consulted when LEGACY_SCHOOL_CHECK_URL is unset", async () => {
const classic = startClassicApp();
const { runtime, create } = await setup();
delete process.env.LEGACY_SCHOOL_CHECK_URL;
try {
expect((await create("oldschool")).status).toBe(201);
} finally {
classic.stop(true);
await runtime.close();
}
});
});
34 changes: 34 additions & 0 deletions apps/api/src/legacy-schools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Subdomains used by schools on the classic CourseLit app, which shares the
* platform domain. The classic app is asked `GET <LEGACY_SCHOOL_CHECK_URL>?host=
* <label>.<platform domain>`: 200 means a classic school owns it, 404 means it
* doesn't. Any other answer throws, so a name is never handed out unchecked.
* When the variable is unset (self-hosted installs), nothing is checked.
* `LEGACY_SCHOOL_DOMAIN` overrides the domain asked about, for environments
* where the classic app serves schools on a different domain (QA).
*/
export async function legacySubdomainsAmong(
candidates: string[],
): Promise<Set<string>> {
const url = process.env.LEGACY_SCHOOL_CHECK_URL;
if (!url || candidates.length === 0) return new Set();
const domain =
process.env.LEGACY_SCHOOL_DOMAIN ||
process.env.PLATFORM_SITE_DOMAIN ||
"courselit.app";
const owned = await Promise.all(
candidates.map(async (label) => {
const endpoint = new URL(url);
endpoint.searchParams.set("host", `${label}.${domain}`);
const response = await fetch(endpoint, {
redirect: "manual",
signal: AbortSignal.timeout(1500),
});
await response.body?.cancel();
if (response.status === 200) return true;
if (response.status === 404) return false;
throw new Error(`classic school check returned ${response.status}`);
}),
);
return new Set(candidates.filter((_, index) => owned[index]));
}
11 changes: 9 additions & 2 deletions apps/api/src/onboarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Clock } from "@codelitdev/platform";
import { createPlatformError, type PlatformError } from "@codelitdev/platform";
import { and, desc, eq, inArray, isNotNull, isNull, ne, sql } from "drizzle-orm";
import * as schema from "./db/schema/index.js";
import { legacySubdomainsAmong } from "./legacy-schools.js";
import { getPaymentProvider } from "./payments.js";
import { getMailingSettings } from "./sendlit-service.js";
import type { AppDb } from "./types.js";
Expand Down Expand Up @@ -356,11 +357,17 @@ async function takenAmong(db: AppDb, candidates: string[]): Promise<Set<string>>
.from(schema.schoolHosts)
.where(inArray(schema.schoolHosts.hostname, candidates)),
]);
// Reserved subdomains read as taken, so the address checker suggests others (S19).
return new Set([
// Reserved subdomains read as taken, so the address checker suggests others (S19),
// and so do subdomains of schools on the classic app.
const taken = new Set([
...[...schools, ...hosts].map((row) => row.value),
...candidates.filter(isReservedSubdomain),
]);
// Only the first few still-free candidates are asked of the classic app, in one
// round of parallel calls; the rest aren't offered. The wizard shows three.
const free = candidates.filter((value) => !taken.has(value));
const legacy = await legacySubdomainsAmong(free.slice(0, 4));
return new Set([...taken, ...legacy, ...free.slice(4)]);
}

export async function checkSchoolSubdomain(
Expand Down
2 changes: 2 additions & 0 deletions packages/api-contract/src/school-subdomain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const RESERVED_SUBDOMAINS: ReadonlySet<string> = new Set([
"blog",
"cdn",
"courselit",
"dash",
"dashboard",
"dev",
"docs",
Expand All @@ -38,6 +39,7 @@ export const RESERVED_SUBDOMAINS: ReadonlySet<string> = new Set([
"staging",
"static",
"status",
"storefront",
"support",
"test",
"webhook",
Expand Down
Loading