Skip to content

Set up SSO with a setup link

For: an app developer who lets the owner of an organization hand the SSO setup to the IT admin of a customer.

What it does: this page turns on the setup links, then shows the five steps. The owner mints a link. The IT admin fills in drafts. A test sign-in passes. The IT admin hands back. The owner reads the preview and activates.

  • A working Enterprise SSO config, with organizations on.
  • A signed-in owner with a second factor on. An owner manages the SSO setup only with a second factor (second_factor_required).
  • The notices of the account on, by account.notices. sso.setup fails at start when account.notices is false, because no owner would learn that a setup waits.
  1. Turn on sso.setup in the config. It is off by default. ttlHours sets the life of a link from 1 to 168 hours, and the default is 72. The hook hooks.sso.setupReady runs after each handback.
  2. The owner mints a link with the steps and the kinds that the customer needs. The answer holds the clear token one time. Send the address to the IT admin. Never write the token to a log.
  3. The IT admin opens the address. The page asks to confirm, and only the confirm opens a session. So a mail scanner that opens the link opens nothing.
  4. The IT admin follows the guide of the provider on the setup page. The guide shows the values to copy. The list at the end of this page has one guide page for each provider. The IT admin adds the domain and publishes its TXT record. Then the IT admin saves the connection and, if the link has the step, takes a SCIM token one time.
  5. The IT admin starts a test sign-in. The test must pass for the draft as it is now. A change of the draft, of a domain, or of the SCIM token makes the old test void. So make these changes before the test.
  6. The IT admin hands back. Core sends the notice sso_setup_ready to every owner of the organization and runs hooks.sso.setupReady.
  7. The owner reads the preview, then activates with the version of that preview. The version moves when the draft, a domain, or the pending SCIM token changes. If the IT admin changed one of them after the preview, the activation answers conflict and nothing goes live. Read the preview again. The activation answers setup_not_tested until a test of the current draft has passed. The link ends at the activation, and core sends the notice sso_activated.
Turn on the setup links, mint a link, and activate
import { createClient } from "@authtempo/client";
import {
createAuth,
dohCloudflare,
dohGoogle,
type MailPort,
type StorageAdapter,
} from "@authtempo/core";
/**
* Setup links on. An owner mints a link and sends it to the IT admin of the
* customer. The IT admin fills in the domain, the connection, and the SCIM
* token. Nothing goes live until the owner activates the link.
* `sso.setup` needs `sso` and `organizations`. It needs `account.notices` too,
* which is on by default: the owners get a notice when a setup is ready.
*/
export function createSetupAuth(
deps: { storage: StorageAdapter; mail: MailPort; secret: string },
/** Runs after the commit of a handback. A throw writes one log line and changes nothing. */
onReady: (e: { organizationId: string; linkId: string }) => void | Promise<void> = () => {},
) {
return createAuth({
baseURL: "https://api.example.com",
appURL: "https://app.example.com",
trustedOrigins: ["https://app.example.com"],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
organizations: {},
sso: {
oidc: true,
saml: {},
// The IT admin proves the domain by a TXT record. Every resolver must give it.
dns: [dohCloudflare(fetch), dohGoogle(fetch)],
// A link lives 24 hours unless the mint names another time. The range is 1 to 168 hours.
setup: { ttlHours: 24 },
},
hooks: { sso: { setupReady: onReady } },
});
}
/** The client of the owner: a signed-in manager of the organization. */
export function ownerClient(fetchImpl: typeof fetch) {
return createClient({ baseURL: "https://api.example.com", fetch: fetchImpl });
}
/**
* Mint a link for the steps that the customer needs. The clear token appears
* once, in this answer. Send it to the IT admin, and never write it to a log.
*/
export async function mintSetupLink(
client: ReturnType<typeof ownerClient>,
organizationId: string,
) {
const made = await client.sso.setupLinks.create({
organizationId,
steps: ["domain", "connection", "directory"],
kinds: ["saml", "oidc"],
note: "Acme staff, from the ticket of the IT team",
});
if (!made.ok) throw new Error(made.code);
// The IT admin opens this address. The page only asks to confirm, and opens no session.
return `https://api.example.com/auth/sso/setup?token=${encodeURIComponent(made.value.token)}`;
}
/**
* After the handback: read what an activation makes live, then activate. The
* activation sends the `version` of the preview that the owner read. When the
* link holder changes the draft after the preview, the activation answers
* `conflict` and nothing goes live: read the preview again. The activation
* answers `setup_not_tested` until a test of this exact draft has passed.
*/
export async function reviewAndActivate(
client: ReturnType<typeof ownerClient>,
linkId: string,
approve: (preview: unknown) => boolean,
) {
const got = await client.sso.setupLinks.get({ id: linkId });
if (!got.ok) throw new Error(got.code);
const preview = got.value.preview;
if (preview === null) throw new Error("The link has no draft yet.");
if (!approve(preview)) {
const revoked = await client.sso.setupLinks.revoke({ id: linkId });
if (!revoked.ok) throw new Error(revoked.code);
return null;
}
const live = await client.sso.setupLinks.activate({ id: linkId, version: preview.version });
if (!live.ok) throw new Error(live.code);
return live.value;
}
The sample as a test
import { createAuth, dohGoogle } from "@authtempo/core";
import { describe, expect, it } from "vitest";
import { call, harness } from "../support/harness.ts";
import {
createSetupAuth,
mintSetupLink,
ownerClient,
reviewAndActivate,
} from "./sso-setup-link.ts";
/** A fetch that keeps each request and answers each one with the next body. */
function stubFetch(bodies: unknown[]) {
const seen: { method: string; url: URL; body: unknown }[] = [];
const fetchImpl: typeof fetch = async (input, init) => {
const req = new Request(input, init);
const text = await req.text();
seen.push({
method: req.method,
url: new URL(req.url),
body: text === "" ? undefined : JSON.parse(text),
});
return Response.json(bodies.shift() ?? {});
};
return { fetchImpl, seen };
}
describe("setup link sample", () => {
it("builds the auth with sso.setup on and answers a bad link with one code", async () => {
const h = harness();
const auth = createSetupAuth(h);
// The page only asks to confirm. It opens no session, so it says nothing of the token.
const page = await call(auth, "GET", "/auth/sso/setup?token=tsl_wrong");
expect(page.status).toBe(200);
expect(page.headers.getSetCookie()).toEqual([]);
const res = await call(auth, "POST", "/auth/sso/setup/open", { token: "tsl_wrong" });
expect(res.status).toBe(404);
expect(await res.json()).toMatchObject({ error: "setup_link_invalid" });
});
it("refuses a config that turns the notices off, because no owner would learn of a setup", () => {
const h = harness();
expect(() =>
createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret: h.secret,
storage: h.storage,
mail: h.mail,
organizations: {},
sso: { oidc: true, dns: [dohGoogle(fetch)], setup: {} },
account: { notices: false },
}),
).toThrow(/account\.notices/);
});
it("refuses sso.setup without organizations", () => {
const h = harness();
expect(() =>
createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret: h.secret,
storage: h.storage,
mail: h.mail,
sso: { oidc: true, dns: [dohGoogle(fetch)], setup: {} },
}),
).toThrow(/organizations/);
});
it("mints a link with the organization in the query and the rest in the body", async () => {
const { fetchImpl, seen } = stubFetch([
{ id: "lnk1", token: "tsl_secret value", expiresAt: "2026-11-24T00:00:00.000Z" },
]);
const address = await mintSetupLink(ownerClient(fetchImpl), "org1");
expect(address).toBe("https://api.example.com/auth/sso/setup?token=tsl_secret%20value");
expect(seen[0]?.method).toBe("POST");
expect(seen[0]?.url.pathname).toBe("/auth/sso/setup-links/create");
expect(seen[0]?.url.searchParams.get("organizationId")).toBe("org1");
expect(seen[0]?.body).toMatchObject({ steps: ["domain", "connection", "directory"] });
});
it("revokes a link whose preview the owner refuses, and activates one that the owner accepts", async () => {
const refuse = stubFetch([
{ link: { id: "lnk1" }, preview: { version: 2, domains: [] } },
{ ok: true },
]);
expect(await reviewAndActivate(ownerClient(refuse.fetchImpl), "lnk1", () => false)).toBeNull();
expect(refuse.seen.map((s) => s.url.pathname)).toEqual([
"/auth/sso/setup-links/get",
"/auth/sso/setup-links/revoke",
]);
const accept = stubFetch([
{ link: { id: "lnk1" }, preview: { version: 2, domains: [] } },
{ connection: { id: "con1" } },
]);
await reviewAndActivate(ownerClient(accept.fetchImpl), "lnk1", () => true);
// R28: the activation sends the version that the preview showed.
expect(accept.seen[1]?.body).toEqual({ id: "lnk1", version: 2 });
expect(accept.seen.map((s) => s.url.pathname)).toEqual([
"/auth/sso/setup-links/get",
"/auth/sso/setup-links/activate",
]);
});
});

What the owner must read before the activation

Section titled “What the owner must read before the activation”

The owner is the last check. Nothing the IT admin does goes live without the owner.

One risk stays. A person who steals the link before the IT admin uses it can fill a draft. That draft can name a provider that the thief controls. If the owner then activates it after a quick read of the preview, the thief signs in to the organization through that provider. The test run does not stop this, because a thief’s provider passes a test too. Core cannot know who the IT admin is. Two things limit the risk. The notice to every owner shows that a setup is ready, so a second owner can ask who handed it back. The notice is a mail. A failed mail writes one log line, and the handback stays. An owner with no address gets no mail. So do not rely on the notice alone. The link also ends at its time, at a revoke, and at the first activation.

So the owner must do three things before an activation:

  • Read the domain, the provider address, and the sign-in URL of the preview. They must be the values of the customer.
  • Ask the IT admin by a second channel, such as a phone call, if the draft is the draft of the customer.
  • Revoke the link when the answer is no.
  • The link, the open, and the page answer one code, setup_link_invalid, for an unknown, expired, revoked, or ended link. An answer tells nothing about the link.
  • A draft is not a live row. It signs nobody in, and the SCIM token of a draft opens no directory, until the owner activates.
  • The IT admin sets the values of the provider only. The owner sets enabled, jit, defaultRole, mfa, and scimRoles after the setup.
  • An organization holds at most 2 live links. A live link is not revoked, not ended, and not expired. The mint answers setup_link_limit past it.
  • A link can expire before the activation. Then the draft connection and the domain of that link stay. They are not live, and they sign nobody in. A new link that adds the same domain answers conflict, because the domain belongs to the old link. Delete the domain with POST /sso/domains/delete. Delete the old draft with POST /sso/connections/delete if you do not want it. Then mint a new link.
  • The sweep deletes a setup link, with the name of its IT contact, 30 days after the link expired. It deletes the setup sessions and test runs of that age too.
  • Each guide shows the date on which a person read the provider docs. A label that the docs do not confirm shows as Unconfirmed. No guide was checked on a real tenant yet.