From c59bc451dbf1cfeea6e73591a02678e8dd050d0b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 13:16:15 +0100
Subject: [PATCH 01/14] feat(cli): connect id track, so Track signs people in
through ID
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
`gateweave connect id track` takes the recorded ID and Track deployments,
shows both addresses and every setting it will set, and waits for a yes.
It sets ID's BETTER_AUTH_URL and OIDC_PAIRWISE_SECRET when unset,
registers Track with ID's own apps:add against the deployed database,
and gives Track OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_PROVIDER_NAME,
OIDC_CLIENT_SECRET and, when unset, BETTER_AUTH_URL. Every value goes
to `wrangler secret put` on stdin.
The pairwise secret is the one value to keep: it goes to a new file
outside the working directory (--keep-secret-at, written new-only with
mode 600), or is shown once on a terminal; with --json or without a
terminal the command asks for the file instead. apps:add output stays
in memory, and output of another form stops the run without showing
any of it.
Everything shown passes through the shared output guard. hideSecrets
also hides `client secret: …`, ID's gwid_cs_ prefix and OIDC_*_SECRET
assignments, and the guard's new `remember` adds the values a run
generates or captures, so even a child that echoes one is filtered.
A second run finds Track's registration with one fixed SELECT on ID's
database and registers nothing twice. A registration without Track's
secret, or a Track with another provider, stops with what to do.
doctor track and doctor id report the connection when one is set up or
recorded; the record keeps the client id, never a secret. Invariant 5
in AGENTS.md now names connect as its one exception, and the source
rule allows randomness and `secret put` in connect.ts only.
---
AGENTS.md | 4 +-
README.md | 24 +-
packages/cli/README.md | 80 ++
packages/cli/src/checks.ts | 35 +
packages/cli/src/connect.ts | 993 +++++++++++++++++++++
packages/cli/src/deploy-track.ts | 15 +-
packages/cli/src/doctor-track.ts | 163 +++-
packages/cli/src/main.ts | 119 ++-
packages/cli/src/record.ts | 106 ++-
packages/cli/src/system.ts | 36 +-
packages/cli/test/connect-id-track.test.ts | 714 +++++++++++++++
packages/cli/test/source.test.ts | 23 +-
12 files changed, 2258 insertions(+), 54 deletions(-)
create mode 100644 packages/cli/src/connect.ts
create mode 100644 packages/cli/test/connect-id-track.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 4caf8ca..c293e29 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -17,7 +17,9 @@ Cloudflare account.
to Cloudflare. A value a person must keep is shown once, with words that say so.
4. **A second run finishes the first and does nothing twice.**
5. **The tool holds no logic a product's own deploy lacks.** It runs each product's repository at
- a release tag; it does not fork their configuration.
+ a release tag; it does not fork their configuration. The one exception is `connect`: it does
+ what both products' self-hosting guides describe by hand to connect them, and nothing more. The
+ one value it makes is ID's `OIDC_PAIRWISE_SECRET`, as ID's guide says to.
6. **Never run against a Cloudflare account that holds anything you care about** in tests or by
hand. Rehearse only in a separate, empty account.
diff --git a/README.md b/README.md
index 9df78e6..4d096b8 100644
--- a/README.md
+++ b/README.md
@@ -5,19 +5,23 @@ Cloudflare account and check the deployment.
**Status: early.** `gateweave deploy`, `gateweave doctor` and `gateweave update` for Track and ID
are tested against a fake Wrangler, git and pnpm. `deploy track` and `doctor track` were also
-rehearsed in a real, empty Cloudflare account. Nothing else exists yet. Run it with
-`npx gateweave` (see [Install](#install)).
+rehearsed in a real, empty Cloudflare account. `gateweave connect id track` is tested against the
+same fakes and its live rehearsal is pending. Run the CLI with `npx gateweave`
+(see [Install](#install)).
## Commands
-| Command | Purpose |
-| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
-| `gateweave deploy track` | Create what Track needs in your Cloudflare account, set its secrets, apply migrations, deploy, and check the result from outside |
-| `gateweave deploy id` | The same for ID: Worker, D1 database, logout Queue and RateLimiter Durable Object |
-| `gateweave doctor track` | Say what is wrong with a Track deployment, in words |
-| `gateweave doctor id` | Say what is wrong with an ID deployment; Track-only checks say they are not checked for ID |
-| `gateweave update track` | Bring a Track deployment to a newer release, keeping the names of its Worker, database and bucket |
-| `gateweave update id` | Bring an ID deployment to a newer release, keeping the names of its Worker, database and queue |
+| Command | Purpose |
+| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
+| `gateweave deploy track` | Create what Track needs in your Cloudflare account, set its secrets, apply migrations, deploy, and check the result from outside |
+| `gateweave deploy id` | The same for ID: Worker, D1 database, logout Queue and RateLimiter Durable Object |
+| `gateweave doctor track` | Say what is wrong with a Track deployment, in words |
+| `gateweave doctor id` | Say what is wrong with an ID deployment; Track-only checks say they are not checked for ID |
+| `gateweave update track` | Bring a Track deployment to a newer release, keeping the names of its Worker, database and bucket |
+| `gateweave update id` | Bring an ID deployment to a newer release, keeping the names of its Worker, database and queue |
+| `gateweave connect id track` | Set up ID's provider, register Track and configure Track to sign people in through ID |
+
+`connect id track` is described in [the package's README](packages/cli/README.md#gateweave-connect-id-track).
## `gateweave deploy track`
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 5203746..2d71203 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -26,6 +26,86 @@ one.
See the [repository](https://github.com/gateweavehq/cli) for what the commands do.
+## `gateweave connect id track`
+
+```
+gateweave connect id track [--id-url
] [--track-url ] [--keep-secret-at ]
+ [--id-name ] [--track-name ] [--account ] [--yes] [--json]
+```
+
+Connects a Track deployment to an ID deployment, so Track signs people in through ID. Both must be
+deployments this tool made and recorded (`gateweave deploy id`, `gateweave deploy track`). With
+several of one product in the account, choose with `--id-name` or `--track-name`. `--id-url` and
+`--track-url` replace the recorded addresses, such as a Custom Domain you added since.
+
+1. **Looks, changing nothing:** the secrets each Worker has (by name), whether ID's
+ `/.well-known/openid-configuration` answers and with which issuer, whether Track's sign-in page
+ already shows a provider, and whether Track is already registered with ID, with one fixed
+ `SELECT` on ID's database.
+2. **Shows the plan and waits for a yes:** both deployments and their addresses, and every setting
+ by name, each marked `set now` or `already set; left as it is`. `--yes` answers for you; without
+ a terminal and without `--yes` it stops at once.
+3. **On ID:** sets `BETTER_AUTH_URL` to ID's address if it is unset, and `OIDC_PAIRWISE_SECRET` if it
+ is unset, to 48 random bytes in base64, made here.
+4. **Registers Track with ID's own `apps:add`**, from ID's release in your cache folder, against the
+ deployed database: app `track`, redirect URI `/api/auth/callback/oidc` and back-channel
+ logout URI `/api/auth/backchannel-logout/oidc`. Its output stays in memory; the command
+ reads the client id and secret from its `client id:` and `client secret:` lines, and if the
+ output has another form it stops and shows none of it.
+5. **On Track:** sets `OIDC_CLIENT_SECRET`, `OIDC_CLIENT_ID`, `OIDC_ISSUER` and `OIDC_PROVIDER_NAME`
+ (`Gateweave ID`), and `BETTER_AUTH_URL` if it is unset, which also turns MCP on.
+6. **Checks:** ID's discovery answers with the issuer, Track's sign-in page shows "Continue with
+ Gateweave ID", and the findings `doctor id` (`oidc-provider`) and `doctor track`
+ (`sign-in-provider`) report for the connection are all `ok`.
+
+Every value goes to `wrangler secret put` on stdin, never as an argument. A setting that is already
+set is left alone, so a second run registers nothing again and replaces no secret; it only checks.
+If ID already has Track registered but Track's `OIDC_CLIENT_SECRET` is not set (a run cut short in
+between), the command stops and says how to recover, because ID shows a client secret once and keeps
+only its hash. If Track already has a client of another provider, it stops and changes nothing.
+
+**The issuer cannot change.** ID's `BETTER_AUTH_URL` becomes the issuer that apps compare, and
+passkeys are bound to it for good. Once any app has signed anyone in, it can never change. Choose
+the address people will always use before you run this: give ID a Custom Domain first and pass it
+with `--id-url`.
+
+**`workers.dev` has a limit.** Two Workers on `workers.dev` cannot reach each other unless each has
+`global_fetch_strictly_public` in its `compatibility_flags`. Until then Track's sign-in through ID
+fails with Cloudflare's error 1042, and ID's back-channel logout cannot reach Track. A
+[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) on
+each Worker is the setup that works. The plan warns about both whenever an address is on
+`workers.dev`.
+
+**What to keep, and where.** `OIDC_PAIRWISE_SECRET` is the one value you must keep: it gives each app
+its own id for each person, and losing or changing it gives everybody a new id in every app.
+Cloudflare cannot show a secret back. When this run makes it:
+
+- with `--keep-secret-at `, it is written to that new file (mode 600 where the system has file
+ modes) before it is set on ID. The path must be outside the folder you run the command from, and
+ the file must not exist yet. Move the value into your password manager.
+- without it, it is shown once on the terminal, with words to keep it. With `--json`, or without a
+ terminal, the command refuses instead and asks for `--keep-secret-at`, so the value never lands
+ in JSON or a log.
+
+Nothing else needs keeping. The client secret goes from `apps:add` to Track and is never shown. No
+secret, token or Wrangler sign-in is printed, logged, written to the record, to the working
+directory or to the system's temporary folder; the generated and captured values join the output
+filter, so even a child process that echoes one shows `[secret]`. The record keeps which Track
+is connected to which ID, the issuer and the client id.
+
+With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`.
+
+| Exit code | Meaning |
+| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 0 | Connected, or already connected, and every check passed |
+| 1 | Something unexpected; the reason says what |
+| 2 | Wrong usage: an unknown option, an address that is not `https://`, a `--keep-secret-at` inside the working directory or already there, or none given where it is needed |
+| 3 | A requirement is missing: a deployment not recorded, a Worker gone, a list it could not read, an issuer other than the one given, Track registered without its secret, or Track with another provider |
+| 4 | The account: several to choose from, or the one named is not reachable |
+| 7 | No yes: declined, or no terminal and no `--yes`; nothing was changed |
+| 8 | Setting a secret, installing ID's release or its `apps:add` failed; the reason says what to do |
+| 9 | Connected, but a check failed, or ID's discovery did not answer before registering |
+
## License
[AGPL-3.0-only](LICENSE).
diff --git a/packages/cli/src/checks.ts b/packages/cli/src/checks.ts
index d3d0054..c3f4bbb 100644
--- a/packages/cli/src/checks.ts
+++ b/packages/cli/src/checks.ts
@@ -146,6 +146,41 @@ export async function mcpIsOn(sys: System, address: string): Promise {
+ try {
+ const response = await sys.fetch(new URL("/.well-known/openid-configuration", address).href);
+ if (response.status !== 200) return null;
+ const issuer = (JSON.parse(response.text) as { issuer?: unknown } | null)?.issuer;
+ return typeof issuer === "string" && issuer !== "" ? issuer : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The names on the provider buttons of Track's sign-in page, other than GitHub's. Track shows its
+ * OpenID Connect button only while OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are all set.
+ * Null when the page did not answer.
+ */
+export async function providerButtons(sys: System, address: string): Promise {
+ try {
+ const page = await sys.fetch(new URL("/login", address).href);
+ if (page.status !== 200) return null;
+ return [...page.text.matchAll(/>\s*Continue with ([^<]+?)\s* match[1] ?? "")
+ .filter((name) => name !== "" && name !== "GitHub");
+ } catch {
+ return null;
+ }
+}
+
/**
* Runs every check against the address, retrying each for up to `withinMs` while a new
* `workers.dev` address comes up.
diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts
new file mode 100644
index 0000000..879533b
--- /dev/null
+++ b/packages/cli/src/connect.ts
@@ -0,0 +1,993 @@
+import { randomBytes } from "node:crypto";
+import { access, chmod, lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import {
+ type CheckResult,
+ discoveredIssuer,
+ ID_PROVIDER_NAME,
+ mcpIsOn,
+ providerButtons,
+} from "./checks.ts";
+import { chooseAccount, confirm, json, outputGuard, plain } from "./deploy-track.ts";
+import {
+ ensureCheckout,
+ type Finding,
+ idProviderFindings,
+ trackSignInFindings,
+} from "./doctor-track.ts";
+import { CliError } from "./errors.ts";
+import { cacheDir, npxCli } from "./paths.ts";
+import { PRODUCTS, type ProductKey } from "./products.ts";
+import {
+ type ConnectionStep,
+ type DeploymentRecord,
+ findConnections,
+ listRecords,
+ saveConnection,
+} from "./record.ts";
+import { type Pins, readPins, releaseTags } from "./release.ts";
+import type { RunResult, System } from "./system.ts";
+
+export interface ConnectOptions {
+ /** ID's address, which becomes the issuer. Default: the record's. */
+ idUrl?: string;
+ /** Track's address, which the redirect URIs are built on. Default: the record's. */
+ trackUrl?: string;
+ /** Where to write OIDC_PAIRWISE_SECRET when this run makes it. Never inside the working directory. */
+ keepSecretAt?: string;
+ /** The recorded ID Worker, when the account holds more than one. */
+ idName?: string;
+ /** The recorded Track Worker, when the account holds more than one. */
+ trackName?: string;
+ account?: string;
+ yes: boolean;
+ json: boolean;
+}
+
+export interface ConnectSetting {
+ product: ProductKey;
+ worker: string;
+ name: string;
+ /** False when it was already set and this run left it alone. */
+ setNow: boolean;
+ shown: false;
+}
+
+export interface ConnectResult {
+ ok: true;
+ account: { id: string; name: string };
+ id: { worker: string; address: string; issuer: string };
+ track: { worker: string; address: string };
+ /** What ID gave Track. Not a secret; the client secret is never part of the result. */
+ clientId: string;
+ registeredNow: boolean;
+ /** False when an earlier run had connected them and this one only checked. */
+ changedNow: boolean;
+ settings: ConnectSetting[];
+ pairwiseSecret: { generatedNow: boolean; keptAt: string | null; shownOnTerminal: boolean };
+ warnings: string[];
+ checks: CheckResult[];
+}
+
+/** The app id and name Track is registered under, as in ID's own example. */
+const APP = { id: "track", name: "Gateweave Track" } as const;
+
+const PAIRWISE = "OIDC_PAIRWISE_SECRET";
+const TRACK_OIDC = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const;
+
+/**
+ * The two lines of ID's `apps:add` that carry the result (apps/web/scripts/add-app.ts). Its client
+ * ids are 24 random bytes and its secrets 32, both base64url; the secret carries ID's prefix.
+ */
+const CLIENT_ID_LINE = /^client id:\s+([A-Za-z0-9_-]{16,})$/;
+const CLIENT_SECRET_LINE = /^client secret:\s+(gwid_cs_[A-Za-z0-9_-]{32,})$/;
+
+/**
+ * An address as the origin it names. Anything after the host would make a different issuer and
+ * different redirect URIs, so a path, a query or a name and password is refused, not dropped.
+ */
+export function originOf(value: string, what: string): string {
+ let url: URL | null = null;
+ try {
+ url = new URL(value);
+ } catch {
+ url = null;
+ }
+ if (
+ url?.protocol !== "https:" ||
+ url.username !== "" ||
+ url.password !== "" ||
+ url.search !== "" ||
+ url.hash !== "" ||
+ url.pathname !== "/" ||
+ !/^[a-z0-9.-]+(?::\d+)?$/.test(url.host)
+ ) {
+ throw new CliError(
+ "usage",
+ "bad-url",
+ `${what} "${value}" is not an address: use https://, with nothing after the host.`,
+ );
+ }
+ return url.origin;
+}
+
+/** Whether this Node runs a `.ts` file as ID's `apps:add` does (`node scripts/add-app.ts`). */
+export function stripsTypes(version: string): boolean {
+ const [major = 0, minor = 0] = version.split(".").map(Number);
+ return major > 23 || (major === 23 && minor >= 6) || (major === 22 && minor >= 18);
+}
+
+function inside(base: string, target: string): boolean {
+ const rel = relative(base, target);
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
+}
+
+/**
+ * The file OIDC_PAIRWISE_SECRET is kept in. It must be outside the working directory, so it cannot
+ * be committed with a project, in a folder that exists, and new: a kept secret is never overwritten.
+ */
+async function keepPath(sys: System, given: string): Promise {
+ const cwd = resolve(sys.cwd ?? process.cwd());
+ const path = resolve(cwd, given);
+ let real: string;
+ try {
+ real = join(await realpath(dirname(path)), basename(path));
+ } catch {
+ throw new CliError(
+ "usage",
+ "keep-path-folder-missing",
+ `The folder of --keep-secret-at, ${dirname(path)}, does not exist.`,
+ );
+ }
+ const realCwd = await realpath(cwd).catch(() => cwd);
+ if (inside(cwd, path) || inside(realCwd, real)) {
+ throw new CliError(
+ "usage",
+ "keep-path-inside",
+ `--keep-secret-at must be outside the folder you run this from (${cwd}), so the secret cannot end up in a project or a commit. Choose a path elsewhere, such as in your home folder.`,
+ );
+ }
+ const taken = await lstat(path).then(
+ () => true,
+ () => false,
+ );
+ if (taken) {
+ throw new CliError(
+ "usage",
+ "keep-path-exists",
+ `${path} already exists. This tool never overwrites a file that may hold a kept secret; choose a new path.`,
+ );
+ }
+ return path;
+}
+
+async function exists(path: string): Promise {
+ return access(path).then(
+ () => true,
+ () => false,
+ );
+}
+
+/** The recorded deployment of a product in the account: the one named, or the only one. */
+async function pickRecord(
+ sys: System,
+ accountId: string,
+ accountLabel: string,
+ key: ProductKey,
+ name: string | undefined,
+): Promise {
+ const records = (await listRecords(sys, accountId, key)).filter(
+ (record) => record.steps.includes("deployed") || record.external === true,
+ );
+ const option = key === "id" ? "--id-name" : "--track-name";
+ const label = PRODUCTS[key].label;
+ if (name !== undefined) {
+ const named = records.find(({ worker }) => worker === name);
+ if (named) return named;
+ throw new CliError(
+ "requirement",
+ "not-recorded",
+ `This tool has no record of a ${label} deployment named ${name} in ${accountLabel}. Deploy it with \`gateweave deploy ${key} --name ${name}\` first.`,
+ );
+ }
+ const [only, ...more] = records;
+ if (!only) {
+ throw new CliError(
+ "requirement",
+ "not-recorded",
+ `This tool has no record of a ${label} deployment in ${accountLabel}. Deploy one with \`gateweave deploy ${key}\` first.`,
+ );
+ }
+ if (more.length > 0) {
+ throw new CliError(
+ "usage",
+ "deployment-ambiguous",
+ `${accountLabel} holds several ${label} deployments: ${records.map(({ worker }) => worker).join(", ")}. Choose one with ${option} .`,
+ );
+ }
+ return only;
+}
+
+function lastLine(text: string): string {
+ return (
+ plain(text)
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .at(-1) ?? ""
+ );
+}
+
+async function waitFor(
+ sys: System,
+ withinMs: number,
+ attempt: () => Promise,
+ done: (value: T) => boolean,
+): Promise {
+ const deadline = sys.now() + withinMs;
+ for (;;) {
+ const value = await attempt();
+ if (done(value) || sys.now() >= deadline) return value;
+ await sys.sleep(5_000);
+ }
+}
+
+/**
+ * Connects a Track deployment to an ID deployment, so Track signs people in through ID: turns on
+ * ID's provider, registers Track with ID's own `apps:add`, and gives Track the result.
+ */
+export async function connectIdTrack(sys: System, options: ConnectOptions): Promise {
+ const say = (line = "") => sys.err(`${line}\n`);
+ const npx = npxCli(sys);
+ const cache = cacheDir(sys);
+ await mkdir(cache, { recursive: true });
+
+ // What can be refused before anything is asked of Cloudflare.
+ const idGiven = options.idUrl !== undefined ? originOf(options.idUrl, "--id-url") : null;
+ const trackGiven =
+ options.trackUrl !== undefined ? originOf(options.trackUrl, "--track-url") : null;
+ const keepAt =
+ options.keepSecretAt !== undefined ? await keepPath(sys, options.keepSecretAt) : null;
+
+ const nodeMajor = Number(sys.nodeVersion.split(".")[0]);
+ if (nodeMajor < 22) {
+ throw new CliError(
+ "requirement",
+ "node-too-old",
+ `Node ${sys.nodeVersion} is too old: use Node 22 or newer.`,
+ );
+ }
+ const git = await sys.run("git", ["--version"], { cwd: cache, env: sys.env });
+ if (git.status !== 0) {
+ throw new CliError("requirement", "git-missing", "git is not installed or not on the PATH.");
+ }
+ const npxVersion = await sys.run(sys.execPath, [npx, "--version"], { cwd: cache, env: sys.env });
+ if (npxVersion.status !== 0) {
+ throw new CliError(
+ "requirement",
+ "npx-missing",
+ `npm's npx was not found next to this Node (${npx}). Install Node with npm.`,
+ );
+ }
+
+ // The shared output filter: the API token and Wrangler's sign-in from the start, and below, what
+ // this run generates and what ID's apps:add returns. Everything shown passes through it. The
+ // account name is shown by design, as in doctor.
+ const guard = await outputGuard(sys);
+ const { hide } = guard;
+
+ const latest = (await releaseTags(sys, cache, PRODUCTS.id))[0];
+ if (!latest) {
+ throw new CliError("requirement", "release-not-found", "ID has no release tag yet.");
+ }
+ const latestPins = await readPins(sys, latest, PRODUCTS.id);
+ let env: Record = sys.env;
+ const wranglerAt =
+ (pins: Pins) =>
+ (args: string[], cwd = cache, input?: string): Promise =>
+ sys.run(sys.execPath, [npx, "--yes", `wrangler@${pins.wrangler}`, ...args], {
+ cwd,
+ env,
+ ...(input === undefined ? {} : { input }),
+ });
+ const account = await chooseAccount(
+ sys,
+ (args) => wranglerAt(latestPins)(args),
+ latestPins,
+ options.account,
+ );
+ env = { ...sys.env, CLOUDFLARE_ACCOUNT_ID: account.id };
+ const accountLabel = `the Cloudflare account ${account.name} (${account.id})`;
+
+ const idRecord = await pickRecord(sys, account.id, accountLabel, "id", options.idName);
+ const trackRecord = await pickRecord(sys, account.id, accountLabel, "track", options.trackName);
+ const idPins = await readPins(sys, idRecord.release, PRODUCTS.id);
+ const trackPins = await readPins(sys, trackRecord.release, PRODUCTS.track);
+ const idWrangler = wranglerAt(idPins);
+ const trackWrangler = wranglerAt(trackPins);
+ const recordedAddress = (record: DeploymentRecord, option: string): string => {
+ if (!record.address) {
+ throw new CliError(
+ "requirement",
+ "address-unknown",
+ `The record of ${record.worker} has no address. Give it with ${option} https://.`,
+ );
+ }
+ return originOf(record.address, `The recorded address of ${record.worker}`);
+ };
+ let idAddress = idGiven ?? recordedAddress(idRecord, "--id-url");
+ const trackAddress = trackGiven ?? recordedAddress(trackRecord, "--track-url");
+
+ // Looks, changing nothing.
+ const listSecrets = async (
+ wrangler: ReturnType,
+ worker: string,
+ ): Promise> => {
+ const listed = await wrangler(["secret", "list", "--name", worker, "--format", "json"]);
+ if (listed.status !== 0) {
+ if (/Worker ".+" not found/.test(plain(listed.stderr + listed.stdout))) {
+ throw new CliError(
+ "requirement",
+ "worker-missing",
+ `The Worker ${worker} is not in ${accountLabel} any more. Nothing was changed.`,
+ );
+ }
+ throw new CliError(
+ "requirement",
+ "lookup-failed",
+ `Could not list the secrets of ${worker}: ${hide(lastLine(listed.stderr))}`,
+ );
+ }
+ try {
+ return new Set(json<{ name: string }[]>(listed.stdout).map(({ name }) => name));
+ } catch {
+ throw new CliError(
+ "requirement",
+ "lookup-failed",
+ `Could not read the secrets of ${worker}: Wrangler's list was not JSON.`,
+ );
+ }
+ };
+ const idSecrets = await listSecrets(idWrangler, idRecord.worker);
+ const trackSecrets = await listSecrets(trackWrangler, trackRecord.worker);
+
+ // While BETTER_AUTH_URL and OIDC_PAIRWISE_SECRET are both set, the provider answers with its
+ // issuer. Either may be a text variable, which the list of secrets does not show.
+ const issuerBefore = await discoveredIssuer(sys, idAddress);
+ let adoptedIssuer = false;
+ if (issuerBefore !== null && issuerBefore !== idAddress) {
+ if (idGiven) {
+ throw new CliError(
+ "requirement",
+ "issuer-differs",
+ `ID's issuer is ${issuerBefore}, not ${idGiven}. An issuer cannot change once any app has signed anyone in, so Track has to name that one: run again with --id-url ${issuerBefore}, or without --id-url. Nothing was changed.`,
+ );
+ }
+ idAddress = originOf(issuerBefore, "ID's issuer");
+ adoptedIssuer = true;
+ }
+ const idUrlSet = issuerBefore !== null || idSecrets.has("BETTER_AUTH_URL");
+ const pairwiseSet = issuerBefore !== null || idSecrets.has(PAIRWISE);
+
+ const idNames = {
+ worker: idRecord.worker,
+ database: idRecord.database,
+ databaseId: idRecord.databaseId,
+ bucket: null,
+ queue: idRecord.queue ?? `${idRecord.worker}${PRODUCTS.id.queue?.suffix ?? ""}`,
+ };
+ const checkout = await ensureCheckout(sys, idRecord.release, idNames, PRODUCTS.id);
+ if (!checkout) {
+ throw new CliError(
+ "requirement",
+ "release-unreadable",
+ `Could not fetch ID ${idRecord.release} into the cache, where its apps:add runs.`,
+ );
+ }
+ const redirectUri = `${trackAddress}/api/auth/callback/oidc`;
+ const logoutUri = `${trackAddress}/api/auth/backchannel-logout/oidc`;
+
+ // One fixed query on ID's own database: the first-party apps registered with Track's redirect URI.
+ // The address in it is an origin checked above, so it holds no quote. json_quote matches the
+ // whole URI as apps:add stores it, in a JSON list, so a longer URI on the same host does not count.
+ const lookup = await idWrangler(
+ [
+ "d1",
+ "execute",
+ "DB",
+ "--remote",
+ "--json",
+ "--command",
+ `SELECT client_id FROM oauth_client WHERE reference_id IS NULL AND instr(redirect_uris, json_quote('${redirectUri}'))`,
+ ],
+ checkout,
+ );
+ if (lookup.status !== 0) {
+ throw new CliError(
+ "requirement",
+ "lookup-failed",
+ `Could not read the apps registered with ID ${idRecord.worker}: ${hide(lastLine(lookup.stderr))}`,
+ );
+ }
+ let registered: string[];
+ try {
+ const answer = json<{ results?: { client_id?: unknown }[] }[]>(lookup.stdout);
+ const rows = answer[0]?.results;
+ if (!Array.isArray(rows)) throw new Error("no results");
+ registered = rows.map(({ client_id }) => String(client_id));
+ } catch {
+ throw new CliError(
+ "requirement",
+ "lookup-failed",
+ `Could not read the apps registered with ID ${idRecord.worker}: Wrangler's answer could not be read.`,
+ );
+ }
+
+ const connections = await findConnections(sys, account.id, {
+ idWorker: idRecord.worker,
+ trackWorker: trackRecord.worker,
+ });
+ const previous = connections[0];
+ const buttonsBefore = await providerButtons(sys, trackAddress);
+ // Track shows the button only once all three are set, text variables included.
+ const trackShowsProvider = (buttonsBefore?.length ?? 0) > 0;
+ const trackHas = (name: string) =>
+ trackSecrets.has(name) ||
+ (trackShowsProvider && (TRACK_OIDC as readonly string[]).includes(name));
+
+ if (registered.length > 1) {
+ throw new CliError(
+ "requirement",
+ "registered-twice",
+ `Track's redirect URI ${redirectUri} is registered with ID ${idRecord.worker} more than once (client ids ${registered.join(", ")}). This tool cannot tell which one Track holds the secret of. Remove the ones Track does not use, then run it again. Nothing was changed.`,
+ );
+ }
+ const existingClient = registered[0] ?? null;
+ const recovery = (clientId: string) =>
+ `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track: npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker} (it asks for the value). If not, remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = '${clientId}'", then run \`gateweave connect id track\` again.`;
+ if (existingClient && !trackHas("OIDC_CLIENT_SECRET")) {
+ throw new CliError(
+ "requirement",
+ "registered-without-secret",
+ `Track ${trackRecord.worker} is already registered with ID ${idRecord.worker} (client id ${existingClient}), but Track's OIDC_CLIENT_SECRET is not set. This tool never registers Track a second time. ${recovery(existingClient)} Nothing was changed.`,
+ );
+ }
+ const register = existingClient === null;
+ if (register) {
+ const held = TRACK_OIDC.filter(trackHas);
+ if (held.length > 0) {
+ throw new CliError(
+ "requirement",
+ "track-has-provider",
+ `Track ${trackRecord.worker} already has ${held.join(", ")} set, but ID ${idRecord.worker} has no app registered for ${redirectUri}: Track signs in through another provider, or its registration was removed. This tool replaces no secret. To connect it to ID instead, delete those first (npx wrangler@${trackPins.wrangler} secret delete --name ${trackRecord.worker}), then run it again. Nothing was changed.`,
+ );
+ }
+ if (!stripsTypes(sys.nodeVersion)) {
+ throw new CliError(
+ "requirement",
+ "node-too-old",
+ `ID's apps:add is a TypeScript file that Node runs as it is from 22.18 (or 23.6); this is Node ${sys.nodeVersion}.`,
+ );
+ }
+ if (!(await exists(join(checkout, "apps", "web", "scripts", "add-app.ts")))) {
+ throw new CliError(
+ "requirement",
+ "apps-add-missing",
+ `ID ${idRecord.release} has no apps:add to register Track with. Update ID first: gateweave update id --name ${idRecord.worker}`,
+ );
+ }
+ }
+ if (previous?.clientId && existingClient && previous.clientId !== existingClient) {
+ say(
+ `Note: ID's registration for Track has the client id ${existingClient}, not ${previous.clientId} as recorded; it is left as it is.`,
+ );
+ }
+
+ const trackMcpOn = trackSecrets.has("BETTER_AUTH_URL")
+ ? true
+ : (await mcpIsOn(sys, trackAddress)) === true;
+ const clientIdKnown = existingClient;
+ interface Planned {
+ product: ProductKey;
+ worker: string;
+ name: string;
+ value: string;
+ set: boolean;
+ }
+ const idPlan: Planned[] = [
+ {
+ product: "id",
+ worker: idRecord.worker,
+ name: "BETTER_AUTH_URL",
+ value: idAddress,
+ set: idUrlSet,
+ },
+ {
+ product: "id",
+ worker: idRecord.worker,
+ name: PAIRWISE,
+ value: keepAt
+ ? `generated here, kept at ${keepAt}, never shown`
+ : "generated here and shown once on this terminal, for you to keep",
+ set: pairwiseSet,
+ },
+ ];
+ const trackPlan: Planned[] = [
+ {
+ product: "track",
+ worker: trackRecord.worker,
+ name: "OIDC_CLIENT_SECRET",
+ value: "from the registration, never shown",
+ set: !register,
+ },
+ {
+ product: "track",
+ worker: trackRecord.worker,
+ name: "OIDC_CLIENT_ID",
+ value: clientIdKnown ?? "from the registration",
+ set: !register && trackHas("OIDC_CLIENT_ID"),
+ },
+ {
+ product: "track",
+ worker: trackRecord.worker,
+ name: "OIDC_ISSUER",
+ value: idAddress,
+ set: !register && trackHas("OIDC_ISSUER"),
+ },
+ {
+ product: "track",
+ worker: trackRecord.worker,
+ name: "OIDC_PROVIDER_NAME",
+ value: ID_PROVIDER_NAME,
+ set: trackSecrets.has("OIDC_PROVIDER_NAME") || (trackShowsProvider && !register),
+ },
+ {
+ product: "track",
+ worker: trackRecord.worker,
+ name: "BETTER_AUTH_URL",
+ value: `${trackAddress} (this also turns MCP on)`,
+ set: trackMcpOn,
+ },
+ ];
+ const plan = [...idPlan, ...trackPlan];
+ const toChange = plan.filter(({ set }) => !set);
+ const changing = register || toChange.length > 0;
+
+ // The value a person must keep goes to a file outside the working directory, or to a terminal
+ // they are looking at: never into --json, and never into a log that stderr may be.
+ if (!pairwiseSet && !keepAt && (options.json || !sys.interactive)) {
+ throw new CliError(
+ "usage",
+ "keep-path-needed",
+ `ID's ${PAIRWISE} is not set, and this run would make it: a value you must keep, as losing it gives everyone a new id in every app. ${options.json ? "With --json it is never printed" : "Without a terminal it would land in a log"}, so give a file to keep it in, outside this folder: --keep-secret-at . Nothing was changed.`,
+ );
+ }
+
+ const warnings: string[] = [];
+ if (!idUrlSet) {
+ warnings.push(
+ `The issuer, ID's BETTER_AUTH_URL (${idAddress}), can never change once any app has signed anyone in: apps compare it, and passkeys are bound to it for good. Choose the address people will always use.`,
+ );
+ }
+ const onWorkersDev = [idAddress, trackAddress].filter((address) =>
+ new URL(address).hostname.endsWith(".workers.dev"),
+ );
+ if (onWorkersDev.length > 0) {
+ if (new URL(idAddress).hostname.endsWith(".workers.dev")) {
+ warnings.push(
+ `The issuer ${idAddress} is a workers.dev address, and it can never change once any app has signed anyone in. To give ID a domain of its own later, every app would have to be connected again. If you mean to have one, add a Custom Domain to ${idRecord.worker} first and run this with --id-url.`,
+ );
+ }
+ warnings.push(
+ "Two Workers on workers.dev cannot reach each other unless each has global_fetch_strictly_public in its compatibility_flags: Track's sign-in through ID then fails with Cloudflare's error 1042, and ID's back-channel logout cannot reach Track, so signing out of ID does not end Track's sessions. A Custom Domain on each Worker is the setup that works: https://developers.cloudflare.com/workers/configuration/routing/custom-domains/",
+ );
+ }
+
+ // The plan.
+ const state = (item: Planned) => (item.set ? "already set; left as it is" : "set now");
+ say(`Connect Track to ID in ${accountLabel}, so Track signs people in through ID:`);
+ say(
+ ` ID ${idRecord.worker} at ${idAddress} (ID ${idRecord.release}${adoptedIssuer ? "; the address is ID's issuer" : ""})`,
+ );
+ say(
+ ` Track ${trackRecord.worker} at ${trackAddress} (Track ${trackRecord.release})`,
+ );
+ say();
+ say(` On ID (${idRecord.worker}):`);
+ for (const item of idPlan)
+ say(` ${item.name.padEnd(22)} ${item.set ? "" : `${item.value} `}(${state(item)})`);
+ say();
+ if (register) {
+ say(" Register Track with ID, with ID's own apps:add, on ID's database:");
+ say(` app ${APP.id} ("${APP.name}")`);
+ say(` redirect URI ${redirectUri}`);
+ say(` back-channel logout ${logoutUri}`);
+ } else {
+ say(
+ ` Track is already registered with ID (client id ${existingClient}); nothing is registered.`,
+ );
+ }
+ say();
+ say(` On Track (${trackRecord.worker}):`);
+ for (const item of trackPlan)
+ say(` ${item.name.padEnd(22)} ${item.set ? "" : `${item.value} `}(${state(item)})`);
+ say();
+ for (const warning of warnings) say(` Warning: ${warning}`);
+ if (warnings.length > 0) say();
+ if (keepAt && pairwiseSet)
+ say(` ${PAIRWISE} is already set, so nothing is written to ${keepAt}.`);
+
+ // "checked" is earned again by this run's own checks.
+ let steps: ConnectionStep[] = (previous?.steps ?? []).filter((step) => step !== "checked");
+ let clientId = existingClient;
+ const providerName = trackPlan.find(({ name }) => name === "OIDC_PROVIDER_NAME")?.set
+ ? (previous?.providerName ?? null)
+ : ID_PROVIDER_NAME;
+ const save = () =>
+ saveConnection(sys, {
+ kind: "id-track",
+ accountId: account.id,
+ idWorker: idRecord.worker,
+ trackWorker: trackRecord.worker,
+ issuer: idAddress,
+ trackAddress,
+ providerName,
+ clientId,
+ steps,
+ updatedAt: new Date(sys.now()).toISOString(),
+ });
+ const addStep = (step: ConnectionStep) => {
+ if (!steps.includes(step)) steps = [...steps, step];
+ };
+
+ const settings: ConnectSetting[] = plan.map(({ product, worker, name, set }) => ({
+ product,
+ worker,
+ name,
+ setNow: !set,
+ shown: false,
+ }));
+ let generatedNow = false;
+ let shownOnTerminal = false;
+ let keptAt: string | null = null;
+ let issuer = idAddress;
+
+ const put = async (
+ wrangler: ReturnType,
+ worker: string,
+ name: string,
+ value: string,
+ ): Promise<{ done: boolean; detail: string }> => {
+ const result = await wrangler(["secret", "put", name, "--name", worker], cache, value);
+ const done =
+ result.status === 0 && plain(result.stdout).includes(`Success! Uploaded secret ${name}`);
+ return {
+ done,
+ detail: hide(lastLine(result.stderr) || lastLine(result.stdout) || `exit ${result.status}`),
+ };
+ };
+ const putOrStop = async (
+ item: Planned,
+ wrangler: ReturnType,
+ value: string,
+ ) => {
+ const { done, detail } = await put(wrangler, item.worker, item.name, value);
+ if (!done) {
+ throw new CliError(
+ "deploy-failed",
+ "secret-put-failed",
+ `Could not set ${item.name} on ${item.worker}: ${detail}. Run the command again to finish; what is set stays.`,
+ );
+ }
+ say(` set ${item.name} on ${item.worker}`);
+ };
+
+ if (!changing) {
+ say("An earlier run connected these already; nothing will be changed. Checking them.");
+ } else {
+ await confirm(sys, options.yes, "connect");
+
+ // ID's provider first: nothing can be registered against an issuer that does not answer.
+ const idUrl = idPlan[0];
+ if (idUrl && !idUrl.set) await putOrStop(idUrl, idWrangler, idAddress);
+ if (!pairwiseSet) {
+ const value = Buffer.from((sys.random ?? randomBytes)(48)).toString("base64");
+ guard.remember(value);
+ generatedNow = true;
+ if (keepAt) {
+ // Written before it is set, so a value that reached ID is never one nobody kept.
+ try {
+ // New only (wx), and readable by its owner alone where the system has file modes.
+ await (sys.writeFile ?? writeFile)(keepAt, `${value}\n`, { flag: "wx", mode: 0o600 });
+ if (sys.platform !== "win32") await chmod(keepAt, 0o600);
+ } catch (error) {
+ throw new CliError(
+ "requirement",
+ "keep-path-unwritable",
+ `Could not write ${keepAt} (${(error as NodeJS.ErrnoException).code ?? "error"}). Nothing was set on ID for ${PAIRWISE}.`,
+ );
+ }
+ }
+ let { done, detail } = await put(idWrangler, idRecord.worker, PAIRWISE, value);
+ // A failure can come after Cloudflare took the value. Then it is the one to keep.
+ if (!done) done = (await listSecrets(idWrangler, idRecord.worker)).has(PAIRWISE);
+ if (!done) {
+ if (keepAt) await rm(keepAt, { force: true });
+ detail = detail || "Wrangler failed";
+ throw new CliError(
+ "deploy-failed",
+ "secret-put-failed",
+ `Could not set ${PAIRWISE} on ${idRecord.worker}: ${detail}. ${keepAt ? `${keepAt} was removed again, as it held a value that was never set. ` : ""}Run the command again.`,
+ );
+ }
+ say(` set ${PAIRWISE} on ${idRecord.worker}`);
+ if (keepAt) {
+ keptAt = keepAt;
+ say(
+ ` Keep ${keepAt}: it holds ${PAIRWISE}, the one value of this connection you must keep. Move it into your password manager. Losing or changing it gives everyone a new id in every app, and Cloudflare cannot show it again.`,
+ );
+ } else {
+ shownOnTerminal = true;
+ say();
+ say(
+ ` Keep this value now, in your password manager. It is ${PAIRWISE}, shown this once and never again: Cloudflare cannot show it back, and losing or changing it gives everyone a new id in every app.`,
+ );
+ say();
+ say(` ${value}`);
+ say();
+ }
+ }
+
+ const discovered = await waitFor(
+ sys,
+ 60_000,
+ () => discoveredIssuer(sys, idAddress),
+ (found) => found !== null,
+ );
+ if (discovered === null) {
+ throw new CliError(
+ "checks-failed",
+ "provider-off",
+ `ID's settings are set, but ${idAddress}/.well-known/openid-configuration does not answer, so Track was not registered. Wait a minute and run the command again.`,
+ );
+ }
+ if (discovered !== idAddress) {
+ throw new CliError(
+ "requirement",
+ "issuer-differs",
+ `ID's issuer is ${discovered}, not ${idAddress}: its BETTER_AUTH_URL was set before. Track has to name that issuer, so run again with --id-url ${discovered}. Nothing was registered.`,
+ );
+ }
+ issuer = discovered;
+
+ let clientSecret: string | null = null;
+ if (register) {
+ const install = await sys.run(
+ sys.execPath,
+ [npx, "--yes", `pnpm@${idPins.pnpm}`, "install", "--frozen-lockfile"],
+ {
+ cwd: checkout,
+ env: sys.env,
+ stream: true,
+ streamFilter: guard.stream(),
+ },
+ );
+ if (install.status !== 0) {
+ throw new CliError(
+ "deploy-failed",
+ "install-failed",
+ `Installing ID ${idRecord.release}'s dependencies failed; pnpm's output is above. Nothing was registered; run the command again.`,
+ );
+ }
+ say("Registering Track with ID (ID's apps:add)");
+ // Its output is kept in memory only, never streamed: it holds the client secret. It is the
+ // package's own script (`apps:add` is `node scripts/add-app.ts`), started with this Node and
+ // no shell, so no value here is parsed as a command.
+ const added = await sys.run(
+ sys.execPath,
+ [
+ join("scripts", "add-app.ts"),
+ "--app",
+ APP.id,
+ "--name",
+ APP.name,
+ "--redirect-uri",
+ redirectUri,
+ "--backchannel-logout-uri",
+ logoutUri,
+ ],
+ { cwd: join(checkout, "apps", "web"), env },
+ );
+ const captured = `${added.stdout}\n${added.stderr}`;
+ for (const match of plain(captured).matchAll(
+ /client secret:\s*(\S+)|(gwid_cs_[A-Za-z0-9_-]+)/gi,
+ )) {
+ const found = match[1] ?? match[2];
+ if (found) guard.remember(found);
+ }
+ const lines = plain(added.stdout)
+ .split(/\r?\n/)
+ .map((line) => line.trim());
+ const ids = lines.flatMap((line) => CLIENT_ID_LINE.exec(line)?.[1] ?? []);
+ const secrets = lines.flatMap((line) => CLIENT_SECRET_LINE.exec(line)?.[1] ?? []);
+ const holdsSecret = /client secret|gwid_cs_/i.test(captured);
+ if (added.status !== 0 && !holdsSecret) {
+ throw new CliError(
+ "deploy-failed",
+ "register-failed",
+ `ID's apps:add stopped (exit ${added.status}): ${hide(lastLine(added.stderr)) || "no reason given"}. Run the command again; it first looks whether Track was registered.`,
+ );
+ }
+ if (added.status !== 0 || ids.length !== 1 || secrets.length !== 1) {
+ throw new CliError(
+ "deploy-failed",
+ "register-output-unreadable",
+ `ID's apps:add ${added.status === 0 ? "finished" : `stopped (exit ${added.status})`}, but its output was not the two lines this tool reads (\`client id:\` and \`client secret:\`). None of it is shown, as it may hold the secret, and Track was given nothing. If Track was registered, the next run says so and how to recover.`,
+ );
+ }
+ clientId = ids[0] ?? null;
+ clientSecret = secrets[0] ?? null;
+ addStep("registered");
+ await save();
+ say(
+ ` registered Track with ID: client id ${clientId}; its secret goes to Track and is never shown`,
+ );
+ }
+
+ if (clientId === null) throw new Error("no client id");
+ const values: Record = {
+ OIDC_CLIENT_ID: clientId,
+ OIDC_ISSUER: issuer,
+ OIDC_PROVIDER_NAME: ID_PROVIDER_NAME,
+ BETTER_AUTH_URL: trackAddress,
+ };
+ for (const item of trackPlan) {
+ if (item.set) continue;
+ if (item.name === "OIDC_CLIENT_SECRET") {
+ if (clientSecret === null) throw new Error("no client secret");
+ // First, as it lives only in this run's memory until Track has it.
+ const { done, detail } = await put(trackWrangler, item.worker, item.name, clientSecret);
+ if (!done) {
+ throw new CliError(
+ "deploy-failed",
+ "client-secret-not-set",
+ `Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker}: ${detail}. ${recovery(clientId)}`,
+ );
+ }
+ say(` set ${item.name} on ${item.worker}`);
+ continue;
+ }
+ const value = values[item.name];
+ if (value === undefined) throw new Error(`no value for ${item.name}`);
+ await putOrStop(item, trackWrangler, value);
+ }
+ addStep("connected");
+ await save();
+ }
+ if (clientId === null) throw new Error("no client id");
+ if (!changing) {
+ issuer = issuerBefore ?? idAddress;
+ addStep("connected");
+ }
+
+ // The checks: ID's provider from outside, Track's button, and what doctor says of both.
+ say(`Checking the connection from outside (up to two minutes while the new settings come up)`);
+ const checks: CheckResult[] = [];
+ const finalIssuer = await waitFor(
+ sys,
+ 60_000,
+ () => discoveredIssuer(sys, idAddress),
+ (found) => found === issuer,
+ );
+ checks.push({
+ name: `ID's /.well-known/openid-configuration answers with the issuer ${issuer}`,
+ ok: finalIssuer === issuer,
+ detail:
+ finalIssuer === issuer ? "passed" : finalIssuer ? `answered ${finalIssuer}` : "no answer",
+ });
+ const wantedButton = providerName;
+ const buttons = await waitFor(
+ sys,
+ 120_000,
+ () => providerButtons(sys, trackAddress),
+ (found) => (found ? (wantedButton ? found.includes(wantedButton) : found.length > 0) : false),
+ );
+ const buttonOk = buttons
+ ? wantedButton
+ ? buttons.includes(wantedButton)
+ : buttons.length > 0
+ : false;
+ checks.push({
+ name: `Track's sign-in page shows "Continue with ${wantedButton ?? "…"}"`,
+ ok: buttonOk,
+ detail: buttonOk ? "passed" : buttons ? "the button is not there" : "the page did not answer",
+ });
+ await save();
+ const connectedNow = await findConnections(sys, account.id, {
+ idWorker: idRecord.worker,
+ trackWorker: trackRecord.worker,
+ });
+ const doctorSays = (product: ProductKey, findings: Finding[]) =>
+ findings.map(
+ (finding): CheckResult => ({
+ name: `doctor ${product}: ${finding.message.replace(/\.$/, "")}`,
+ ok: finding.status === "ok",
+ detail: finding.status === "ok" ? "passed" : (finding.fix ?? finding.status),
+ }),
+ );
+ checks.push(
+ ...doctorSays(
+ "id",
+ await idProviderFindings(
+ sys,
+ await listSecrets(idWrangler, idRecord.worker),
+ idAddress,
+ connectedNow,
+ ),
+ ),
+ ...doctorSays(
+ "track",
+ await trackSignInFindings(
+ sys,
+ await listSecrets(trackWrangler, trackRecord.worker),
+ trackAddress,
+ connectedNow,
+ ),
+ ),
+ );
+ for (const check of checks)
+ say(` ${check.ok ? "ok " : "FAIL"} ${check.name}: ${check.detail}`);
+ const failed = checks.filter(({ ok }) => !ok);
+ if (failed.length > 0) {
+ throw new CliError(
+ "checks-failed",
+ "checks-failed",
+ `Track and ID are connected, but ${failed.map(({ name, detail }) => `${name} (${detail})`).join("; ")}. Run \`gateweave doctor track\` and \`gateweave doctor id\` for more.`,
+ );
+ }
+ addStep("checked");
+ await save();
+
+ return {
+ ok: true,
+ account: { id: account.id, name: account.name },
+ id: { worker: idRecord.worker, address: idAddress, issuer },
+ track: { worker: trackRecord.worker, address: trackAddress },
+ clientId,
+ registeredNow: register,
+ changedNow: changing,
+ settings,
+ pairwiseSecret: { generatedNow, keptAt, shownOnTerminal },
+ warnings,
+ checks,
+ };
+}
+
+/** The result in words. It names settings and never holds a secret's value. */
+export function describeConnect(result: ConnectResult): string {
+ const now = result.settings.filter(({ setNow }) => setNow);
+ const kept = result.settings.filter(({ setNow }) => !setNow);
+ const list = (items: ConnectSetting[]) =>
+ items.length
+ ? items.map(({ product, name }) => `${PRODUCTS[product].label} ${name}`).join(", ")
+ : "none";
+ const secret = result.pairwiseSecret;
+ const lines = [
+ result.changedNow
+ ? `Track (${result.track.worker}) signs people in through ID (${result.id.worker}) now.`
+ : `Track (${result.track.worker}) was already connected to ID (${result.id.worker}); nothing was changed.`,
+ "",
+ ` Issuer ${result.id.issuer}`,
+ ` Track ${result.track.address}`,
+ ` Client id ${result.clientId}${result.registeredNow ? " (registered now)" : ""}`,
+ ` Set now ${list(now)}`,
+ ` Left as they were ${list(kept)}`,
+ ` ${PAIRWISE.padEnd(20)} ${secret.generatedNow ? (secret.keptAt ? `generated; kept at ${secret.keptAt}, the only value to keep` : "generated; shown once above, the only value to keep") : "already set; left as it is"}`,
+ "",
+ ...result.checks.map((check) => ` ok ${check.name}`),
+ ...(result.warnings.length
+ ? ["", ...result.warnings.map((warning) => `Warning: ${warning}`)]
+ : []),
+ ];
+ return `${lines.join("\n")}\n`;
+}
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index 95e8c2e..595ec7c 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -553,7 +553,8 @@ export function hideSecrets(text: string, values: readonly string[]): string {
}
// Formatted JSON can place a quoted value on the next line. An unquoted value must start
// on the assignment's line so a separate message below an empty assignment stays visible.
- const key = "(?:BETTER_AUTH_SECRET|(?:oauth|api|refresh)_token)";
+ const key =
+ "(?:BETTER_AUTH_SECRET|OIDC_PAIRWISE_SECRET|OIDC_CLIENT_SECRET|(?:oauth|api|refresh)_token|client[ _]secret)";
const quoted = new RegExp(
`(${key}["']?\\s*[:=]\\s*)(["'])(?:\\\\.|(?!\\2)[^\\\\\\r\\n])*(\\2)?`,
"gi",
@@ -566,7 +567,9 @@ export function hideSecrets(text: string, values: readonly string[]): string {
`${before}${quote}${REDACTED}${end ?? ""}`,
)
.replace(unquoted, `$1${REDACTED}`)
- .replace(/(Authorization:\s*Bearer\s+)\S+/gi, `$1${REDACTED}`);
+ .replace(/(Authorization:\s*Bearer\s+)\S+/gi, `$1${REDACTED}`)
+ // The prefix ID gives every client secret, so one this run has not learned yet is caught.
+ .replace(/gwid_cs_[A-Za-z0-9_-]+/g, REDACTED);
}
export function hideSensitive(
@@ -586,6 +589,13 @@ export async function outputGuard(sys: System, names: () => readonly string[] =
return {
hide: (text: string): string => hideSensitive(text, names(), secrets),
stream: (hidden: readonly string[] = []) => sensitiveStreamFilter(hidden, secrets),
+ /**
+ * Adds a value this run made or was handed, such as a generated secret or one a child printed,
+ * so everything shown after, a child's echo included, hides it too.
+ */
+ remember: (value: string): void => {
+ if (value.length >= 8 && !secrets.includes(value)) secrets.push(value);
+ },
};
}
@@ -810,6 +820,7 @@ export async function lookUp(
const CONFIRMATION = {
create: { question: "Create these? [y/N] ", nothing: "Nothing was created" },
update: { question: "Update it? [y/N] ", nothing: "Nothing was changed" },
+ connect: { question: "Make these changes? [y/N] ", nothing: "Nothing was changed" },
} as const;
/** Asks for the yes the plan above waits for; `operation` words the question and the refusal. */
diff --git a/packages/cli/src/doctor-track.ts b/packages/cli/src/doctor-track.ts
index 3e177ff..6c6df3b 100644
--- a/packages/cli/src/doctor-track.ts
+++ b/packages/cli/src/doctor-track.ts
@@ -1,6 +1,12 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
-import { checkFromOutside, checkIdsFor, mcpIsOn } from "./checks.ts";
+import {
+ checkFromOutside,
+ checkIdsFor,
+ discoveredIssuer,
+ mcpIsOn,
+ providerButtons,
+} from "./checks.ts";
import {
type Account,
chooseAccount,
@@ -12,10 +18,15 @@ import {
import { CliError } from "./errors.ts";
import { cacheDir, npxCli } from "./paths.ts";
import { PRODUCTS, type ProductDescription } from "./products.ts";
-import { type DeploymentRecord, findRecord } from "./record.ts";
+import {
+ type ConnectionRecord,
+ type DeploymentRecord,
+ findConnections,
+ findRecord,
+} from "./record.ts";
import { compareTags, type Pins, readPins, releaseTags } from "./release.ts";
import type { RunResult, System } from "./system.ts";
-import { nameProduct } from "./wrangler-config.ts";
+import { nameProduct, type ProductNames } from "./wrangler-config.ts";
export type Status = "ok" | "warn" | "fail";
@@ -242,10 +253,152 @@ export async function doctorProduct(
? await mcpFinding(sys, pins, worker, secrets, address)
: { id: "mcp", status: "ok", message: "MCP is not checked for id.", fix: null },
);
+ findings.push(
+ ...(product.key === "track"
+ ? await trackSignInFindings(
+ sys,
+ secrets,
+ address,
+ await findConnections(sys, account.id, { trackWorker: worker }),
+ )
+ : await idProviderFindings(
+ sys,
+ secrets,
+ address,
+ await findConnections(sys, account.id, { idWorker: worker }),
+ )),
+ );
findings.push(...(await outsideFindings(sys, address, product)));
return finish();
}
+const TRACK_OIDC = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const;
+
+/**
+ * Whether Track signs people in through an OpenID Connect provider. Said only when Track has one of
+ * its settings or `gateweave connect id track` connected it, so a Track without one is not told off.
+ */
+export async function trackSignInFindings(
+ sys: System,
+ secrets: Set,
+ address: string | null,
+ connections: readonly ConnectionRecord[],
+): Promise {
+ const connection = connections.find(({ steps }) => steps.includes("connected"));
+ const set = TRACK_OIDC.filter((name) => secrets.has(name));
+ if (set.length === 0 && !connection) return [];
+ const fix = `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.track)}`;
+ const signIn = connection
+ ? `Sign-in through ID ${connection.idWorker} (${connection.issuer}, client id ${connection.clientId})`
+ : "Sign-in through an OpenID Connect provider";
+ // A setting may be a text variable, which the list of secrets does not show; the page does.
+ const buttons = address ? await providerButtons(sys, address) : null;
+ const wanted = connection?.providerName ?? null;
+ const shown = buttons !== null && (wanted ? buttons.includes(wanted) : buttons.length > 0);
+ const missing = TRACK_OIDC.filter((name) => !secrets.has(name));
+ if (missing.length > 0 && !shown) {
+ return [
+ {
+ id: "sign-in-provider",
+ status: "fail",
+ message: `${signIn} is set up only in part: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not set, so the sign-in page has no button for it.`,
+ fix,
+ },
+ ];
+ }
+ if (address && buttons === null) {
+ return [
+ {
+ id: "sign-in-provider",
+ status: "warn",
+ message: `${signIn} is set up, but the sign-in page did not answer, so its button was not seen.`,
+ fix: `Open ${address}/login; if the Worker was just changed, wait a minute and run again.`,
+ },
+ ];
+ }
+ if (address && !shown) {
+ return [
+ {
+ id: "sign-in-provider",
+ status: "fail",
+ message: `${signIn} is set up, but the sign-in page shows no "Continue with ${wanted ?? "…"}" button.`,
+ fix,
+ },
+ ];
+ }
+ return [
+ {
+ id: "sign-in-provider",
+ status: "ok",
+ message: address
+ ? `${signIn} is set up, and the sign-in page shows its button.`
+ : `${signIn} is set up (OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are set).`,
+ fix: null,
+ },
+ ];
+}
+
+/**
+ * Whether ID's OpenID Connect provider is on, and which Track this tool connected to it. Said only
+ * when OIDC_PAIRWISE_SECRET is set or a connection is recorded.
+ */
+export async function idProviderFindings(
+ sys: System,
+ secrets: Set,
+ address: string | null,
+ connections: readonly ConnectionRecord[],
+): Promise {
+ const connected = connections.filter(({ steps }) => steps.includes("connected"));
+ if (!secrets.has("OIDC_PAIRWISE_SECRET") && connected.length === 0) return [];
+ const apps =
+ connected.length > 0
+ ? ` Connected by this tool: ${connected.map(({ trackWorker, clientId }) => `Track ${trackWorker} (client id ${clientId})`).join(", ")}.`
+ : "";
+ if (!address) {
+ return [
+ {
+ id: "oidc-provider",
+ status: "warn",
+ message: `Whether the OpenID Connect provider is on could not be told: the address is unknown.${apps}`,
+ fix: "Run again with --url https://..workers.dev",
+ },
+ ];
+ }
+ const issuer = await discoveredIssuer(sys, address);
+ if (issuer === null) {
+ const missing = ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"].filter(
+ (name) => !secrets.has(name),
+ );
+ return [
+ {
+ id: "oidc-provider",
+ status: "fail",
+ message: `The OpenID Connect provider is off: ${address}/.well-known/openid-configuration does not answer${missing.length ? `, and ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} not set` : ""}. No app can sign anyone in.${apps}`,
+ fix: `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.id)}#turning-on-the-provider`,
+ },
+ ];
+ }
+ const stale = connected.filter((connection) => connection.issuer !== issuer);
+ if (stale.length > 0) {
+ return [
+ {
+ id: "oidc-provider",
+ status: "fail",
+ message: `The OpenID Connect provider answers with the issuer ${issuer}, but ${stale.map(({ trackWorker, issuer: was }) => `Track ${trackWorker} was connected to ${was}`).join(", ")}. Sign-in from there fails.`,
+ fix: `An issuer cannot change once an app has signed anyone in; set ID's BETTER_AUTH_URL back, or see ${selfHosting(PRODUCTS.id)}#turning-on-the-provider`,
+ },
+ ];
+ }
+ return [
+ {
+ id: "oidc-provider",
+ status: "ok",
+ message: `The OpenID Connect provider is on, with the issuer ${issuer}.${apps}`,
+ fix: null,
+ },
+ ];
+}
+
function releaseFinding(
record: DeploymentRecord | undefined,
latest: string,
@@ -305,10 +458,10 @@ async function databaseId(
* Wrangler needs to find the migrations and the database. A checkout the deploy made is reused,
* and its names are written again. Null when it cannot be had.
*/
-async function ensureCheckout(
+export async function ensureCheckout(
sys: System,
release: string,
- names: { worker: string; database: string; bucket: string | null; queue?: string | null },
+ names: ProductNames,
product: ProductDescription,
): Promise {
const parent = join(cacheDir(sys), product.key);
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index f55d854..9b777b5 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -1,4 +1,5 @@
import { parseArgs } from "node:util";
+import { connectIdTrack, describeConnect } from "./connect.ts";
import { type DeployTrackResult, deployId, deployTrack } from "./deploy-track.ts";
import { type DoctorTrackResult, doctorId, doctorTrack } from "./doctor-track.ts";
import { CliError } from "./errors.ts";
@@ -65,6 +66,30 @@ Options:
Each finding is ok, warn or fail. The exit code is 1 when there is a fail, else 0.
`;
+const CONNECT_USAGE = `Usage: gateweave connect id track [options]
+
+Connects a Track deployment to an ID deployment, so Track signs people in through ID. It turns on
+ID's OpenID Connect provider, registers Track with ID's own apps:add and gives Track the client.
+It shows both deployments and every setting it will set, by name, and waits for a yes.
+
+Options:
+ --id-url ID's address, which becomes the issuer for good. Default: the record's.
+ --track-url Track's address, for its redirect URIs. Default: the record's.
+ --keep-secret-at Writes OIDC_PAIRWISE_SECRET, the one value you must keep, to this new
+ file outside the working directory. Without it the value is shown once
+ on the terminal. Needed with --json, and without a terminal.
+ --id-name The recorded ID Worker, when the account has several.
+ --track-name The recorded Track Worker, when the account has several.
+ --account The Cloudflare account, when the sign-in reaches several.
+ Default: CLOUDFLARE_ACCOUNT_ID.
+ --yes Make the changes without asking. Needed when there is no terminal.
+ --json Print the result, or the failure, as one JSON object on stdout.
+ --help Show this.
+`;
+
+/** The options only `connect id track` takes. */
+const CONNECT_ONLY = ["id-url", "track-url", "keep-secret-at", "id-name", "track-name"];
+
function deployUsage(product: (typeof PRODUCTS)[keyof typeof PRODUCTS]): string {
if (product.key === "track") return USAGE;
return `Usage: gateweave deploy id [options]
@@ -220,6 +245,7 @@ export async function main(argv: string[], sys: System): Promise {
const { values, positionals } = parsed;
json = values.json === true;
const command = positionals.join(" ");
+ const connect = command === "connect id track";
const doctor = command === "doctor track" || command === "doctor id";
const update = command === "update track" || command === "update id";
const deployProduct =
@@ -233,39 +259,61 @@ export async function main(argv: string[], sys: System): Promise {
sys.out(`${version()}\n`);
return 0;
}
+ const usageOf = () => {
+ if (connect) return CONNECT_USAGE;
+ if (doctor) return doctorUsage(product);
+ return update ? updateUsage(product) : deployUsage(product);
+ };
if (values.help) {
- sys.err(doctor ? doctorUsage(product) : update ? updateUsage(product) : deployUsage(product));
+ sys.err(usageOf());
return 0;
}
- if (!deployProduct && !doctor && !update) {
+ if (!deployProduct && !doctor && !update && !connect) {
throw new CliError(
"usage",
"usage",
- `This version knows these commands: \`gateweave deploy track\`, \`gateweave deploy id\`, \`gateweave doctor track\`, \`gateweave doctor id\`, \`gateweave update track\` and \`gateweave update id\`.\n\n${USAGE}`,
+ `This version knows these commands: \`gateweave deploy track\`, \`gateweave deploy id\`, \`gateweave doctor track\`, \`gateweave doctor id\`, \`gateweave update track\`, \`gateweave update id\` and \`gateweave connect id track\`.\n\n${USAGE}`,
);
}
// Another command's options are refused, not ignored, so a typo cannot pass for a choice.
- const foreignOptions = doctor
- ? [
- "release",
- "no-attachments",
- "no-account-name",
- "yes",
- "to",
- "from",
- "worker",
- "database",
- "bucket",
- "queue",
- ]
- : update
+ const connectForeign = [
+ "name",
+ "url",
+ "release",
+ "to",
+ "from",
+ "worker",
+ "database",
+ "bucket",
+ "queue",
+ "no-attachments",
+ "no-account-name",
+ ];
+ const foreignOptions = connect
+ ? connectForeign
+ : doctor
? [
- "url",
+ ...CONNECT_ONLY,
"release",
+ "no-attachments",
"no-account-name",
- ...(product.key === "track" ? ["queue"] : ["bucket", "no-attachments"]),
+ "yes",
+ "to",
+ "from",
+ "worker",
+ "database",
+ "bucket",
+ "queue",
]
- : ["url", "to", "from", "worker", "database", "bucket", "queue"];
+ : update
+ ? [
+ ...CONNECT_ONLY,
+ "url",
+ "release",
+ "no-account-name",
+ ...(product.key === "track" ? ["queue"] : ["bucket", "no-attachments"]),
+ ]
+ : [...CONNECT_ONLY, "url", "to", "from", "worker", "database", "bucket", "queue"];
const foreign = foreignOptions.filter(
(option) => values[option as keyof typeof values] !== undefined,
);
@@ -273,9 +321,33 @@ export async function main(argv: string[], sys: System): Promise {
throw new CliError(
"usage",
"usage",
- `\`gateweave ${command}\` has no option --${foreign[0]}.\n\n${doctor ? doctorUsage(product) : update ? updateUsage(product) : deployUsage(product)}`,
+ `\`gateweave ${command}\` has no option --${foreign[0]}.\n\n${usageOf()}`,
);
}
+ for (const option of ["id-name", "track-name"] as const) {
+ const given = values[option];
+ if (given !== undefined && !NAME.test(given)) {
+ throw new CliError(
+ "usage",
+ "bad-name",
+ `"${given}" given with --${option} cannot name a Worker: use lowercase letters, digits and dashes.`,
+ );
+ }
+ }
+ if (connect) {
+ const result = await connectIdTrack(sys, {
+ idUrl: values["id-url"],
+ trackUrl: values["track-url"],
+ keepSecretAt: values["keep-secret-at"],
+ idName: values["id-name"],
+ trackName: values["track-name"],
+ account: values.account,
+ yes: values.yes === true,
+ json,
+ });
+ sys.out(json ? `${JSON.stringify(result)}\n` : describeConnect(result));
+ return 0;
+ }
const name = values.name ?? product.defaultName;
if (!NAME.test(name)) {
throw new CliError(
@@ -348,6 +420,11 @@ function parse(argv: string[]) {
bucket: { type: "string" },
queue: { type: "string" },
account: { type: "string" },
+ "id-url": { type: "string" },
+ "track-url": { type: "string" },
+ "keep-secret-at": { type: "string" },
+ "id-name": { type: "string" },
+ "track-name": { type: "string" },
"no-attachments": { type: "boolean" },
"no-account-name": { type: "boolean" },
yes: { type: "boolean", short: "y" },
diff --git a/packages/cli/src/record.ts b/packages/cli/src/record.ts
index c518a1a..5decba0 100644
--- a/packages/cli/src/record.ts
+++ b/packages/cli/src/record.ts
@@ -53,9 +53,46 @@ export const RECORD_FIELDS: readonly (keyof DeploymentRecord)[] = [
"updatedAt",
];
+export const CONNECTION_STEPS = ["registered", "connected", "checked"] as const;
+export type ConnectionStep = (typeof CONNECTION_STEPS)[number];
+
+/**
+ * What `gateweave connect id track` connected: which Track signs in through which ID, and the
+ * client id ID gave it. The client id is not a secret. There is no field for the client secret or
+ * the pairwise secret, and none may be added.
+ */
+export interface ConnectionRecord {
+ kind: "id-track";
+ accountId: string;
+ idWorker: string;
+ trackWorker: string;
+ /** ID's issuer, the origin of its BETTER_AUTH_URL, which Track's OIDC_ISSUER names. */
+ issuer: string;
+ trackAddress: string;
+ /** The OIDC_PROVIDER_NAME this tool set, or null when Track already had one and kept it. */
+ providerName: string | null;
+ clientId: string | null;
+ steps: ConnectionStep[];
+ updatedAt: string;
+}
+
+export const CONNECTION_FIELDS: readonly (keyof ConnectionRecord)[] = [
+ "kind",
+ "accountId",
+ "idWorker",
+ "trackWorker",
+ "issuer",
+ "trackAddress",
+ "providerName",
+ "clientId",
+ "steps",
+ "updatedAt",
+];
+
interface RecordFile {
version: 1;
deployments: DeploymentRecord[];
+ connections: ConnectionRecord[];
}
export function recordPath(sys: System): string {
@@ -65,9 +102,15 @@ export function recordPath(sys: System): string {
async function readAll(sys: System): Promise {
try {
const file = JSON.parse(await readFile(recordPath(sys), "utf8")) as RecordFile;
- return { version: 1, deployments: Array.isArray(file.deployments) ? file.deployments : [] };
+ return {
+ version: 1,
+ deployments: Array.isArray(file.deployments) ? file.deployments : [],
+ connections: Array.isArray(file.connections) ? file.connections : [],
+ };
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, deployments: [] };
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return { version: 1, deployments: [], connections: [] };
+ }
// Whatever else stops the read (a folder in its place, no permission) is the same stop. The
// error's own text quotes JSON or a path, so it is not passed on.
throw new CliError(
@@ -78,6 +121,14 @@ async function readAll(sys: System): Promise {
}
}
+async function writeAll(sys: System, file: RecordFile): Promise {
+ const path = recordPath(sys);
+ await mkdir(configDir(sys), { recursive: true });
+ // Written beside and moved into place, so an interrupted write never leaves half a record.
+ await writeFile(`${path}.tmp`, `${JSON.stringify(file, null, "\t")}\n`);
+ await rename(`${path}.tmp`, path);
+}
+
export async function findRecord(
sys: System,
accountId: string,
@@ -91,6 +142,18 @@ export async function findRecord(
);
}
+/** Every recorded deployment of a product in an account. */
+export async function listRecords(
+ sys: System,
+ accountId: string,
+ product: DeploymentRecord["product"],
+): Promise {
+ const { deployments } = await readAll(sys);
+ return deployments.filter(
+ (record) => record.product === product && record.accountId === accountId,
+ );
+}
+
/** Saves a record, keeping only the known fields, so nothing else can slip into the file. */
export async function saveRecord(sys: System, record: DeploymentRecord): Promise {
const file = await readAll(sys);
@@ -108,12 +171,37 @@ export async function saveRecord(sys: System, record: DeploymentRecord): Promise
other.worker === clean.worker
),
);
- const path = recordPath(sys);
- await mkdir(configDir(sys), { recursive: true });
- // Written beside and moved into place, so an interrupted write never leaves half a record.
- await writeFile(
- `${path}.tmp`,
- `${JSON.stringify({ version: 1, deployments: [...others, clean] }, null, "\t")}\n`,
+ await writeAll(sys, { ...file, deployments: [...others, clean] });
+}
+
+/** The recorded connections in an account that name this ID Worker or this Track Worker. */
+export async function findConnections(
+ sys: System,
+ accountId: string,
+ match: { idWorker?: string; trackWorker?: string },
+): Promise {
+ const { connections } = await readAll(sys);
+ return connections.filter(
+ (connection) =>
+ connection.accountId === accountId &&
+ (match.idWorker === undefined || connection.idWorker === match.idWorker) &&
+ (match.trackWorker === undefined || connection.trackWorker === match.trackWorker),
);
- await rename(`${path}.tmp`, path);
+}
+
+/** Saves a connection, keeping only the known fields, so no secret can slip into the file. */
+export async function saveConnection(sys: System, connection: ConnectionRecord): Promise {
+ const file = await readAll(sys);
+ const clean = Object.fromEntries(
+ CONNECTION_FIELDS.map((field) => [field, connection[field]]),
+ ) as unknown as ConnectionRecord;
+ const others = file.connections.filter(
+ (other) =>
+ !(
+ other.accountId === clean.accountId &&
+ other.idWorker === clean.idWorker &&
+ other.trackWorker === clean.trackWorker
+ ),
+ );
+ await writeAll(sys, { ...file, connections: [...others, clean] });
}
diff --git a/packages/cli/src/system.ts b/packages/cli/src/system.ts
index 0218062..571a759 100644
--- a/packages/cli/src/system.ts
+++ b/packages/cli/src/system.ts
@@ -12,6 +12,11 @@ export interface RunOptions {
stream?: boolean;
/** Filters streamed output before it reaches this process's stderr. */
streamFilter?: StreamFilter;
+ /**
+ * Written to the child's stdin, which is then closed. A secret travels this way only: never in
+ * an argument, which other users of the machine can read from the process list.
+ */
+ input?: string;
}
export interface RunResult {
@@ -54,22 +59,44 @@ export interface System {
nodeVersion: string;
sleep(ms: number): Promise;
now(): number;
+ /** The folder the command was started in. A value a person must keep is never written there. */
+ cwd?: string;
+ /** Random bytes for a secret this tool makes itself; node:crypto's when unset. Tests set it. */
+ random?: (bytes: number) => Uint8Array;
+ /**
+ * Writes a file a person is to keep; node:fs's when unset. Tests wrap it to see the mode asked
+ * for, which Windows does not keep.
+ */
+ writeFile?: (
+ path: string,
+ data: string,
+ options: { flag: string; mode: number },
+ ) => Promise;
}
export function realSystem(): System {
return {
run(command, args, options) {
return new Promise((resolve) => {
- const child = spawn(command, args, {
+ const common = {
cwd: options.cwd,
env: options.env ?? process.env,
shell: false,
- // Nothing a child asks can be answered: this tool asks its one question itself.
- stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
- });
+ } as const;
+ // Nothing a child asks can be answered: this tool asks its one question itself. Only a
+ // value given as input reaches its stdin.
+ const child =
+ options.input === undefined
+ ? spawn(command, args, { ...common, stdio: ["ignore", "pipe", "pipe"] })
+ : spawn(command, args, { ...common, stdio: ["pipe", "pipe", "pipe"] });
let stdout = "";
let stderr = "";
+ if (options.input !== undefined && child.stdin) {
+ // A child that exits before reading its stdin must not take this process down with EPIPE.
+ child.stdin.on("error", () => undefined);
+ child.stdin.end(options.input);
+ }
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => {
@@ -133,5 +160,6 @@ export function realSystem(): System {
nodeVersion: process.versions.node,
sleep: (ms) => delay(ms),
now: () => Date.now(),
+ cwd: process.cwd(),
};
}
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
new file mode 100644
index 0000000..78ec74d
--- /dev/null
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -0,0 +1,714 @@
+import assert from "node:assert/strict";
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { after, describe, test } from "node:test";
+import { parse } from "jsonc-parser";
+import { hideSecrets } from "../src/deploy-track.ts";
+import { main } from "../src/main.ts";
+import { recordPath } from "../src/record.ts";
+import type { HttpRequest, RunOptions } from "../src/system.ts";
+import { type FakeOptions, fakeSystem, readsOnly, WRANGLER } from "./fake.ts";
+
+// Known fake secrets. Each must reach only what the test allows, and nothing else.
+const PAIRWISE_BYTES = Buffer.from("pairwise-bytes-known-to-this-test-only-0123456789").subarray(
+ 0,
+ 48,
+);
+const PAIRWISE = PAIRWISE_BYTES.toString("base64");
+const CLIENT_ID = "dGVzdC1jbGllbnQtaWQtMDEyMzQ1Njc4OQ";
+const CLIENT_SECRET = "gwid_cs_c2VjcmV0LW9mLXRoZS10ZXN0LWNsaWVudC0wMTIzNDU2Nzg5";
+const API_TOKEN = "api-token-known-to-this-test-0123456789";
+const OAUTH_TOKEN = "oauth-token-known-to-this-test-abcdefghij";
+const SECRETS = { PAIRWISE, CLIENT_SECRET, API_TOKEN, OAUTH_TOKEN };
+
+const ID = "https://gateweave-id.rehearsal.workers.dev";
+const TRACK = "https://gateweave-track.rehearsal.workers.dev";
+const ADD_APP = join("scripts", "add-app.ts");
+
+const cleanup: string[] = [];
+after(() => {
+ for (const dir of cleanup) rmSync(dir, { recursive: true, force: true });
+});
+
+interface ConnectFakeOptions extends FakeOptions {
+ /** Secrets each Worker has besides BETTER_AUTH_SECRET. */
+ idSecrets?: string[];
+ trackSecrets?: string[];
+ /** Client ids already registered in ID for Track's redirect URI. */
+ registered?: string[];
+ /** Replaces what the fake apps:add prints. */
+ appsAddOutput?: string;
+ /** A `secret put` of this name fails, echoing its value and the tokens on stderr. */
+ failPut?: string;
+}
+
+/**
+ * Two deployments made by this tool in the fake account, ID and Track, and a fake that also knows
+ * `wrangler secret put`, ID's apps:add, the registration query and the provider's two pages.
+ */
+async function connectFake(options: ConnectFakeOptions = {}) {
+ const fake = fakeSystem({ ...options, env: { CLOUDFLARE_API_TOKEN: API_TOKEN, ...options.env } });
+ cleanup.push(fake.home);
+ const work = mkdtempSync(join(tmpdir(), "gateweave-connect-work-"));
+ const keepDir = mkdtempSync(join(tmpdir(), "gateweave-connect-keep-"));
+ cleanup.push(work, keepDir);
+ const wranglerConfig = join(fake.home, ".wrangler", "config");
+ mkdirSync(wranglerConfig, { recursive: true });
+ const oauthFile = join(wranglerConfig, "default.toml");
+ writeFileSync(
+ oauthFile,
+ `oauth_token = "${OAUTH_TOKEN}"\nrefresh_token = "refresh-0123456789"\n`,
+ );
+
+ const puts: { worker: string; name: string; input: string | undefined }[] = [];
+ const appsAdd: { args: string[]; cwd: string }[] = [];
+ const registrations = [...(options.registered ?? [])];
+ let randomCalls = 0;
+ /** Each file written for a person to keep, with the options the write asked for. */
+ const kept: { path: string; options: { flag: string; mode: number } }[] = [];
+ const secretsOf = (worker: string) => {
+ let set = fake.cloud.secrets.get(worker);
+ if (!set) {
+ set = new Set(["BETTER_AUTH_SECRET"]);
+ fake.cloud.secrets.set(worker, set);
+ }
+ return set;
+ };
+
+ const inner = fake.sys.run;
+ fake.sys.run = async (command: string, args: string[], runOptions: RunOptions) => {
+ const record = () =>
+ fake.calls.push({
+ argv: [command, ...args],
+ cwd: runOptions.cwd,
+ accountId: runOptions.env?.CLOUDFLARE_ACCOUNT_ID,
+ });
+ const at = args.indexOf(`wrangler@${WRANGLER}`);
+ const rest = at >= 0 ? args.slice(at + 1) : [];
+ if (command === fake.sys.execPath && rest[0] === "secret" && rest[1] === "put") {
+ record();
+ const name = rest[2] ?? "";
+ const worker = rest[rest.indexOf("--name") + 1] ?? "";
+ puts.push({ worker, name, input: runOptions.input });
+ if (options.failPut === name) {
+ return {
+ status: 1,
+ stdout: "",
+ stderr: `✘ [ERROR] A request to the Cloudflare API failed: the body ${runOptions.input} was sent with ${API_TOKEN} and ${OAUTH_TOKEN}\n`,
+ };
+ }
+ secretsOf(worker).add(name);
+ return {
+ status: 0,
+ stdout: `🌀 Creating the secret for the Worker "${worker}"\n✨ Success! Uploaded secret ${name}\n`,
+ stderr: "",
+ };
+ }
+ if (
+ command === fake.sys.execPath &&
+ rest[0] === "d1" &&
+ rest[1] === "execute" &&
+ rest.join(" ").includes("oauth_client")
+ ) {
+ record();
+ // It runs in ID's checkout, whose wrangler.jsonc must name ID's database.
+ const config = parse(readFileSync(join(runOptions.cwd, "wrangler.jsonc"), "utf8")) as {
+ d1_databases: { database_name: string; database_id?: string }[];
+ };
+ assert.equal(config.d1_databases[0]?.database_name, "gateweave-id");
+ assert.equal(config.d1_databases[0]?.database_id, "uuid-gateweave-id");
+ return {
+ status: 0,
+ stdout: JSON.stringify([
+ { results: registrations.map((id) => ({ client_id: id })), success: true, meta: {} },
+ ]),
+ stderr: "",
+ };
+ }
+ if (command === fake.sys.execPath && args[0] === ADD_APP) {
+ record();
+ appsAdd.push({ args, cwd: runOptions.cwd });
+ // ID's script runs in apps/web and reaches the database through the checkout's config.
+ const config = readFileSync(join(runOptions.cwd, "..", "..", "wrangler.jsonc"), "utf8");
+ assert.match(config, /"database_name": "gateweave-id"/);
+ assert.equal(runOptions.stream, undefined);
+ if (options.appsAddOutput !== undefined) {
+ registrations.push(CLIENT_ID);
+ return { status: 0, stdout: options.appsAddOutput, stderr: "" };
+ }
+ registrations.push(CLIENT_ID);
+ return {
+ status: 0,
+ stdout: `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\n`,
+ stderr: "",
+ };
+ }
+ const result = await inner(command, args, runOptions);
+ if (
+ command === "git" &&
+ args.includes("clone") &&
+ args.includes("https://github.com/gateweavehq/id.git")
+ ) {
+ const scripts = join(args.at(-1) ?? "", "apps", "web", "scripts");
+ mkdirSync(scripts, { recursive: true });
+ writeFileSync(join(scripts, "add-app.ts"), "// ID's apps:add\n");
+ }
+ return result;
+ };
+
+ const innerFetch = fake.sys.fetch;
+ fake.sys.fetch = async (url: string, request: HttpRequest = {}) => {
+ const { pathname, origin } = new URL(url);
+ if (pathname === "/.well-known/openid-configuration") {
+ fake.events.push(`fetch GET ${url}`);
+ const id = secretsOf("gateweave-id");
+ return id.has("BETTER_AUTH_URL") && id.has("OIDC_PAIRWISE_SECRET")
+ ? { status: 200, headers: {}, text: JSON.stringify({ issuer: origin }) }
+ : { status: 404, headers: {}, text: "" };
+ }
+ if (pathname === "/login" && !url.startsWith(ID)) {
+ fake.events.push(`fetch GET ${url}`);
+ const track = secretsOf("gateweave-track");
+ const on = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"].every((name) =>
+ track.has(name),
+ );
+ return {
+ status: 200,
+ headers: {},
+ text: `Gateweave Track ${on ? "Continue with Gateweave ID " : ""}`,
+ };
+ }
+ return innerFetch(url, request);
+ };
+
+ fake.sys.cwd = work;
+ fake.sys.writeFile = async (path, data, writeOptions) => {
+ kept.push({ path, options: writeOptions });
+ await writeFile(path, data, writeOptions);
+ };
+ fake.sys.random = (bytes: number) => {
+ randomCalls++;
+ assert.equal(bytes, 48);
+ return new Uint8Array(PAIRWISE_BYTES);
+ };
+
+ assert.equal(await main(["deploy", "id", "--yes"], fake.sys), 0);
+ assert.equal(await main(["deploy", "track", "--yes"], fake.sys), 0);
+ for (const name of options.idSecrets ?? []) secretsOf("gateweave-id").add(name);
+ for (const name of options.trackSecrets ?? []) secretsOf("gateweave-track").add(name);
+ fake.output.out = "";
+ fake.output.err = "";
+ const callsBefore = fake.calls.length;
+ const tmpBefore = new Set(readdirSync(tmpdir()));
+
+ async function connect(args: string[]) {
+ fake.output.out = "";
+ fake.output.err = "";
+ const code = await main(["connect", "id", "track", ...args], fake.sys);
+ const result =
+ args.includes("--json") && fake.output.out ? JSON.parse(fake.output.out) : undefined;
+ return { code, result, out: fake.output.out, err: fake.output.err };
+ }
+
+ /** Every file this run could have written to, outside the one the test allows. */
+ function writtenFiles(allowed: readonly string[] = []): string[] {
+ const files: string[] = [];
+ const walk = (dir: string) => {
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const path = join(dir, entry);
+ try {
+ const stat = lstatSync(path);
+ if (stat.isDirectory()) walk(path);
+ else if (stat.isFile()) files.push(path);
+ } catch {
+ // Another test file removed it meanwhile.
+ }
+ }
+ };
+ walk(work);
+ walk(fake.home);
+ for (const entry of readdirSync(tmpdir())) {
+ if (!tmpBefore.has(entry)) walk(join(tmpdir(), entry));
+ }
+ const skip = new Set([oauthFile, ...allowed].map((path) => resolve(path)));
+ return files.filter((path) => !skip.has(resolve(path)));
+ }
+
+ return {
+ fake,
+ work,
+ keepDir,
+ puts,
+ appsAdd,
+ registrations,
+ connect,
+ writtenFiles,
+ randomCalls: () => randomCalls,
+ kept,
+ newCalls: () => fake.calls.slice(callsBefore),
+ };
+}
+
+function leaked(text: string, which: Record = SECRETS): string[] {
+ return Object.entries(which)
+ .filter(([, value]) => text.includes(value))
+ .map(([name]) => name);
+}
+
+function leakedInFiles(files: string[], which: Record = SECRETS): string[] {
+ const found: string[] = [];
+ for (const file of files) {
+ let text: string;
+ try {
+ text = readFileSync(file, "latin1");
+ } catch {
+ continue;
+ }
+ for (const name of leaked(text, which)) found.push(`${name} in ${file}`);
+ }
+ return found;
+}
+
+describe("gateweave connect id track", () => {
+ test("the shared filter hides ID's client secret line, its prefix and OIDC secret assignments", () => {
+ assert.equal(hideSecrets("client secret: abcdefghijkl", []), "client secret: [secret]");
+ assert.equal(hideSecrets(`{"client_secret": "zz zz"}`, []), `{"client_secret": "[secret]"}`);
+ assert.equal(hideSecrets("OIDC_CLIENT_SECRET=xyz123", []), "OIDC_CLIENT_SECRET=[secret]");
+ assert.equal(
+ hideSecrets('OIDC_PAIRWISE_SECRET: "a b c"', []),
+ 'OIDC_PAIRWISE_SECRET: "[secret]"',
+ );
+ assert.equal(hideSecrets("see gwid_cs_abcDEF-_1 here", []), "see [secret] here");
+ });
+
+ test("the secrets reach only the stdin of secret put and the --keep-secret-at file", async () => {
+ const run = await connectFake();
+ const keep = join(run.keepDir, "pairwise.txt");
+ const { code, result, out, err } = await run.connect([
+ "--keep-secret-at",
+ keep,
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 0, err);
+ assert.equal(result.ok, true);
+ assert.equal(result.clientId, CLIENT_ID);
+ assert.equal(result.registeredNow, true);
+ assert.deepEqual(result.id, { worker: "gateweave-id", address: ID, issuer: ID });
+ assert.deepEqual(result.track, { worker: "gateweave-track", address: TRACK });
+ assert.deepEqual(result.pairwiseSecret, {
+ generatedNow: true,
+ keptAt: keep,
+ shownOnTerminal: false,
+ });
+ assert.ok(result.checks.length >= 4);
+ assert.ok(result.checks.every((check: { ok: boolean }) => check.ok));
+
+ // Where each value went: the generated one to ID, the registration's to Track, on stdin.
+ assert.deepEqual(
+ run.puts.map(({ worker, name }) => `${worker} ${name}`),
+ [
+ "gateweave-id BETTER_AUTH_URL",
+ "gateweave-id OIDC_PAIRWISE_SECRET",
+ "gateweave-track OIDC_CLIENT_SECRET",
+ "gateweave-track OIDC_CLIENT_ID",
+ "gateweave-track OIDC_ISSUER",
+ "gateweave-track OIDC_PROVIDER_NAME",
+ "gateweave-track BETTER_AUTH_URL",
+ ],
+ );
+ const input = (name: string) => run.puts.find((put) => put.name === name)?.input;
+ assert.equal(input("OIDC_PAIRWISE_SECRET"), PAIRWISE);
+ assert.equal(input("OIDC_CLIENT_SECRET"), CLIENT_SECRET);
+ assert.equal(input("OIDC_CLIENT_ID"), CLIENT_ID);
+ assert.equal(input("OIDC_ISSUER"), ID);
+ assert.equal(input("OIDC_PROVIDER_NAME"), "Gateweave ID");
+ assert.deepEqual(
+ run.puts.filter((put) => leaked(put.input ?? "").length > 0).map(({ name }) => name),
+ ["OIDC_PAIRWISE_SECRET", "OIDC_CLIENT_SECRET"],
+ );
+ assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`);
+ // Asked for on every platform: new only, and readable by its owner alone. Where the system
+ // keeps modes, the file has it.
+ assert.deepEqual(run.kept, [{ path: keep, options: { flag: "wx", mode: 0o600 } }]);
+ if (process.platform !== "win32") assert.equal(statSync(keep).mode & 0o777, 0o600);
+
+ // Nowhere else: not the screen, not --json, not the record, not a file, not an argument.
+ assert.deepEqual(leaked(out), []);
+ assert.deepEqual(leaked(err), []);
+ assert.deepEqual(leaked(readFileSync(recordPath(run.fake.sys), "utf8")), []);
+ assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []);
+ assert.deepEqual(
+ run.fake.calls.filter(({ argv }) => leaked(argv.join(" ")).length > 0),
+ [],
+ );
+
+ // Registered with ID's own apps:add, the redirect and back-channel logout URIs on Track.
+ assert.equal(run.appsAdd.length, 1);
+ assert.deepEqual(run.appsAdd[0]?.args, [
+ ADD_APP,
+ "--app",
+ "track",
+ "--name",
+ "Gateweave Track",
+ "--redirect-uri",
+ `${TRACK}/api/auth/callback/oidc`,
+ "--backchannel-logout-uri",
+ `${TRACK}/api/auth/backchannel-logout/oidc`,
+ ]);
+ assert.match(run.appsAdd[0]?.cwd ?? "", /[\\/]id[\\/]v0\.50\.0-gateweave-id[\\/]apps[\\/]web$/);
+
+ // The record keeps the client id, never a secret.
+ const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8"));
+ assert.equal(file.deployments.length, 2);
+ assert.deepEqual(
+ file.connections.map(({ clientId, steps }: { clientId: string; steps: string[] }) => ({
+ clientId,
+ steps,
+ })),
+ [{ clientId: CLIENT_ID, steps: ["registered", "connected", "checked"] }],
+ );
+ });
+
+ test("without --keep-secret-at, a terminal shows the pairwise secret once, with words to keep it", async () => {
+ const run = await connectFake({ interactive: true, answer: true });
+ const { code, out, err } = await run.connect([]);
+ assert.equal(code, 0, err);
+ assert.equal(err.split(PAIRWISE).length - 1, 1);
+ assert.match(err, /Keep this value now, in your password manager/);
+ assert.match(err, /gives everyone a new id in every app/);
+ assert.deepEqual(leaked(out), []);
+ assert.deepEqual(leaked(err, { CLIENT_SECRET, API_TOKEN, OAUTH_TOKEN }), []);
+ assert.deepEqual(leakedInFiles(run.writtenFiles()), []);
+ assert.deepEqual(run.fake.questions, ["Make these changes? [y/N] "]);
+ assert.match(out, /signs people in through ID \(gateweave-id\) now/);
+ });
+
+ test("a second run registers nothing again and replaces no secret", async () => {
+ const run = await connectFake();
+ const keep = join(run.keepDir, "pairwise.txt");
+ assert.equal((await run.connect(["--keep-secret-at", keep, "--yes"])).code, 0);
+ const puts = run.puts.length;
+ const second = await run.connect(["--yes", "--json"]);
+ assert.equal(second.code, 0, second.err);
+ assert.equal(second.result.changedNow, false);
+ assert.equal(second.result.registeredNow, false);
+ assert.equal(second.result.clientId, CLIENT_ID);
+ assert.equal(run.appsAdd.length, 1);
+ assert.equal(run.puts.length, puts);
+ assert.equal(run.randomCalls(), 1);
+ assert.equal(run.registrations.length, 1);
+ assert.match(second.err, /An earlier run connected these already; nothing will be changed/);
+ });
+
+ test("apps:add output in another form stops, and nothing it printed is shown", async () => {
+ for (const output of [
+ `Registered Gateweave Track.\nclient id ${CLIENT_ID}\nclient secret ${CLIENT_SECRET}\n`,
+ `Registered Gateweave Track.\nclient id: ${CLIENT_ID}\nclient secret: plain-secret-without-its-prefix-0123456789\n`,
+ `Registered Gateweave Track.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\nclient secret: ${CLIENT_SECRET}\n`,
+ ]) {
+ const run = await connectFake({ appsAddOutput: output });
+ const keep = join(run.keepDir, "pairwise.txt");
+ const { code, result, out, err } = await run.connect([
+ "--keep-secret-at",
+ keep,
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 8);
+ assert.equal(result.code, "register-output-unreadable");
+ for (const text of [out, err]) {
+ assert.doesNotMatch(text, /Registered Gateweave Track/);
+ assert.ok(!text.includes(CLIENT_ID), "the captured client id is not shown");
+ assert.ok(!text.includes("plain-secret-without-its-prefix"));
+ assert.deepEqual(leaked(text), []);
+ }
+ assert.deepEqual(
+ run.puts.filter(({ worker }) => worker === "gateweave-track"),
+ [],
+ "Track is given nothing",
+ );
+ assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []);
+ }
+ });
+
+ test("settings already set are left alone", async () => {
+ const run = await connectFake({
+ idSecrets: ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"],
+ trackSecrets: ["BETTER_AUTH_URL", "OIDC_PROVIDER_NAME"],
+ });
+ // No pairwise secret is made, so --json needs no file to keep one in.
+ const { code, result, err } = await run.connect(["--yes", "--json"]);
+ assert.equal(code, 0, err);
+ assert.deepEqual(
+ run.puts.map(({ worker, name }) => `${worker} ${name}`),
+ [
+ "gateweave-track OIDC_CLIENT_SECRET",
+ "gateweave-track OIDC_CLIENT_ID",
+ "gateweave-track OIDC_ISSUER",
+ ],
+ );
+ assert.equal(run.randomCalls(), 0);
+ assert.equal(result.pairwiseSecret.generatedNow, false);
+ assert.deepEqual(
+ result.settings
+ .filter(({ setNow }: { setNow: boolean }) => !setNow)
+ .map(({ product, name }: { product: string; name: string }) => `${product} ${name}`),
+ [
+ "id BETTER_AUTH_URL",
+ "id OIDC_PAIRWISE_SECRET",
+ "track OIDC_PROVIDER_NAME",
+ "track BETTER_AUTH_URL",
+ ],
+ );
+ assert.match(err, /OIDC_PAIRWISE_SECRET\s+\(already set; left as it is\)/);
+ assert.match(err, /OIDC_PROVIDER_NAME\s+\(already set; left as it is\)/);
+ assert.doesNotMatch(err, /issuer, ID's BETTER_AUTH_URL .* can never change/);
+ });
+
+ test("the plan names both deployments, both addresses and every setting, and waits", async () => {
+ const run = await connectFake();
+ const { code, err } = await run.connect(["--keep-secret-at", join(run.keepDir, "k")]);
+ assert.equal(code, 7);
+ for (const text of [
+ /Connect Track to ID in the Cloudflare account Rehearsal \(a1b2c3\)/,
+ /ID\s+gateweave-id\s+at https:\/\/gateweave-id\.rehearsal\.workers\.dev/,
+ /Track\s+gateweave-track\s+at https:\/\/gateweave-track\.rehearsal\.workers\.dev/,
+ /On ID \(gateweave-id\):\n\s+BETTER_AUTH_URL\s+https:\/\/gateweave-id\.rehearsal\.workers\.dev\s+\(set now\)/,
+ /OIDC_PAIRWISE_SECRET\s+generated here, kept at .*k, never shown\s+\(set now\)/,
+ /redirect URI\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev\/api\/auth\/callback\/oidc/,
+ /back-channel logout\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev\/api\/auth\/backchannel-logout\/oidc/,
+ /OIDC_CLIENT_SECRET\s+from the registration, never shown\s+\(set now\)/,
+ /OIDC_CLIENT_ID\s+from the registration\s+\(set now\)/,
+ /OIDC_ISSUER\s+https:\/\/gateweave-id\.rehearsal\.workers\.dev\s+\(set now\)/,
+ /OIDC_PROVIDER_NAME\s+Gateweave ID\s+\(set now\)/,
+ /On Track \(gateweave-track\):[\s\S]*BETTER_AUTH_URL\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev \(this also turns MCP on\)\s+\(set now\)/,
+ /Nothing was changed: there is no terminal/,
+ ]) {
+ assert.match(err, text);
+ }
+ // Before the yes it only read: listings, the one SELECT, outside pages, and the release cache.
+ const changes = run
+ .newCalls()
+ .filter((call) => !readsOnly(call) && !call.argv.includes("clone"));
+ assert.deepEqual(changes, []);
+ assert.deepEqual(run.puts, []);
+ assert.equal(run.appsAdd.length, 0);
+ assert.ok(!existsSync(join(run.keepDir, "k")));
+ });
+
+ test("on workers.dev the plan warns about the issuer and about Workers that cannot reach each other", async () => {
+ const run = await connectFake();
+ const { code, err } = await run.connect(["--keep-secret-at", join(run.keepDir, "k")]);
+ assert.equal(code, 7);
+ assert.match(
+ err,
+ /Warning: The issuer, ID's BETTER_AUTH_URL \(https:\/\/gateweave-id\.rehearsal\.workers\.dev\), can never change once any app has signed anyone in/,
+ );
+ assert.match(
+ err,
+ /Warning: The issuer https:\/\/gateweave-id\.rehearsal\.workers\.dev is a workers\.dev address/,
+ );
+ assert.match(
+ err,
+ /Two Workers on workers\.dev cannot reach each other unless each has global_fetch_strictly_public/,
+ );
+ assert.match(err, /ID's back-channel logout cannot reach Track/);
+ assert.match(err, /A Custom Domain on each Worker is the setup that works/);
+
+ const custom = await connectFake();
+ const own = await custom.connect([
+ "--id-url",
+ "https://id.example.com",
+ "--track-url",
+ "https://track.example.com",
+ "--keep-secret-at",
+ join(custom.keepDir, "k"),
+ ]);
+ assert.equal(own.code, 7);
+ assert.match(own.err, /can never change once any app has signed anyone in/);
+ assert.doesNotMatch(own.err, /workers\.dev/);
+ assert.match(
+ own.err,
+ /redirect URI\s+https:\/\/track\.example\.com\/api\/auth\/callback\/oidc/,
+ );
+ });
+
+ test("--json without --keep-secret-at refuses, as does a run with no terminal", async () => {
+ const run = await connectFake();
+ const { code, result, err } = await run.connect(["--yes", "--json"]);
+ assert.equal(code, 2);
+ assert.equal(result.ok, false);
+ assert.equal(result.code, "keep-path-needed");
+ assert.match(result.reason, /With --json it is never printed/);
+ assert.deepEqual(leaked(err), []);
+ const plain = await run.connect(["--yes"]);
+ assert.equal(plain.code, 2);
+ assert.match(plain.err, /Without a terminal it would land in a log/);
+ assert.deepEqual(run.puts, []);
+ assert.equal(run.randomCalls(), 0);
+ });
+
+ test("a --keep-secret-at path inside the working directory is refused before anything runs", async () => {
+ const run = await connectFake();
+ for (const path of [
+ join(run.work, "pairwise.txt"),
+ "pairwise.txt",
+ join("..", "x", "..", run.work.split(/[\\/]/).at(-1) ?? "", "k"),
+ ]) {
+ const { code, result } = await run.connect(["--keep-secret-at", path, "--yes", "--json"]);
+ assert.equal(code, 2, path);
+ assert.equal(result.code, "keep-path-inside", path);
+ }
+ assert.deepEqual(run.newCalls(), []);
+ assert.deepEqual(readdirSync(run.work), []);
+ });
+
+ test("a --keep-secret-at file that exists is never overwritten", async () => {
+ const run = await connectFake();
+ const keep = join(run.keepDir, "kept.txt");
+ writeFileSync(keep, "a value someone kept\n");
+ const { code, result } = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]);
+ assert.equal(code, 2);
+ assert.equal(result.code, "keep-path-exists");
+ assert.equal(readFileSync(keep, "utf8"), "a value someone kept\n");
+ });
+
+ test("Track registered in ID without Track's secret stops, says how to recover and registers nothing", async () => {
+ const run = await connectFake({ registered: [CLIENT_ID] });
+ const { code, result } = await run.connect([
+ "--keep-secret-at",
+ join(run.keepDir, "k"),
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "registered-without-secret");
+ assert.match(result.reason, /never registers Track a second time/);
+ assert.match(result.reason, /secret put OIDC_CLIENT_SECRET --name gateweave-track/);
+ assert.match(
+ result.reason,
+ new RegExp(`DELETE FROM oauth_client WHERE client_id = '${CLIENT_ID}'`),
+ );
+ assert.equal(run.appsAdd.length, 0);
+ assert.deepEqual(run.puts, []);
+ });
+
+ test("a Track that already has another provider's client is not changed", async () => {
+ const run = await connectFake({
+ trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"],
+ });
+ const { code, result } = await run.connect([
+ "--keep-secret-at",
+ join(run.keepDir, "k"),
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "track-has-provider");
+ assert.match(result.reason, /replaces no secret/);
+ assert.equal(run.appsAdd.length, 0);
+ assert.deepEqual(run.puts, []);
+ });
+
+ test("a child process that echoes a secret or a token is filtered", async () => {
+ const run = await connectFake({ failPut: "OIDC_CLIENT_SECRET" });
+ const keep = join(run.keepDir, "pairwise.txt");
+ const { code, result, out, err } = await run.connect([
+ "--keep-secret-at",
+ keep,
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 8);
+ assert.equal(result.code, "client-secret-not-set");
+ assert.match(result.reason, /the body \[secret\] was sent with \[secret\] and \[secret\]/);
+ assert.match(result.reason, /DELETE FROM oauth_client/);
+ assert.deepEqual(leaked(out), []);
+ assert.deepEqual(leaked(err), []);
+ const [connection] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections;
+ assert.equal(connection.clientId, CLIENT_ID);
+ assert.deepEqual(connection.steps, ["registered"]);
+ assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []);
+
+ // The generated value, echoed by a failed put, is filtered too, and its file goes again.
+ const pairwise = await connectFake({ failPut: "OIDC_PAIRWISE_SECRET" });
+ const kept = join(pairwise.keepDir, "pairwise.txt");
+ const failed = await pairwise.connect(["--keep-secret-at", kept, "--yes", "--json"]);
+ assert.equal(failed.code, 8);
+ assert.equal(failed.result.code, "secret-put-failed");
+ assert.match(failed.result.reason, /the body \[secret\] was sent/);
+ assert.deepEqual(leaked(failed.out), []);
+ assert.deepEqual(leaked(failed.err), []);
+ assert.ok(!existsSync(kept), "a value that was never set is not left to be kept");
+ assert.equal(pairwise.appsAdd.length, 0);
+ });
+
+ test("doctor reports the connection on both sides", async () => {
+ const run = await connectFake();
+ assert.equal(
+ (await run.connect(["--keep-secret-at", join(run.keepDir, "k"), "--yes"])).code,
+ 0,
+ );
+ const findings = async (product: string) => {
+ run.fake.output.out = "";
+ await main(["doctor", product, "--json"], run.fake.sys);
+ return JSON.parse(run.fake.output.out) as { id: string; status: string; message: string }[];
+ };
+ const track = (await findings("track")).find(({ id }) => id === "sign-in-provider");
+ assert.equal(track?.status, "ok");
+ assert.match(
+ track?.message ?? "",
+ new RegExp(
+ `through ID gateweave-id \\(${ID.replaceAll(".", "\\.")}, client id ${CLIENT_ID}\\)`,
+ ),
+ );
+ const id = (await findings("id")).find(({ id: found }) => found === "oidc-provider");
+ assert.equal(id?.status, "ok");
+ assert.match(
+ id?.message ?? "",
+ /with the issuer https:\/\/gateweave-id\.rehearsal\.workers\.dev/,
+ );
+ assert.match(
+ id?.message ?? "",
+ new RegExp(`Track gateweave-track \\(client id ${CLIENT_ID}\\)`),
+ );
+
+ // Half a setup is a fail, with the command that finishes it.
+ run.fake.cloud.secrets.get("gateweave-track")?.delete("OIDC_CLIENT_SECRET");
+ const half = (await findings("track")).find(({ id: found }) => found === "sign-in-provider");
+ assert.equal(half?.status, "fail");
+ assert.match(half?.message ?? "", /OIDC_CLIENT_SECRET is not set/);
+ });
+
+ test("options of other commands are refused, and the new options only belong to connect", async () => {
+ const run = await connectFake();
+ assert.equal((await run.connect(["--name", "x"])).code, 2);
+ assert.equal((await run.connect(["--id-url", "http://id.example.com"])).code, 2);
+ assert.equal((await run.connect(["--id-url", "https://id.example.com/path"])).code, 2);
+ assert.equal(
+ await main(["deploy", "track", "--id-url", "https://id.example.com"], run.fake.sys),
+ 2,
+ );
+ assert.equal(await main(["doctor", "id", "--keep-secret-at", "x"], run.fake.sys), 2);
+ assert.deepEqual(run.newCalls(), []);
+ });
+});
diff --git a/packages/cli/test/source.test.ts b/packages/cli/test/source.test.ts
index 59502cf..e3af115 100644
--- a/packages/cli/test/source.test.ts
+++ b/packages/cli/test/source.test.ts
@@ -6,6 +6,16 @@ import { fileURLToPath } from "node:url";
const src = fileURLToPath(new URL("../src", import.meta.url));
+const RANDOM = /randomBytes|randomUUID|getRandomValues/;
+const SECRET_PUT = /"secret",\s*"put"/;
+
+/**
+ * The exception in invariant 5 of AGENTS.md: `connect` does what both products' self-hosting guides
+ * describe by hand, and makes one value, ID's OIDC_PAIRWISE_SECRET. So connect.ts, and no other
+ * file, may make a random value and give a value to `wrangler secret put`.
+ */
+const CONNECTING = new Map([["connect.ts", [RANDOM, SECRET_PUT]]]);
+
// The product's own deploy does these; the tool holds no copy of that logic.
test("the source never deploys, migrates or makes a secret itself", () => {
for (const file of readdirSync(src)) {
@@ -16,10 +26,19 @@ test("the source never deploys, migrates or makes a secret itself", () => {
// Any `d1 migrations ` other than `list`: apply, or a subcommand held in a variable.
/["'`]d1["'`]\s*,\s*["'`]migrations["'`](?!\s*,\s*["'`]list["'`])/,
/--secrets-file/,
- /randomBytes|randomUUID|getRandomValues/,
- /"secret",\s*"put"/,
+ RANDOM,
+ SECRET_PUT,
]) {
+ if (CONNECTING.get(file)?.includes(pattern)) continue;
assert.doesNotMatch(text, pattern, `${file} matches ${pattern}`);
}
}
});
+
+test("only connect.ts makes a secret, and it hands each one to Wrangler on stdin", () => {
+ const text = readFileSync(join(src, "connect.ts"), "utf8");
+ assert.match(text, RANDOM);
+ // Every `secret put` goes through one helper, whose value is the run's input, never an argument.
+ assert.equal(text.match(/"secret", "put"/g)?.length, 1);
+ assert.match(text, /\["secret", "put", name, "--name", worker\], cache, value\)/);
+});
From 8220ceb146a3fd9d4030fdf8e481fe622be91467 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:09:13 +0100
Subject: [PATCH 02/14] docs(cli): say why both of Wrangler's folders are read
Reading both roots is a superset of Wrangler's own rule. The folders are
read only to learn values to hide, so hiding one more costs nothing, and
missing the one Wrangler uses would print a token.
---
packages/cli/src/deploy-track.ts | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index 595ec7c..c9a0ad0 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -604,7 +604,9 @@ export async function outputGuard(sys: System, names: () => readonly string[] =
* is: the legacy `~/.wrangler` when that folder exists, otherwise `.wrangler` in its XDG config
* folder (`%APPDATA%\xdg.config` on Windows, `~/Library/Preferences` on macOS, `~/.config` on
* Linux, each replaced by `XDG_CONFIG_HOME` when that is set). Both are read, so whichever one the
- * installed Wrangler chose is covered.
+ * installed Wrangler chose is covered. That is a superset of Wrangler's rule on purpose: these
+ * folders are read only to learn values to hide, and hiding a value from a sign-in Wrangler no
+ * longer uses costs nothing, while missing the one it uses would print a token.
*/
function wranglerConfigFolders(sys: System): string[] {
const set = (name: string) => sys.env[name] || undefined;
From e0e2e8b8714bb7f5dacdb99c828a191f54d4a0da Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:09:14 +0100
Subject: [PATCH 03/14] fix(cli): connect proves what is set before it changes
anything
- --no-account-name, as deploy has it: the plan, errors and --json name
the account by id.
- "Already set" is proof: secrets and every binding of the deployed
version, text variables included. A failed look, listings that
disagree or a split deployment stop the run. A visible button is no
longer taken for a setting, and a provider name that cannot be read
stops the run instead of loosening the check.
- The plan names ID's database by name and id; a deployment recorded as
external is used only when named.
- The keep path is decided after knowing whether a value is made, made
new without following a link, and checked again where its folder
really leads once opened. The terminal copy comes before the put.
- apps:add is read only in its exact three-line form, and nothing it
printed reaches an error.
- The registration query also matches the app id, and quotes its
address; the recovery covers a Track that still holds OIDC settings.
- The client id is on record before Track is given anything, and the
client secret is tried three times.
- One run at a time, with a lock file beside the record.
- Children start without NODE_DEBUG or WRANGLER_LOG_SANITIZE, and every
command stops while NODE_DEBUG is set.
- Doctor checks at the connection's addresses, looks for the exact
button and the issuer in Track's page policy, says the client id
cannot be read, and doctor id reads ID's database for it.
- A URL with a name and password is not repeated.
- The workers.dev warning names the calling Worker that lacks
global_fetch_strictly_public.
---
packages/cli/src/checks.ts | 27 +
packages/cli/src/connect.ts | 748 ++++++++++++++------
packages/cli/src/doctor-track.ts | 223 ++++--
packages/cli/src/lock.ts | 110 +++
packages/cli/src/main.ts | 18 +-
packages/cli/src/registration.ts | 48 ++
packages/cli/src/system.ts | 30 +-
packages/cli/test/connect-id-track.test.ts | 771 +++++++++++++++++----
packages/cli/test/fake.ts | 2 +
packages/cli/test/registration.test.ts | 110 +++
packages/cli/test/system.test.ts | 61 ++
11 files changed, 1745 insertions(+), 403 deletions(-)
create mode 100644 packages/cli/src/lock.ts
create mode 100644 packages/cli/src/registration.ts
create mode 100644 packages/cli/test/registration.test.ts
create mode 100644 packages/cli/test/system.test.ts
diff --git a/packages/cli/src/checks.ts b/packages/cli/src/checks.ts
index c3f4bbb..52f09f0 100644
--- a/packages/cli/src/checks.ts
+++ b/packages/cli/src/checks.ts
@@ -181,6 +181,33 @@ export async function providerButtons(sys: System, address: string): Promise {
+ try {
+ const page = await sys.fetch(new URL("/login", address).href);
+ const policy = Object.entries(page.headers).find(
+ ([name]) => name.toLowerCase() === "content-security-policy",
+ )?.[1];
+ if (page.status !== 200 || !policy) return null;
+ const images = policy
+ .split(";")
+ .map((directive) => directive.trim().split(/\s+/))
+ .find(([name]) => name === "img-src");
+ if (!images) return null;
+ return images
+ .slice(1)
+ .filter((source) => /^https?:\/\//.test(source))
+ .filter((source) => source !== "https://avatars.githubusercontent.com");
+ } catch {
+ return null;
+ }
+}
+
/**
* Runs every check against the address, retrying each for up to `withinMs` while a new
* `workers.dev` address comes up.
diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts
index 879533b..ab19cbe 100644
--- a/packages/cli/src/connect.ts
+++ b/packages/cli/src/connect.ts
@@ -1,21 +1,19 @@
import { randomBytes } from "node:crypto";
-import { access, chmod, lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
+import { constants, type Stats } from "node:fs";
+import { access, type FileHandle, lstat, mkdir, open, realpath, rm } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { type CheckResult, discoveredIssuer, ID_PROVIDER_NAME, providerButtons } from "./checks.ts";
+import { type Account, chooseAccount, confirm, json, outputGuard, plain } from "./deploy-track.ts";
import {
- type CheckResult,
- discoveredIssuer,
- ID_PROVIDER_NAME,
- mcpIsOn,
- providerButtons,
-} from "./checks.ts";
-import { chooseAccount, confirm, json, outputGuard, plain } from "./deploy-track.ts";
-import {
+ databaseId,
ensureCheckout,
type Finding,
idProviderFindings,
+ readRegistrations,
trackSignInFindings,
} from "./doctor-track.ts";
import { CliError } from "./errors.ts";
+import { takeLock } from "./lock.ts";
import { cacheDir, npxCli } from "./paths.ts";
import { PRODUCTS, type ProductKey } from "./products.ts";
import {
@@ -25,6 +23,14 @@ import {
listRecords,
saveConnection,
} from "./record.ts";
+import {
+ backchannelLogoutUri,
+ callbackUri,
+ readClientIds,
+ sqlString,
+ TRACK_APP,
+ trackRegistrationSql,
+} from "./registration.ts";
import { type Pins, readPins, releaseTags } from "./release.ts";
import type { RunResult, System } from "./system.ts";
@@ -35,11 +41,13 @@ export interface ConnectOptions {
trackUrl?: string;
/** Where to write OIDC_PAIRWISE_SECRET when this run makes it. Never inside the working directory. */
keepSecretAt?: string;
- /** The recorded ID Worker, when the account holds more than one. */
+ /** The recorded ID Worker, when the account holds more than one, or the one recorded external. */
idName?: string;
- /** The recorded Track Worker, when the account holds more than one. */
+ /** The recorded Track Worker, when the account holds more than one, or the one recorded external. */
trackName?: string;
account?: string;
+ /** Whether the account's name may appear in the output. */
+ accountName: boolean;
yes: boolean;
json: boolean;
}
@@ -55,7 +63,8 @@ export interface ConnectSetting {
export interface ConnectResult {
ok: true;
- account: { id: string; name: string };
+ /** The name only when --no-account-name was not given. */
+ account: { id: string; name?: string };
id: { worker: string; address: string; issuer: string };
track: { worker: string; address: string };
/** What ID gave Track. Not a secret; the client secret is never part of the result. */
@@ -69,22 +78,27 @@ export interface ConnectResult {
checks: CheckResult[];
}
-/** The app id and name Track is registered under, as in ID's own example. */
-const APP = { id: "track", name: "Gateweave Track" } as const;
+/** The name Track is registered under, as in ID's own example. */
+const APP_NAME = "Gateweave Track";
const PAIRWISE = "OIDC_PAIRWISE_SECRET";
const TRACK_OIDC = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const;
+const STRICTLY_PUBLIC = "global_fetch_strictly_public";
/**
- * The two lines of ID's `apps:add` that carry the result (apps/web/scripts/add-app.ts). Its client
- * ids are 24 random bytes and its secrets 32, both base64url; the secret carries ID's prefix.
+ * All that ID's `apps:add` prints when it registers an app (apps/web/scripts/add-app.ts): three
+ * lines and nothing else. Its client ids are 24 random bytes and its secrets 32, both base64url,
+ * the secret behind ID's prefix. Anything else, a line more or a value of another shape, is not
+ * read at all, so a secret can never be taken for the client id.
*/
-const CLIENT_ID_LINE = /^client id:\s+([A-Za-z0-9_-]{16,})$/;
-const CLIENT_SECRET_LINE = /^client secret:\s+(gwid_cs_[A-Za-z0-9_-]{32,})$/;
+const APPS_ADD_OUTPUT = new RegExp(
+ `^Registered ${APP_NAME}\\. The secret is shown this once, and only its hash is kept\\.\\nclient id: {5}([A-Za-z0-9_-]{32})\\nclient secret: (gwid_cs_[A-Za-z0-9_-]{43})\\n?$`,
+);
/**
* An address as the origin it names. Anything after the host would make a different issuer and
- * different redirect URIs, so a path, a query or a name and password is refused, not dropped.
+ * different redirect URIs, so a path, a query or a name and password is refused, not dropped. A
+ * value that may hold a password is never repeated.
*/
export function originOf(value: string, what: string): string {
let url: URL | null = null;
@@ -93,10 +107,15 @@ export function originOf(value: string, what: string): string {
} catch {
url = null;
}
+ if (url && (url.username !== "" || url.password !== "")) {
+ throw new CliError(
+ "usage",
+ "bad-url",
+ `${what} holds a name or a password. It is not repeated here; give the address alone: https://, with nothing after the host.`,
+ );
+ }
if (
url?.protocol !== "https:" ||
- url.username !== "" ||
- url.password !== "" ||
url.search !== "" ||
url.hash !== "" ||
url.pathname !== "/" ||
@@ -105,7 +124,7 @@ export function originOf(value: string, what: string): string {
throw new CliError(
"usage",
"bad-url",
- `${what} "${value}" is not an address: use https://, with nothing after the host.`,
+ `${what}${value.includes("@") ? "" : ` "${value}"`} is not an address: use https://, with nothing after the host.`,
);
}
return url.origin;
@@ -125,6 +144,7 @@ function inside(base: string, target: string): boolean {
/**
* The file OIDC_PAIRWISE_SECRET is kept in. It must be outside the working directory, so it cannot
* be committed with a project, in a folder that exists, and new: a kept secret is never overwritten.
+ * Checked here for the plan, and again where it is opened.
*/
async function keepPath(sys: System, given: string): Promise {
const cwd = resolve(sys.cwd ?? process.cwd());
@@ -161,6 +181,64 @@ async function keepPath(sys: System, given: string): Promise {
return path;
}
+const sameFile = (a: Stats, b: Stats) => a.ino === b.ino && a.dev === b.dev;
+
+/**
+ * Writes the value a person is to keep. The file is made new (never through a link in its last
+ * part, never over a file), readable by its owner alone; then, opened, it is looked for again
+ * where its folder really is now, so a folder changed since the plan cannot carry it into the
+ * working directory unseen. Nothing is written until that holds.
+ */
+async function writeKept(sys: System, path: string, value: string): Promise {
+ const cwd = resolve(sys.cwd ?? process.cwd());
+ const realCwd = await realpath(cwd).catch(() => cwd);
+ const flags =
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);
+ let handle: FileHandle;
+ try {
+ handle = await (sys.openNew ?? open)(path, flags, 0o600);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ throw code === "EEXIST"
+ ? new CliError(
+ "usage",
+ "keep-path-exists",
+ `${path} appeared after the plan was shown. This tool never overwrites a file that may hold a kept secret. Nothing was set on ID for ${PAIRWISE}; run again with a new path.`,
+ )
+ : new CliError(
+ "requirement",
+ "keep-path-unwritable",
+ `Could not write ${path} (${code ?? "error"}). Nothing was set on ID for ${PAIRWISE}.`,
+ );
+ }
+ let opened: Stats | null = null;
+ let written = false;
+ try {
+ opened = await handle.stat();
+ const folder = await realpath(dirname(path));
+ const there = await lstat(join(folder, basename(path)));
+ const same = there.isFile() && sameFile(there, opened);
+ if (!same || inside(cwd, folder) || inside(realCwd, folder)) {
+ throw new CliError(
+ "usage",
+ "keep-path-moved",
+ `${path} no longer leads where it was checked to: its folder changed after the plan, and now ${same ? "lies inside the folder you run this from" : "leads somewhere else"}. Nothing was written to it, and nothing was set on ID for ${PAIRWISE}. Choose a path in a folder nobody else changes.`,
+ );
+ }
+ await handle.writeFile(`${value}\n`);
+ if (sys.platform !== "win32") await handle.chmod(0o600);
+ await handle.sync();
+ written = true;
+ } finally {
+ await handle.close();
+ if (!written && opened) {
+ // The empty file this run made goes again, wherever its folder now leads.
+ const now = await lstat(path).catch(() => null);
+ if (now && sameFile(now, opened)) await rm(path, { force: true });
+ }
+ }
+}
+
async function exists(path: string): Promise {
return access(path).then(
() => true,
@@ -168,7 +246,10 @@ async function exists(path: string): Promise {
);
}
-/** The recorded deployment of a product in the account: the one named, or the only one. */
+/**
+ * The recorded deployment of a product in the account: the one named, or the only one this tool
+ * deployed. A deployment `update` recorded without having made it is used only when named.
+ */
async function pickRecord(
sys: System,
accountId: string,
@@ -205,6 +286,13 @@ async function pickRecord(
`${accountLabel} holds several ${label} deployments: ${records.map(({ worker }) => worker).join(", ")}. Choose one with ${option} .`,
);
}
+ if (only.external === true) {
+ throw new CliError(
+ "usage",
+ "deployment-not-named",
+ `The only ${label} deployment on record, ${only.worker}, is one this tool did not make (\`gateweave update\` recorded it). It is changed only when named: run again with ${option} ${only.worker}.`,
+ );
+ }
return only;
}
@@ -232,23 +320,28 @@ async function waitFor(
}
}
+/** A binding of the deployed Worker: a secret, a text variable, or anything else by its type. */
+interface Binding {
+ type: string;
+ /** A text variable's value. Secrets have none: Cloudflare never shows one back. */
+ text?: string;
+}
+
+/** What a deployed Worker has, as its deployed version says: every binding, and its flags. */
+interface Deployed {
+ bindings: Map;
+ flags: string[];
+}
+
/**
* Connects a Track deployment to an ID deployment, so Track signs people in through ID: turns on
* ID's provider, registers Track with ID's own `apps:add`, and gives Track the result.
*/
export async function connectIdTrack(sys: System, options: ConnectOptions): Promise {
- const say = (line = "") => sys.err(`${line}\n`);
- const npx = npxCli(sys);
- const cache = cacheDir(sys);
- await mkdir(cache, { recursive: true });
-
// What can be refused before anything is asked of Cloudflare.
const idGiven = options.idUrl !== undefined ? originOf(options.idUrl, "--id-url") : null;
const trackGiven =
options.trackUrl !== undefined ? originOf(options.trackUrl, "--track-url") : null;
- const keepAt =
- options.keepSecretAt !== undefined ? await keepPath(sys, options.keepSecretAt) : null;
-
const nodeMajor = Number(sys.nodeVersion.split(".")[0]);
if (nodeMajor < 22) {
throw new CliError(
@@ -257,6 +350,26 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
`Node ${sys.nodeVersion} is too old: use Node 22 or newer.`,
);
}
+ // One run at a time: two could both make the pairwise secret, or both register Track.
+ const release = await takeLock(sys, "connect-id-track");
+ try {
+ return await connect(sys, options, idGiven, trackGiven);
+ } finally {
+ await release();
+ }
+}
+
+async function connect(
+ sys: System,
+ options: ConnectOptions,
+ idGiven: string | null,
+ trackGiven: string | null,
+): Promise {
+ const say = (line = "") => sys.err(`${line}\n`);
+ const npx = npxCli(sys);
+ const cache = cacheDir(sys);
+ await mkdir(cache, { recursive: true });
+
const git = await sys.run("git", ["--version"], { cwd: cache, env: sys.env });
if (git.status !== 0) {
throw new CliError("requirement", "git-missing", "git is not installed or not on the PATH.");
@@ -272,8 +385,11 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
// The shared output filter: the API token and Wrangler's sign-in from the start, and below, what
// this run generates and what ID's apps:add returns. Everything shown passes through it. The
- // account name is shown by design, as in doctor.
- const guard = await outputGuard(sys);
+ // account's name is shown unless --no-account-name keeps it out, as in deploy.
+ const showName = options.accountName;
+ const reachable: { accounts: Account[] } = { accounts: [] };
+ const hiddenNames = () => (showName ? [] : reachable.accounts.map(({ name }) => name));
+ const guard = await outputGuard(sys, hiddenNames);
const { hide } = guard;
const latest = (await releaseTags(sys, cache, PRODUCTS.id))[0];
@@ -295,9 +411,13 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
(args) => wranglerAt(latestPins)(args),
latestPins,
options.account,
+ showName,
+ reachable,
);
env = { ...sys.env, CLOUDFLARE_ACCOUNT_ID: account.id };
- const accountLabel = `the Cloudflare account ${account.name} (${account.id})`;
+ const accountLabel = showName
+ ? `the Cloudflare account ${account.name} (${account.id})`
+ : `the Cloudflare account ${account.id}`;
const idRecord = await pickRecord(sys, account.id, accountLabel, "id", options.idName);
const trackRecord = await pickRecord(sys, account.id, accountLabel, "track", options.trackName);
@@ -318,7 +438,14 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
let idAddress = idGiven ?? recordedAddress(idRecord, "--id-url");
const trackAddress = trackGiven ?? recordedAddress(trackRecord, "--track-url");
- // Looks, changing nothing.
+ // Looks, changing nothing. A look that fails stops the run: a setting it could not see is never
+ // taken for one that is not there.
+ const unseen = (worker: string, why: string) =>
+ new CliError(
+ "requirement",
+ "lookup-failed",
+ `Could not read the settings of ${worker}: ${why}. This tool sets only what it has seen is not set. Nothing was changed.`,
+ );
const listSecrets = async (
wrangler: ReturnType,
worker: string,
@@ -332,28 +459,136 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
`The Worker ${worker} is not in ${accountLabel} any more. Nothing was changed.`,
);
}
- throw new CliError(
- "requirement",
- "lookup-failed",
- `Could not list the secrets of ${worker}: ${hide(lastLine(listed.stderr))}`,
- );
+ throw unseen(worker, `Wrangler's secret list failed (${hide(lastLine(listed.stderr))})`);
}
try {
return new Set(json<{ name: string }[]>(listed.stdout).map(({ name }) => name));
} catch {
+ throw unseen(worker, "Wrangler's secret list was not JSON");
+ }
+ };
+ // The secrets, and from the deployed version every binding: text variables show only there.
+ const readDeployed = async (
+ wrangler: ReturnType,
+ worker: string,
+ ): Promise => {
+ const secrets = await listSecrets(wrangler, worker);
+ const status = await wrangler(["deployments", "status", "--name", worker, "--json"]);
+ if (status.status !== 0) {
+ throw unseen(
+ worker,
+ `Wrangler's deployments status failed (${hide(lastLine(status.stderr))})`,
+ );
+ }
+ let versions: string[];
+ try {
+ const latestDeployment = json<{ versions?: { version_id?: unknown }[] }>(status.stdout);
+ versions = (latestDeployment.versions ?? []).map(({ version_id }) => String(version_id));
+ } catch {
+ throw unseen(worker, "Wrangler's deployments status was not JSON");
+ }
+ const [version, ...others] = versions;
+ if (!version || !/^[0-9a-f][0-9a-f-]{7,63}$/i.test(version)) {
+ throw unseen(worker, "its deployment names no version");
+ }
+ if (others.length > 0) {
throw new CliError(
"requirement",
- "lookup-failed",
- `Could not read the secrets of ${worker}: Wrangler's list was not JSON.`,
+ "gradual-deployment",
+ `${worker} is in a gradual deployment across ${versions.length} versions, so which settings it has depends on the request. Finish it with \`npx wrangler versions deploy\`, then run this again. Nothing was changed.`,
);
}
+ const view = await wrangler(["versions", "view", version, "--name", worker, "--json"]);
+ if (view.status !== 0) {
+ throw unseen(worker, `Wrangler's versions view failed (${hide(lastLine(view.stderr))})`);
+ }
+ let deployed: Deployed;
+ try {
+ const read = json<{
+ resources?: {
+ bindings?: { type?: unknown; name?: unknown; text?: unknown }[];
+ script_runtime?: { compatibility_flags?: unknown };
+ };
+ }>(view.stdout);
+ const bindings = read.resources?.bindings;
+ if (!Array.isArray(bindings)) throw new Error("no bindings");
+ const flags = read.resources?.script_runtime?.compatibility_flags ?? [];
+ if (!Array.isArray(flags)) throw new Error("no flags");
+ deployed = {
+ bindings: new Map(
+ bindings.map(({ type, name, text }) => [
+ String(name),
+ { type: String(type), ...(typeof text === "string" ? { text } : {}) },
+ ]),
+ ),
+ flags: flags.map(String),
+ };
+ } catch {
+ throw unseen(worker, "Wrangler's versions view could not be read");
+ }
+ // Two listings that disagree are not proof of either.
+ for (const name of secrets) {
+ if (deployed.bindings.get(name)?.type !== "secret_text") {
+ throw unseen(worker, `its secret ${name} is not in the deployed version`);
+ }
+ }
+ return deployed;
+ };
+ const idDeployed = await readDeployed(idWrangler, idRecord.worker);
+ const trackDeployed = await readDeployed(trackWrangler, trackRecord.worker);
+ /** How a setting is held: "secret", "text", another binding's type, or undefined when absent. */
+ const held = (deployed: Deployed, name: string): string | undefined => {
+ const binding = deployed.bindings.get(name);
+ if (!binding) return undefined;
+ if (binding.type === "secret_text") return "secret";
+ if (binding.type === "plain_text") return "text";
+ return binding.type;
};
- const idSecrets = await listSecrets(idWrangler, idRecord.worker);
- const trackSecrets = await listSecrets(trackWrangler, trackRecord.worker);
+ const textOf = (deployed: Deployed, name: string) => deployed.bindings.get(name)?.text;
+ for (const [deployed, worker, names] of [
+ [idDeployed, idRecord.worker, ["BETTER_AUTH_URL", PAIRWISE]],
+ [trackDeployed, trackRecord.worker, [...TRACK_OIDC, "OIDC_PROVIDER_NAME", "BETTER_AUTH_URL"]],
+ ] as const) {
+ for (const name of names) {
+ const how = held(deployed, name);
+ if (how !== undefined && how !== "secret" && how !== "text") {
+ throw new CliError(
+ "requirement",
+ "name-in-use",
+ `${worker} has a ${how} binding named ${name}, where its guide has a setting. This tool replaces nothing; rename or remove that binding, then run again. Nothing was changed.`,
+ );
+ }
+ }
+ }
- // While BETTER_AUTH_URL and OIDC_PAIRWISE_SECRET are both set, the provider answers with its
- // issuer. Either may be a text variable, which the list of secrets does not show.
- const issuerBefore = await discoveredIssuer(sys, idAddress);
+ // The issuer. ID's BETTER_AUTH_URL names it; while that and OIDC_PAIRWISE_SECRET are both set,
+ // the provider also answers with it. A text variable shows its value; a secret does not.
+ const idUrlSet = held(idDeployed, "BETTER_AUTH_URL") !== undefined;
+ const pairwiseSet = held(idDeployed, PAIRWISE) !== undefined;
+ let issuerBefore: string | null = null;
+ if (idUrlSet && pairwiseSet) {
+ issuerBefore = await discoveredIssuer(sys, idAddress);
+ if (issuerBefore === null) {
+ throw new CliError(
+ "requirement",
+ "provider-unreachable",
+ `ID's BETTER_AUTH_URL and ${PAIRWISE} are both set, but ${idAddress}/.well-known/openid-configuration did not answer, so ID's issuer could not be seen. If ID answers at another address, run again with --id-url. Nothing was changed.`,
+ );
+ }
+ } else {
+ const text = textOf(idDeployed, "BETTER_AUTH_URL");
+ if (text !== undefined) {
+ try {
+ issuerBefore = new URL(text).origin;
+ } catch {
+ throw new CliError(
+ "requirement",
+ "issuer-unreadable",
+ `ID's BETTER_AUTH_URL is a text variable that is not an address, so its issuer cannot be told. Nothing was changed.`,
+ );
+ }
+ }
+ }
let adoptedIssuer = false;
if (issuerBefore !== null && issuerBefore !== idAddress) {
if (idGiven) {
@@ -366,13 +601,40 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
idAddress = originOf(issuerBefore, "ID's issuer");
adoptedIssuer = true;
}
- const idUrlSet = issuerBefore !== null || idSecrets.has("BETTER_AUTH_URL");
- const pairwiseSet = issuerBefore !== null || idSecrets.has(PAIRWISE);
+ const trackUrlText = textOf(trackDeployed, "BETTER_AUTH_URL");
+ if (trackUrlText !== undefined && originOrNull(trackUrlText) !== trackAddress) {
+ throw new CliError(
+ "requirement",
+ "track-address-differs",
+ `Track's BETTER_AUTH_URL is ${trackUrlText}, not ${trackAddress}. Track builds its sign-in addresses on it, so it has to be the address registered with ID: run again with --track-url set to it. Nothing was changed.`,
+ );
+ }
+ // ID's database, by name in the account, and the one the record names.
+ const idDatabaseId = await databaseId(
+ (pins, args) => wranglerAt(pins)(args),
+ idPins,
+ idRecord.database,
+ hide,
+ );
+ if (idDatabaseId === null) {
+ throw new CliError(
+ "requirement",
+ "database-missing",
+ `ID's D1 database ${idRecord.database} is not in ${accountLabel}, so Track cannot be registered with ID. Nothing was changed.`,
+ );
+ }
+ if (idRecord.databaseId && idRecord.databaseId !== idDatabaseId) {
+ throw new CliError(
+ "requirement",
+ "database-differs",
+ `ID's D1 database ${idRecord.database} is ${idDatabaseId} now, not ${idRecord.databaseId} as recorded: it was made again. Look at it before anything is registered in it. Nothing was changed.`,
+ );
+ }
const idNames = {
worker: idRecord.worker,
database: idRecord.database,
- databaseId: idRecord.databaseId,
+ databaseId: idDatabaseId,
bucket: null,
queue: idRecord.queue ?? `${idRecord.worker}${PRODUCTS.id.queue?.suffix ?? ""}`,
};
@@ -384,42 +646,28 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
`Could not fetch ID ${idRecord.release} into the cache, where its apps:add runs.`,
);
}
- const redirectUri = `${trackAddress}/api/auth/callback/oidc`;
- const logoutUri = `${trackAddress}/api/auth/backchannel-logout/oidc`;
+ const redirectUri = callbackUri(trackAddress);
+ const logoutUri = backchannelLogoutUri(trackAddress);
- // One fixed query on ID's own database: the first-party apps registered with Track's redirect URI.
- // The address in it is an origin checked above, so it holds no quote. json_quote matches the
- // whole URI as apps:add stores it, in a JSON list, so a longer URI on the same host does not count.
+ // One fixed query on ID's own database: the first-party apps registered as Track with Track's
+ // redirect URI. The address in it is an origin checked above, and quoted besides.
const lookup = await idWrangler(
- [
- "d1",
- "execute",
- "DB",
- "--remote",
- "--json",
- "--command",
- `SELECT client_id FROM oauth_client WHERE reference_id IS NULL AND instr(redirect_uris, json_quote('${redirectUri}'))`,
- ],
+ ["d1", "execute", "DB", "--remote", "--json", "--command", trackRegistrationSql(redirectUri)],
checkout,
);
if (lookup.status !== 0) {
throw new CliError(
"requirement",
"lookup-failed",
- `Could not read the apps registered with ID ${idRecord.worker}: ${hide(lastLine(lookup.stderr))}`,
+ `Could not read the apps registered with ID ${idRecord.worker}: ${hide(lastLine(lookup.stderr))}. Nothing was changed.`,
);
}
- let registered: string[];
- try {
- const answer = json<{ results?: { client_id?: unknown }[] }[]>(lookup.stdout);
- const rows = answer[0]?.results;
- if (!Array.isArray(rows)) throw new Error("no results");
- registered = rows.map(({ client_id }) => String(client_id));
- } catch {
+ const registered = readClientIds(lookup.stdout);
+ if (registered === null) {
throw new CliError(
"requirement",
"lookup-failed",
- `Could not read the apps registered with ID ${idRecord.worker}: Wrangler's answer could not be read.`,
+ `Could not read the apps registered with ID ${idRecord.worker}: Wrangler's answer could not be read. Nothing was changed.`,
);
}
@@ -428,12 +676,16 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
trackWorker: trackRecord.worker,
});
const previous = connections[0];
- const buttonsBefore = await providerButtons(sys, trackAddress);
- // Track shows the button only once all three are set, text variables included.
- const trackShowsProvider = (buttonsBefore?.length ?? 0) > 0;
- const trackHas = (name: string) =>
- trackSecrets.has(name) ||
- (trackShowsProvider && (TRACK_OIDC as readonly string[]).includes(name));
+ const trackHas = (name: string) => held(trackDeployed, name) !== undefined;
+ const deleteOnTrack = (name: string) =>
+ held(trackDeployed, name) === "text"
+ ? `remove ${name} from the vars in Track's configuration and deploy it`
+ : `npx wrangler@${trackPins.wrangler} secret delete ${name} --name ${trackRecord.worker}`;
+ /** The steps that start the connection again from nothing, ending in a run that works. */
+ const startAgain = (clientId: string, onTrack: readonly string[]) =>
+ `remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = ${sqlString(clientId)}"${onTrack.length ? `; remove ${onTrack.join(", ")} from Track: ${onTrack.map(deleteOnTrack).join("; ")}` : ""}; then run \`gateweave connect id track\` again, which registers Track anew.`;
+ const recovery = (clientId: string, onTrack: readonly string[]) =>
+ `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track (npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker}, which asks for the value) and run \`gateweave connect id track\` again. If not, ${startAgain(clientId, onTrack)}`;
if (registered.length > 1) {
throw new CliError(
@@ -443,23 +695,42 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
);
}
const existingClient = registered[0] ?? null;
- const recovery = (clientId: string) =>
- `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track: npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker} (it asks for the value). If not, remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = '${clientId}'", then run \`gateweave connect id track\` again.`;
+ const trackHeld = TRACK_OIDC.filter(trackHas);
if (existingClient && !trackHas("OIDC_CLIENT_SECRET")) {
throw new CliError(
"requirement",
"registered-without-secret",
- `Track ${trackRecord.worker} is already registered with ID ${idRecord.worker} (client id ${existingClient}), but Track's OIDC_CLIENT_SECRET is not set. This tool never registers Track a second time. ${recovery(existingClient)} Nothing was changed.`,
+ `Track ${trackRecord.worker} is already registered with ID ${idRecord.worker} (client id ${existingClient}), but Track's OIDC_CLIENT_SECRET is not set. This tool never registers Track a second time. ${recovery(existingClient, trackHeld)} Nothing was changed.`,
);
}
+ if (existingClient) {
+ // What Track holds must be this registration: the record says which client it was given, and
+ // a text variable shows its value. A secret cannot be read, so a record that disagrees stops.
+ const idText = textOf(trackDeployed, "OIDC_CLIENT_ID");
+ const issuerText = textOf(trackDeployed, "OIDC_ISSUER");
+ const differs =
+ previous?.clientId && previous.clientId !== existingClient
+ ? `this tool gave Track the client id ${previous.clientId}, as its record says`
+ : idText !== undefined && idText !== existingClient
+ ? `Track's OIDC_CLIENT_ID is ${idText}`
+ : issuerText !== undefined && originOrNull(issuerText) !== idAddress
+ ? `Track's OIDC_ISSUER is ${issuerText}, not ${idAddress}`
+ : null;
+ if (differs) {
+ throw new CliError(
+ "requirement",
+ "client-differs",
+ `ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but ${differs}. Which client Track signs in with cannot be told, so nothing is changed. To start again, ${startAgain(existingClient, trackHeld)}`,
+ );
+ }
+ }
const register = existingClient === null;
if (register) {
- const held = TRACK_OIDC.filter(trackHas);
- if (held.length > 0) {
+ if (trackHeld.length > 0) {
throw new CliError(
"requirement",
"track-has-provider",
- `Track ${trackRecord.worker} already has ${held.join(", ")} set, but ID ${idRecord.worker} has no app registered for ${redirectUri}: Track signs in through another provider, or its registration was removed. This tool replaces no secret. To connect it to ID instead, delete those first (npx wrangler@${trackPins.wrangler} secret delete --name ${trackRecord.worker}), then run it again. Nothing was changed.`,
+ `Track ${trackRecord.worker} already has ${trackHeld.join(", ")} set, but ID ${idRecord.worker} has no app registered as Track for ${redirectUri}: Track signs in through another provider, or its registration was removed. This tool replaces no setting. To connect it to ID instead, remove those first (${trackHeld.map(deleteOnTrack).join("; ")}), then run it again. Nothing was changed.`,
);
}
if (!stripsTypes(sys.nodeVersion)) {
@@ -477,30 +748,46 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
);
}
}
- if (previous?.clientId && existingClient && previous.clientId !== existingClient) {
- say(
- `Note: ID's registration for Track has the client id ${existingClient}, not ${previous.clientId} as recorded; it is left as it is.`,
+
+ // The name on Track's button, which the checks look for exactly: the one this run sets, the text
+ // variable's, or the one this tool set before. A secret set by someone else cannot be read.
+ const nameHeld = held(trackDeployed, "OIDC_PROVIDER_NAME");
+ const providerName =
+ nameHeld === undefined
+ ? ID_PROVIDER_NAME
+ : nameHeld === "text"
+ ? (textOf(trackDeployed, "OIDC_PROVIDER_NAME") ?? "")
+ : (previous?.providerName ?? null);
+ if (providerName === null || providerName === "") {
+ throw new CliError(
+ "requirement",
+ "provider-name-unknown",
+ `Track's OIDC_PROVIDER_NAME is set as a secret this tool did not set, and a secret cannot be read back, so the check that Track's sign-in page shows ID's button could not be made. Remove it (${deleteOnTrack("OIDC_PROVIDER_NAME")}) to have this tool set it to "${ID_PROVIDER_NAME}", or make it a text variable in Track's configuration; then run again. Nothing was changed.`,
);
}
- const trackMcpOn = trackSecrets.has("BETTER_AUTH_URL")
- ? true
- : (await mcpIsOn(sys, trackAddress)) === true;
- const clientIdKnown = existingClient;
interface Planned {
product: ProductKey;
worker: string;
name: string;
value: string;
- set: boolean;
+ /** How it is held already, or undefined when this run sets it. */
+ held: string | undefined;
}
+ const generate = !pairwiseSet;
+ // The keep path counts only when this run makes the value. Decided first, so a run that makes
+ // nothing never refuses a path, such as the file an earlier run wrote.
+ const keepAt =
+ generate && options.keepSecretAt !== undefined
+ ? await keepPath(sys, options.keepSecretAt)
+ : null;
const idPlan: Planned[] = [
{
product: "id",
worker: idRecord.worker,
name: "BETTER_AUTH_URL",
value: idAddress,
- set: idUrlSet,
+ held: held(idDeployed, "BETTER_AUTH_URL"),
},
{
product: "id",
@@ -508,8 +795,8 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
name: PAIRWISE,
value: keepAt
? `generated here, kept at ${keepAt}, never shown`
- : "generated here and shown once on this terminal, for you to keep",
- set: pairwiseSet,
+ : "generated here and shown once on this terminal, before it is set, for you to keep",
+ held: held(idDeployed, PAIRWISE),
},
];
const trackPlan: Planned[] = [
@@ -518,44 +805,44 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
worker: trackRecord.worker,
name: "OIDC_CLIENT_SECRET",
value: "from the registration, never shown",
- set: !register,
+ held: held(trackDeployed, "OIDC_CLIENT_SECRET"),
},
{
product: "track",
worker: trackRecord.worker,
name: "OIDC_CLIENT_ID",
- value: clientIdKnown ?? "from the registration",
- set: !register && trackHas("OIDC_CLIENT_ID"),
+ value: existingClient ?? "from the registration",
+ held: held(trackDeployed, "OIDC_CLIENT_ID"),
},
{
product: "track",
worker: trackRecord.worker,
name: "OIDC_ISSUER",
value: idAddress,
- set: !register && trackHas("OIDC_ISSUER"),
+ held: held(trackDeployed, "OIDC_ISSUER"),
},
{
product: "track",
worker: trackRecord.worker,
name: "OIDC_PROVIDER_NAME",
value: ID_PROVIDER_NAME,
- set: trackSecrets.has("OIDC_PROVIDER_NAME") || (trackShowsProvider && !register),
+ held: nameHeld,
},
{
product: "track",
worker: trackRecord.worker,
name: "BETTER_AUTH_URL",
value: `${trackAddress} (this also turns MCP on)`,
- set: trackMcpOn,
+ held: held(trackDeployed, "BETTER_AUTH_URL"),
},
];
const plan = [...idPlan, ...trackPlan];
- const toChange = plan.filter(({ set }) => !set);
- const changing = register || toChange.length > 0;
+ const changing = register || plan.some((item) => item.held === undefined);
// The value a person must keep goes to a file outside the working directory, or to a terminal
- // they are looking at: never into --json, and never into a log that stderr may be.
- if (!pairwiseSet && !keepAt && (options.json || !sys.interactive)) {
+ // they are looking at: never into --json, and never into a log that stderr may be. When it is
+ // set already, nothing is made, and --json needs no file.
+ if (generate && !keepAt && (options.json || !sys.interactive)) {
throw new CliError(
"usage",
"keep-path-needed",
@@ -569,22 +856,34 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
`The issuer, ID's BETTER_AUTH_URL (${idAddress}), can never change once any app has signed anyone in: apps compare it, and passkeys are bound to it for good. Choose the address people will always use.`,
);
}
- const onWorkersDev = [idAddress, trackAddress].filter((address) =>
- new URL(address).hostname.endsWith(".workers.dev"),
- );
- if (onWorkersDev.length > 0) {
- if (new URL(idAddress).hostname.endsWith(".workers.dev")) {
- warnings.push(
- `The issuer ${idAddress} is a workers.dev address, and it can never change once any app has signed anyone in. To give ID a domain of its own later, every app would have to be connected again. If you mean to have one, add a Custom Domain to ${idRecord.worker} first and run this with --id-url.`,
- );
- }
+ const onWorkersDev = (address: string) => new URL(address).hostname.endsWith(".workers.dev");
+ if (onWorkersDev(idAddress)) {
warnings.push(
- "Two Workers on workers.dev cannot reach each other unless each has global_fetch_strictly_public in its compatibility_flags: Track's sign-in through ID then fails with Cloudflare's error 1042, and ID's back-channel logout cannot reach Track, so signing out of ID does not end Track's sessions. A Custom Domain on each Worker is the setup that works: https://developers.cloudflare.com/workers/configuration/routing/custom-domains/",
+ `The issuer ${idAddress} is a workers.dev address, and it can never change once any app has signed anyone in. To give ID a domain of its own later, every app would have to be connected again. If you mean to have one, add a Custom Domain to ${idRecord.worker} first and run this with --id-url.`,
+ );
+ }
+ // A Worker reaches another on workers.dev only with this flag, and it is the calling Worker's
+ // that counts: Track calls ID to sign people in, and ID calls Track to sign them out.
+ const customDomains =
+ "https://developers.cloudflare.com/workers/configuration/routing/custom-domains/";
+ if (onWorkersDev(idAddress) && !trackDeployed.flags.includes(STRICTLY_PUBLIC)) {
+ warnings.push(
+ `Track (${trackRecord.worker}) does not have ${STRICTLY_PUBLIC} in its compatibility_flags, so it cannot reach ID on workers.dev: sign-in through ID fails with Cloudflare's error 1042. A Custom Domain on ID is the setup that works: ${customDomains}`,
+ );
+ }
+ if (onWorkersDev(trackAddress) && !idDeployed.flags.includes(STRICTLY_PUBLIC)) {
+ warnings.push(
+ `ID (${idRecord.worker}) does not have ${STRICTLY_PUBLIC} in its compatibility_flags, so its back-channel logout cannot reach Track on workers.dev: signing out of ID does not end Track's sessions. Sign-in works, as there Track calls ID. A Custom Domain on Track is the setup that works: ${customDomains}`,
);
}
// The plan.
- const state = (item: Planned) => (item.set ? "already set; left as it is" : "set now");
+ const state = (item: Planned) =>
+ item.held === undefined
+ ? "set now"
+ : `already set${item.held === "text" ? " as a text variable" : ""}; left as it is`;
+ const line = (item: Planned) =>
+ ` ${item.name.padEnd(22)} ${item.held === undefined ? `${item.value} ` : ""}(${state(item)})`;
say(`Connect Track to ID in ${accountLabel}, so Track signs people in through ID:`);
say(
` ID ${idRecord.worker} at ${idAddress} (ID ${idRecord.release}${adoptedIssuer ? "; the address is ID's issuer" : ""})`,
@@ -594,57 +893,64 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
);
say();
say(` On ID (${idRecord.worker}):`);
- for (const item of idPlan)
- say(` ${item.name.padEnd(22)} ${item.set ? "" : `${item.value} `}(${state(item)})`);
+ for (const item of idPlan) say(line(item));
say();
if (register) {
- say(" Register Track with ID, with ID's own apps:add, on ID's database:");
- say(` app ${APP.id} ("${APP.name}")`);
+ say(
+ ` Register Track with ID, with ID's own apps:add, in ID's D1 database ${idRecord.database} (${idDatabaseId}):`,
+ );
+ say(` app ${TRACK_APP} ("${APP_NAME}")`);
say(` redirect URI ${redirectUri}`);
say(` back-channel logout ${logoutUri}`);
} else {
say(
- ` Track is already registered with ID (client id ${existingClient}); nothing is registered.`,
+ ` Track is already registered with ID (client id ${existingClient}, in ID's D1 database ${idRecord.database}); nothing is registered.`,
);
}
say();
say(` On Track (${trackRecord.worker}):`);
- for (const item of trackPlan)
- say(` ${item.name.padEnd(22)} ${item.set ? "" : `${item.value} `}(${state(item)})`);
+ for (const item of trackPlan) say(line(item));
say();
for (const warning of warnings) say(` Warning: ${warning}`);
if (warnings.length > 0) say();
- if (keepAt && pairwiseSet)
- say(` ${PAIRWISE} is already set, so nothing is written to ${keepAt}.`);
+ if (!generate && options.keepSecretAt !== undefined)
+ say(` ${PAIRWISE} is already set, so --keep-secret-at is not used and nothing is written.`);
// "checked" is earned again by this run's own checks.
let steps: ConnectionStep[] = (previous?.steps ?? []).filter((step) => step !== "checked");
let clientId = existingClient;
- const providerName = trackPlan.find(({ name }) => name === "OIDC_PROVIDER_NAME")?.set
- ? (previous?.providerName ?? null)
- : ID_PROVIDER_NAME;
- const save = () =>
- saveConnection(sys, {
- kind: "id-track",
- accountId: account.id,
- idWorker: idRecord.worker,
- trackWorker: trackRecord.worker,
- issuer: idAddress,
- trackAddress,
- providerName,
- clientId,
- steps,
- updatedAt: new Date(sys.now()).toISOString(),
- });
+ const save = async () => {
+ try {
+ await saveConnection(sys, {
+ kind: "id-track",
+ accountId: account.id,
+ idWorker: idRecord.worker,
+ trackWorker: trackRecord.worker,
+ issuer: idAddress,
+ trackAddress,
+ providerName,
+ clientId,
+ steps,
+ updatedAt: new Date(sys.now()).toISOString(),
+ });
+ } catch (error) {
+ if (error instanceof CliError) throw error;
+ throw new CliError(
+ "requirement",
+ "record-unwritable",
+ `The record of connections could not be written (${(error as NodeJS.ErrnoException).code ?? "error"}). What was set stays; run the command again once the record can be written.`,
+ );
+ }
+ };
const addStep = (step: ConnectionStep) => {
if (!steps.includes(step)) steps = [...steps, step];
};
- const settings: ConnectSetting[] = plan.map(({ product, worker, name, set }) => ({
+ const settings: ConnectSetting[] = plan.map(({ product, worker, name, held: was }) => ({
product,
worker,
name,
- setNow: !set,
+ setNow: was === undefined,
shown: false,
}));
let generatedNow = false;
@@ -666,17 +972,23 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
detail: hide(lastLine(result.stderr) || lastLine(result.stdout) || `exit ${result.status}`),
};
};
+ /** A failed put can come after Cloudflare took the value; then the value is set. */
+ const listedNow = (wrangler: ReturnType, worker: string, name: string) =>
+ listSecrets(wrangler, worker).then(
+ (names) => names.has(name),
+ () => false,
+ );
const putOrStop = async (
item: Planned,
wrangler: ReturnType,
value: string,
) => {
const { done, detail } = await put(wrangler, item.worker, item.name, value);
- if (!done) {
+ if (!done && !(await listedNow(wrangler, item.worker, item.name))) {
throw new CliError(
"deploy-failed",
"secret-put-failed",
- `Could not set ${item.name} on ${item.worker}: ${detail}. Run the command again to finish; what is set stays.`,
+ `Could not set ${item.name} on ${item.worker}: ${detail}. Run the command again to finish; what is set stays, and nothing is registered twice.`,
);
}
say(` set ${item.name} on ${item.worker}`);
@@ -689,35 +1001,32 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
// ID's provider first: nothing can be registered against an issuer that does not answer.
const idUrl = idPlan[0];
- if (idUrl && !idUrl.set) await putOrStop(idUrl, idWrangler, idAddress);
- if (!pairwiseSet) {
+ if (idUrl && idUrl.held === undefined) await putOrStop(idUrl, idWrangler, idAddress);
+ if (generate) {
const value = Buffer.from((sys.random ?? randomBytes)(48)).toString("base64");
guard.remember(value);
generatedNow = true;
+ // Kept before it is set, so a value that reached ID is never one nobody kept.
if (keepAt) {
- // Written before it is set, so a value that reached ID is never one nobody kept.
- try {
- // New only (wx), and readable by its owner alone where the system has file modes.
- await (sys.writeFile ?? writeFile)(keepAt, `${value}\n`, { flag: "wx", mode: 0o600 });
- if (sys.platform !== "win32") await chmod(keepAt, 0o600);
- } catch (error) {
- throw new CliError(
- "requirement",
- "keep-path-unwritable",
- `Could not write ${keepAt} (${(error as NodeJS.ErrnoException).code ?? "error"}). Nothing was set on ID for ${PAIRWISE}.`,
- );
- }
+ await writeKept(sys, keepAt, value);
+ } else {
+ shownOnTerminal = true;
+ say();
+ say(
+ ` Keep this value now, in your password manager. It is ${PAIRWISE}, shown this once and never again: Cloudflare cannot show it back, and losing or changing it gives everyone a new id in every app. It is set on ID next.`,
+ );
+ say();
+ say(` ${value}`);
+ say();
}
let { done, detail } = await put(idWrangler, idRecord.worker, PAIRWISE, value);
- // A failure can come after Cloudflare took the value. Then it is the one to keep.
- if (!done) done = (await listSecrets(idWrangler, idRecord.worker)).has(PAIRWISE);
+ if (!done) done = await listedNow(idWrangler, idRecord.worker, PAIRWISE);
if (!done) {
if (keepAt) await rm(keepAt, { force: true });
- detail = detail || "Wrangler failed";
throw new CliError(
"deploy-failed",
"secret-put-failed",
- `Could not set ${PAIRWISE} on ${idRecord.worker}: ${detail}. ${keepAt ? `${keepAt} was removed again, as it held a value that was never set. ` : ""}Run the command again.`,
+ `Could not set ${PAIRWISE} on ${idRecord.worker}: ${detail}. ${keepAt ? `${keepAt} was removed again, as it held a value that was never set. ` : "The value shown above was never set: do not keep it. "}Run the command again; it makes a new one.`,
);
}
say(` set ${PAIRWISE} on ${idRecord.worker}`);
@@ -727,14 +1036,7 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
` Keep ${keepAt}: it holds ${PAIRWISE}, the one value of this connection you must keep. Move it into your password manager. Losing or changing it gives everyone a new id in every app, and Cloudflare cannot show it again.`,
);
} else {
- shownOnTerminal = true;
- say();
- say(
- ` Keep this value now, in your password manager. It is ${PAIRWISE}, shown this once and never again: Cloudflare cannot show it back, and losing or changing it gives everyone a new id in every app.`,
- );
- say();
- say(` ${value}`);
- say();
+ say(` The value shown above is set on ID now; it is the one to keep.`);
}
}
@@ -761,6 +1063,7 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
issuer = discovered;
let clientSecret: string | null = null;
+ let recordFailure: CliError | null = null;
if (register) {
const install = await sys.run(
sys.execPath,
@@ -769,7 +1072,7 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
cwd: checkout,
env: sys.env,
stream: true,
- streamFilter: guard.stream(),
+ streamFilter: guard.stream(hiddenNames()),
},
);
if (install.status !== 0) {
@@ -780,17 +1083,17 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
);
}
say("Registering Track with ID (ID's apps:add)");
- // Its output is kept in memory only, never streamed: it holds the client secret. It is the
- // package's own script (`apps:add` is `node scripts/add-app.ts`), started with this Node and
- // no shell, so no value here is parsed as a command.
+ // Its output is kept in memory only, never streamed or repeated: it holds the client secret.
+ // It is the package's own script (`apps:add` is `node scripts/add-app.ts`), started with
+ // this Node and no shell, so no value here is parsed as a command.
const added = await sys.run(
sys.execPath,
[
join("scripts", "add-app.ts"),
"--app",
- APP.id,
+ TRACK_APP,
"--name",
- APP.name,
+ APP_NAME,
"--redirect-uri",
redirectUri,
"--backchannel-logout-uri",
@@ -798,37 +1101,38 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
],
{ cwd: join(checkout, "apps", "web"), env },
);
- const captured = `${added.stdout}\n${added.stderr}`;
- for (const match of plain(captured).matchAll(
+ // Whatever looks like a secret is hidden from everything shown after, read or not.
+ for (const match of plain(`${added.stdout}\n${added.stderr}`).matchAll(
/client secret:\s*(\S+)|(gwid_cs_[A-Za-z0-9_-]+)/gi,
)) {
const found = match[1] ?? match[2];
if (found) guard.remember(found);
}
- const lines = plain(added.stdout)
- .split(/\r?\n/)
- .map((line) => line.trim());
- const ids = lines.flatMap((line) => CLIENT_ID_LINE.exec(line)?.[1] ?? []);
- const secrets = lines.flatMap((line) => CLIENT_SECRET_LINE.exec(line)?.[1] ?? []);
- const holdsSecret = /client secret|gwid_cs_/i.test(captured);
- if (added.status !== 0 && !holdsSecret) {
+ const where = `To see why, check that Wrangler reaches ID's database: in ${join(checkout, "apps", "web")}, run npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "SELECT 1".`;
+ if (added.status !== 0) {
throw new CliError(
"deploy-failed",
"register-failed",
- `ID's apps:add stopped (exit ${added.status}): ${hide(lastLine(added.stderr)) || "no reason given"}. Run the command again; it first looks whether Track was registered.`,
+ `ID's apps:add stopped (exit ${added.status}), and Track was given nothing. What it printed is not shown, as it may hold the client secret. ${where} Then run this again: it first looks whether Track was registered.`,
);
}
- if (added.status !== 0 || ids.length !== 1 || secrets.length !== 1) {
+ const output = APPS_ADD_OUTPUT.exec(plain(added.stdout).replace(/\r\n/g, "\n"));
+ const [, givenId, givenSecret] = output ?? [];
+ if (!givenId || !givenSecret || givenId.startsWith("gwid_")) {
throw new CliError(
"deploy-failed",
"register-output-unreadable",
- `ID's apps:add ${added.status === 0 ? "finished" : `stopped (exit ${added.status})`}, but its output was not the two lines this tool reads (\`client id:\` and \`client secret:\`). None of it is shown, as it may hold the secret, and Track was given nothing. If Track was registered, the next run says so and how to recover.`,
+ `ID's apps:add finished, but what it printed was not the three lines this tool reads, so Track was given nothing. None of it is shown, as it may hold the client secret. If Track was registered, the next run says so and how to recover.`,
);
}
- clientId = ids[0] ?? null;
- clientSecret = secrets[0] ?? null;
+ clientId = givenId;
+ clientSecret = givenSecret;
+ // On record before Track is given anything: a rerun then knows the client, never its secret.
addStep("registered");
- await save();
+ recordFailure = await save().then(
+ () => null,
+ (error: CliError) => error,
+ );
say(
` registered Track with ID: client id ${clientId}; its secret goes to Track and is never shown`,
);
@@ -842,16 +1146,22 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
BETTER_AUTH_URL: trackAddress,
};
for (const item of trackPlan) {
- if (item.set) continue;
+ if (item.held !== undefined) continue;
if (item.name === "OIDC_CLIENT_SECRET") {
if (clientSecret === null) throw new Error("no client secret");
- // First, as it lives only in this run's memory until Track has it.
- const { done, detail } = await put(trackWrangler, item.worker, item.name, clientSecret);
+ // First, and tried again: it lives only in this run's memory until Track has it.
+ let done = false;
+ let detail = "";
+ for (let attempt = 0; attempt < 3 && !done; attempt++) {
+ if (attempt > 0) await sys.sleep(5_000);
+ ({ done, detail } = await put(trackWrangler, item.worker, item.name, clientSecret));
+ if (!done) done = await listedNow(trackWrangler, item.worker, item.name);
+ }
if (!done) {
throw new CliError(
"deploy-failed",
"client-secret-not-set",
- `Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker}: ${detail}. ${recovery(clientId)}`,
+ `Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker}: ${detail}. ${recovery(clientId, [])}`,
);
}
say(` set ${item.name} on ${item.worker}`);
@@ -863,6 +1173,7 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
}
addStep("connected");
await save();
+ if (recordFailure) say(` The record could be written only now: ${recordFailure.message}`);
}
if (clientId === null) throw new Error("no client id");
if (!changing) {
@@ -870,7 +1181,8 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
addStep("connected");
}
- // The checks: ID's provider from outside, Track's button, and what doctor says of both.
+ // The checks: ID's provider from outside, Track's button by its exact name, and what doctor says
+ // of both, ID's database included.
say(`Checking the connection from outside (up to two minutes while the new settings come up)`);
const checks: CheckResult[] = [];
const finalIssuer = await waitFor(
@@ -885,20 +1197,15 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
detail:
finalIssuer === issuer ? "passed" : finalIssuer ? `answered ${finalIssuer}` : "no answer",
});
- const wantedButton = providerName;
const buttons = await waitFor(
sys,
120_000,
() => providerButtons(sys, trackAddress),
- (found) => (found ? (wantedButton ? found.includes(wantedButton) : found.length > 0) : false),
+ (found) => found?.includes(providerName) === true,
);
- const buttonOk = buttons
- ? wantedButton
- ? buttons.includes(wantedButton)
- : buttons.length > 0
- : false;
+ const buttonOk = buttons?.includes(providerName) === true;
checks.push({
- name: `Track's sign-in page shows "Continue with ${wantedButton ?? "…"}"`,
+ name: `Track's sign-in page shows "Continue with ${providerName}"`,
ok: buttonOk,
detail: buttonOk ? "passed" : buttons ? "the button is not there" : "the page did not answer",
});
@@ -915,21 +1222,34 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
detail: finding.status === "ok" ? "passed" : (finding.fix ?? finding.status),
}),
);
+ // Set is set, as a secret or as a text variable: the variables do not change here.
+ const setOn = async (
+ wrangler: ReturnType,
+ worker: string,
+ deployed: Deployed,
+ ) =>
+ new Set([
+ ...(await listSecrets(wrangler, worker)),
+ ...[...deployed.bindings]
+ .filter(([, { type }]) => type === "plain_text")
+ .map(([name]) => name),
+ ]);
checks.push(
...doctorSays(
"id",
await idProviderFindings(
sys,
- await listSecrets(idWrangler, idRecord.worker),
+ await setOn(idWrangler, idRecord.worker, idDeployed),
idAddress,
connectedNow,
+ await readRegistrations((args, cwd) => idWrangler(args, cwd), checkout, connectedNow),
),
),
...doctorSays(
"track",
await trackSignInFindings(
sys,
- await listSecrets(trackWrangler, trackRecord.worker),
+ await setOn(trackWrangler, trackRecord.worker, trackDeployed),
trackAddress,
connectedNow,
),
@@ -942,7 +1262,7 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
throw new CliError(
"checks-failed",
"checks-failed",
- `Track and ID are connected, but ${failed.map(({ name, detail }) => `${name} (${detail})`).join("; ")}. Run \`gateweave doctor track\` and \`gateweave doctor id\` for more.`,
+ `Track and ID are set up, but ${failed.map(({ name, detail }) => `${name} (${detail})`).join("; ")}. Run \`gateweave doctor track\` and \`gateweave doctor id\` for more.`,
);
}
addStep("checked");
@@ -950,7 +1270,7 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
return {
ok: true,
- account: { id: account.id, name: account.name },
+ account: showName ? { id: account.id, name: account.name } : { id: account.id },
id: { worker: idRecord.worker, address: idAddress, issuer },
track: { worker: trackRecord.worker, address: trackAddress },
clientId,
@@ -963,6 +1283,14 @@ export async function connectIdTrack(sys: System, options: ConnectOptions): Prom
};
}
+function originOrNull(value: string): string | null {
+ try {
+ return new URL(value).origin;
+ } catch {
+ return null;
+ }
+}
+
/** The result in words. It names settings and never holds a secret's value. */
export function describeConnect(result: ConnectResult): string {
const now = result.settings.filter(({ setNow }) => setNow);
diff --git a/packages/cli/src/doctor-track.ts b/packages/cli/src/doctor-track.ts
index 6c6df3b..0819c5c 100644
--- a/packages/cli/src/doctor-track.ts
+++ b/packages/cli/src/doctor-track.ts
@@ -5,6 +5,7 @@ import {
checkIdsFor,
discoveredIssuer,
mcpIsOn,
+ pagePolicyIssuers,
providerButtons,
} from "./checks.ts";
import {
@@ -24,6 +25,7 @@ import {
findConnections,
findRecord,
} from "./record.ts";
+import { callbackUri, readClientIds, trackRegistrationSql } from "./registration.ts";
import { compareTags, type Pins, readPins, releaseTags } from "./release.ts";
import type { RunResult, System } from "./system.ts";
import { nameProduct, type ProductNames } from "./wrangler-config.ts";
@@ -219,6 +221,12 @@ export async function doctorProduct(
queue: record?.queue ?? (product.queue ? `${worker}${product.queue.suffix}` : null),
};
const address = options.url ?? record?.address ?? null;
+ const connections = await findConnections(
+ sys,
+ account.id,
+ product.key === "track" ? { trackWorker: worker } : { idWorker: worker },
+ );
+ let registrations: Registrations = new Map();
const database = await databaseId(wrangler, latestPins, names.database, hide);
if (database === null) {
@@ -246,6 +254,13 @@ export async function doctorProduct(
),
);
findings.push(...(await signUpFindings(sys, read, address, product)));
+ if (product.key === "id" && checkout) {
+ registrations = await readRegistrations(
+ (args, cwd) => wrangler(pins, args, cwd),
+ checkout,
+ connections,
+ );
+ }
}
findings.push(
@@ -255,18 +270,8 @@ export async function doctorProduct(
);
findings.push(
...(product.key === "track"
- ? await trackSignInFindings(
- sys,
- secrets,
- address,
- await findConnections(sys, account.id, { trackWorker: worker }),
- )
- : await idProviderFindings(
- sys,
- secrets,
- address,
- await findConnections(sys, account.id, { idWorker: worker }),
- )),
+ ? await trackSignInFindings(sys, secrets, address, connections)
+ : await idProviderFindings(sys, secrets, address, connections, registrations)),
);
findings.push(...(await outsideFindings(sys, address, product)));
return finish();
@@ -274,9 +279,36 @@ export async function doctorProduct(
const TRACK_OIDC = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const;
+/** What ID's database says of each Track a recorded connection names: its client ids, or null. */
+export type Registrations = Map;
+
+/** Runs the one registration query for each recorded connection, in ID's checkout. */
+export async function readRegistrations(
+ run: (args: string[], cwd: string) => Promise,
+ checkout: string,
+ connections: readonly ConnectionRecord[],
+): Promise {
+ const found: Registrations = new Map();
+ for (const connection of connections) {
+ const sql = trackRegistrationSql(callbackUri(connection.trackAddress));
+ const answer = await run(
+ ["d1", "execute", "DB", "--remote", "--json", "--command", sql],
+ checkout,
+ );
+ found.set(connection.trackWorker, answer.status === 0 ? readClientIds(answer.stdout) : null);
+ }
+ return found;
+}
+
+const worst = (statuses: Status[]): Status =>
+ statuses.includes("fail") ? "fail" : statuses.includes("warn") ? "warn" : "ok";
+
/**
* Whether Track signs people in through an OpenID Connect provider. Said only when Track has one of
* its settings or `gateweave connect id track` connected it, so a Track without one is not told off.
+ * For a recorded connection it looks at the address the connection was made on, and says what it
+ * can see from outside (the button by its exact name, the issuer in the page's policy) and what it
+ * cannot: the client id Track holds is a secret.
*/
export async function trackSignInFindings(
sys: System,
@@ -287,84 +319,112 @@ export async function trackSignInFindings(
const connection = connections.find(({ steps }) => steps.includes("connected"));
const set = TRACK_OIDC.filter((name) => secrets.has(name));
if (set.length === 0 && !connection) return [];
+ const at = connection?.trackAddress ?? address;
const fix = `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.track)}`;
+ const finding = (status: Status, message: string, fixWith: string | null = fix): Finding[] => [
+ { id: "sign-in-provider", status, message, fix: status === "ok" ? null : fixWith },
+ ];
const signIn = connection
- ? `Sign-in through ID ${connection.idWorker} (${connection.issuer}, client id ${connection.clientId})`
+ ? `Sign-in through ID ${connection.idWorker} (${connection.issuer})`
: "Sign-in through an OpenID Connect provider";
// A setting may be a text variable, which the list of secrets does not show; the page does.
- const buttons = address ? await providerButtons(sys, address) : null;
- const wanted = connection?.providerName ?? null;
- const shown = buttons !== null && (wanted ? buttons.includes(wanted) : buttons.length > 0);
+ const buttons = at ? await providerButtons(sys, at) : null;
+ const wanted = connection ? connection.providerName : null;
+ const shown =
+ buttons !== null &&
+ (connection ? wanted !== null && buttons.includes(wanted) : buttons.length > 0);
const missing = TRACK_OIDC.filter((name) => !secrets.has(name));
if (missing.length > 0 && !shown) {
- return [
- {
- id: "sign-in-provider",
- status: "fail",
- message: `${signIn} is set up only in part: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not set, so the sign-in page has no button for it.`,
- fix,
- },
- ];
+ return finding(
+ "fail",
+ `${signIn} is set up only in part: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not set, so the sign-in page has no button for it.`,
+ );
}
- if (address && buttons === null) {
- return [
- {
- id: "sign-in-provider",
- status: "warn",
- message: `${signIn} is set up, but the sign-in page did not answer, so its button was not seen.`,
- fix: `Open ${address}/login; if the Worker was just changed, wait a minute and run again.`,
- },
- ];
+ if (!at) {
+ return connection
+ ? finding(
+ "warn",
+ `${signIn}: its settings are set, but the address is unknown, so nothing was seen from outside.`,
+ "Run again with --url https://",
+ )
+ : finding(
+ "ok",
+ `${signIn} is set up (OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are set).`,
+ );
}
- if (address && !shown) {
- return [
- {
- id: "sign-in-provider",
- status: "fail",
- message: `${signIn} is set up, but the sign-in page shows no "Continue with ${wanted ?? "…"}" button.`,
- fix,
- },
- ];
+ if (buttons === null) {
+ return finding(
+ "warn",
+ `${signIn}: its settings are set, but the sign-in page did not answer, so its button was not seen.`,
+ `Open ${at}/login; if the Worker was just changed, wait a minute and run again.`,
+ );
}
- return [
- {
- id: "sign-in-provider",
- status: "ok",
- message: address
- ? `${signIn} is set up, and the sign-in page shows its button.`
- : `${signIn} is set up (OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are set).`,
- fix: null,
- },
- ];
+ if (connection && wanted === null) {
+ return finding(
+ "warn",
+ `${signIn}: which button on the sign-in page is ID's cannot be told, as the provider's name is not on record.`,
+ "Run gateweave connect id track, which says how to give Track a name it can check.",
+ );
+ }
+ if (!shown) {
+ return finding(
+ "fail",
+ `${signIn}: the settings are set, but the sign-in page shows no "Continue with ${wanted ?? "…"}" button.`,
+ );
+ }
+ if (!connection) {
+ return finding("ok", `${signIn} is set up, and the sign-in page shows its button.`);
+ }
+ // Track names the issuer in its page's policy, the one place OIDC_ISSUER shows from outside.
+ const issuers = await pagePolicyIssuers(sys, at);
+ const unread = `The client id Track holds is a secret, which cannot be read back; this tool gave it ${connection.clientId}, and \`gateweave doctor id\` checks that ID still has that one.`;
+ if (issuers === null) {
+ return finding(
+ "warn",
+ `${signIn}: the sign-in page shows "Continue with ${wanted}", but which issuer Track names could not be seen, as the page sent no policy naming one. ${unread}`,
+ `Open ${at}/login; Track names its issuer in the page's Content-Security-Policy from v0.29.5.`,
+ );
+ }
+ if (!issuers.includes(connection.issuer)) {
+ return finding(
+ "fail",
+ `${signIn}: the sign-in page shows "Continue with ${wanted}", but Track names ${issuers.length ? `the issuer ${issuers.join(", ")}` : "no issuer"}, not ${connection.issuer}, so its button does not lead to this ID.`,
+ );
+ }
+ return finding(
+ "ok",
+ `${signIn} is set up: the sign-in page shows "Continue with ${wanted}", and Track names the issuer ${connection.issuer}. ${unread}`,
+ );
}
/**
- * Whether ID's OpenID Connect provider is on, and which Track this tool connected to it. Said only
- * when OIDC_PAIRWISE_SECRET is set or a connection is recorded.
+ * Whether ID's OpenID Connect provider is on, and whether ID still has each Track this tool
+ * connected, as its database shows. Said only when OIDC_PAIRWISE_SECRET is set or a connection is
+ * recorded. It asks the provider at the address a connection was made with: the issuer.
*/
export async function idProviderFindings(
sys: System,
secrets: Set,
address: string | null,
connections: readonly ConnectionRecord[],
+ registrations: Registrations = new Map(),
): Promise {
const connected = connections.filter(({ steps }) => steps.includes("connected"));
if (!secrets.has("OIDC_PAIRWISE_SECRET") && connected.length === 0) return [];
- const apps =
- connected.length > 0
- ? ` Connected by this tool: ${connected.map(({ trackWorker, clientId }) => `Track ${trackWorker} (client id ${clientId})`).join(", ")}.`
- : "";
- if (!address) {
+ const at = connected[0]?.issuer ?? address;
+ const fix = `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.id)}#turning-on-the-provider`;
+ if (!at) {
return [
{
id: "oidc-provider",
status: "warn",
- message: `Whether the OpenID Connect provider is on could not be told: the address is unknown.${apps}`,
+ message:
+ "Whether the OpenID Connect provider is on could not be told: the address is unknown.",
fix: "Run again with --url https://..workers.dev",
},
];
}
- const issuer = await discoveredIssuer(sys, address);
+ const issuer = await discoveredIssuer(sys, at);
if (issuer === null) {
const missing = ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"].filter(
(name) => !secrets.has(name),
@@ -373,8 +433,8 @@ export async function idProviderFindings(
{
id: "oidc-provider",
status: "fail",
- message: `The OpenID Connect provider is off: ${address}/.well-known/openid-configuration does not answer${missing.length ? `, and ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} not set` : ""}. No app can sign anyone in.${apps}`,
- fix: `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.id)}#turning-on-the-provider`,
+ message: `The OpenID Connect provider is off: ${at}/.well-known/openid-configuration does not answer${missing.length ? `, and ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} not set` : ""}. No app can sign anyone in.`,
+ fix,
},
];
}
@@ -389,12 +449,41 @@ export async function idProviderFindings(
},
];
}
+ // What ID's own database says of each Track: proof, where the record alone is only a claim.
+ const seen = connected.map(({ trackWorker, clientId }): { status: Status; text: string } => {
+ const ids = registrations.get(trackWorker);
+ if (!ids) {
+ return {
+ status: "warn",
+ text: `whether Track ${trackWorker} is still registered could not be read from ID's database`,
+ };
+ }
+ if (ids.length === 0) {
+ return {
+ status: "fail",
+ text: `Track ${trackWorker} is not registered any more (this tool registered it as client id ${clientId})`,
+ };
+ }
+ if (ids.length > 1) {
+ return {
+ status: "fail",
+ text: `Track ${trackWorker} is registered ${ids.length} times (client ids ${ids.join(", ")})`,
+ };
+ }
+ return ids[0] === clientId
+ ? { status: "ok", text: `Track ${trackWorker} is registered, as client id ${clientId}` }
+ : {
+ status: "fail",
+ text: `Track ${trackWorker} is registered as client id ${ids[0]}, not ${clientId}, the one this tool gave Track`,
+ };
+ });
+ const status = worst(seen.map((item) => item.status));
return [
{
id: "oidc-provider",
- status: "ok",
- message: `The OpenID Connect provider is on, with the issuer ${issuer}.${apps}`,
- fix: null,
+ status,
+ message: `The OpenID Connect provider is on, with the issuer ${issuer}.${seen.length ? ` In ID's database: ${seen.map(({ text }) => text).join("; ")}.` : ""}`,
+ fix: status === "ok" ? null : fix,
},
];
}
@@ -428,7 +517,7 @@ function releaseFinding(
};
}
-async function databaseId(
+export async function databaseId(
wrangler: (pins: Pins, args: string[]) => Promise,
pins: Pins,
name: string,
diff --git a/packages/cli/src/lock.ts b/packages/cli/src/lock.ts
new file mode 100644
index 0000000..e655d8c
--- /dev/null
+++ b/packages/cli/src/lock.ts
@@ -0,0 +1,110 @@
+import { link, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
+import { hostname } from "node:os";
+import { join } from "node:path";
+import { CliError } from "./errors.ts";
+import { configDir } from "./paths.ts";
+import type { System } from "./system.ts";
+
+interface Holder {
+ pid: number;
+ host: string;
+ startedAt: string;
+}
+
+/** A lock older than this is taken for one whose run ended without removing it. */
+const STALE_AFTER_MS = 6 * 60 * 60 * 1000;
+
+function isAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ // EPERM: the process exists, it is only someone else's.
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+function holderOf(text: string): Holder | null {
+ try {
+ const held = JSON.parse(text) as Partial;
+ return typeof held.pid === "number" &&
+ typeof held.host === "string" &&
+ typeof held.startedAt === "string"
+ ? (held as Holder)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * One run of a command at a time: an exclusive lock file beside the record. A second run is
+ * refused in words. A lock whose process has ended on this machine, or that is hours old, is stale:
+ * it is moved aside and checked to be the one judged stale before it is removed, so two runs that
+ * both find it stale cannot remove a lock a third has just taken. Returns the release.
+ */
+export async function takeLock(sys: System, command: string): Promise<() => Promise> {
+ const dir = configDir(sys);
+ await mkdir(dir, { recursive: true });
+ const path = join(dir, `${command}.lock`);
+ const mine = JSON.stringify({
+ pid: process.pid,
+ host: hostname(),
+ startedAt: new Date(Date.now()).toISOString(),
+ } satisfies Holder);
+ const busy = (held: Holder | null) =>
+ new CliError(
+ "requirement",
+ "run-in-progress",
+ `Another \`gateweave ${command.replaceAll("-", " ")}\` is running${held ? ` (process ${held.pid} on ${held.host}, since ${held.startedAt})` : ""}. Two at once could both make ID's pairwise secret or both register Track, so this one stops; nothing was changed. Run it again when the other has finished. If none is running, remove ${path}.`,
+ );
+
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ const handle = await open(path, "wx", 0o600);
+ try {
+ await handle.writeFile(mine);
+ } finally {
+ await handle.close();
+ }
+ return async () => {
+ // Only its own lock: one a later run took after this one's was cleared stays.
+ const now = await readFile(path, "utf8").catch(() => null);
+ if (now === mine) await rm(path, { force: true });
+ };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
+ throw new CliError(
+ "requirement",
+ "lock-unwritable",
+ `Could not take the lock ${path} (${(error as NodeJS.ErrnoException).code ?? "error"}).`,
+ );
+ }
+ }
+ const text = await readFile(path, "utf8").catch(() => null);
+ if (text === null) continue; // Removed meanwhile: try again.
+ const held = holderOf(text);
+ const age = await stat(path).then(
+ (found) => Date.now() - found.mtimeMs,
+ () => 0,
+ );
+ const ended = held !== null && held.host === hostname() && !isAlive(held.pid);
+ // A lock that cannot be read is one being written: it is stale only once it is old.
+ if (!ended && age < STALE_AFTER_MS) throw busy(held);
+ const aside = `${path}.stale-${process.pid}-${Date.now()}`;
+ try {
+ await rename(path, aside);
+ } catch {
+ continue; // Another run moved it first.
+ }
+ const moved = await readFile(aside, "utf8").catch(() => null);
+ if (moved !== text) {
+ // A live lock was taken between the read and the move: put it back, never remove it.
+ await link(aside, path).catch(() => undefined);
+ await rm(aside, { force: true });
+ throw busy(holderOf(moved ?? ""));
+ }
+ await rm(aside, { force: true });
+ }
+ throw busy(null);
+}
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 9b777b5..b7095fa 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -82,6 +82,7 @@ Options:
--track-name The recorded Track Worker, when the account has several.
--account The Cloudflare account, when the sign-in reaches several.
Default: CLOUDFLARE_ACCOUNT_ID.
+ --no-account-name Print only the Cloudflare account id, never its name.
--yes Make the changes without asking. Needed when there is no terminal.
--json Print the result, or the failure, as one JSON object on stdout.
--help Show this.
@@ -287,7 +288,6 @@ export async function main(argv: string[], sys: System): Promise {
"bucket",
"queue",
"no-attachments",
- "no-account-name",
];
const foreignOptions = connect
? connectForeign
@@ -324,6 +324,18 @@ export async function main(argv: string[], sys: System): Promise {
`\`gateweave ${command}\` has no option --${foreign[0]}.\n\n${usageOf()}`,
);
}
+ // Node prints what it hands a child, the environment with the Cloudflare API token included,
+ // once NODE_DEBUG names child_process. It reads NODE_DEBUG as it starts, so it cannot be
+ // unset from here: the run stops instead.
+ if (
+ Object.entries(sys.env).some(([key, value]) => key.toUpperCase() === "NODE_DEBUG" && value)
+ ) {
+ throw new CliError(
+ "requirement",
+ "node-debug-set",
+ "NODE_DEBUG is set, which makes Node print what this tool hands the programs it starts, the Cloudflare API token included. Run it again without NODE_DEBUG.",
+ );
+ }
for (const option of ["id-name", "track-name"] as const) {
const given = values[option];
if (given !== undefined && !NAME.test(given)) {
@@ -342,6 +354,7 @@ export async function main(argv: string[], sys: System): Promise {
idName: values["id-name"],
trackName: values["track-name"],
account: values.account,
+ accountName: values["no-account-name"] !== true,
yes: values.yes === true,
json,
});
@@ -358,10 +371,11 @@ export async function main(argv: string[], sys: System): Promise {
}
if (doctor) {
if (values.url !== undefined && !/^https?:\/\/[^\s/]+/.test(values.url)) {
+ // A value with an @ may hold a name and password, so it is not repeated.
throw new CliError(
"usage",
"bad-url",
- `"${values.url}" is not an address: use https://.`,
+ `${values.url.includes("@") ? "--url" : `"${values.url}"`} is not an address: use https://.`,
);
}
const found = await (command === "doctor id" ? doctorId : doctorTrack)(sys, {
diff --git a/packages/cli/src/registration.ts b/packages/cli/src/registration.ts
new file mode 100644
index 0000000..5906e27
--- /dev/null
+++ b/packages/cli/src/registration.ts
@@ -0,0 +1,48 @@
+import { json } from "./deploy-track.ts";
+
+/** The app id Track is registered under with ID's `apps:add`, as in ID's own example. */
+export const TRACK_APP = "track";
+
+/** Where ID sends someone back to Track after sign-in, as Track's self-hosting guide names it. */
+export function callbackUri(trackAddress: string): string {
+ return `${trackAddress}/api/auth/callback/oidc`;
+}
+
+/** Where ID tells Track that someone signed out of ID. */
+export function backchannelLogoutUri(trackAddress: string): string {
+ return `${trackAddress}/api/auth/backchannel-logout/oidc`;
+}
+
+/** A text as an SQL string literal, its quotes doubled, as ID's own apps:add writes its values. */
+export function sqlString(value: string): string {
+ return `'${value.replaceAll("'", "''")}'`;
+}
+
+/**
+ * The one query this tool runs on ID's database: the first-party apps registered as Track with
+ * Track's redirect URI. apps:add stores the URIs as a JSON list and the app id in `metadata`.
+ * json_quote makes the whole URI the thing matched, so a longer URI on the same host does not
+ * count; the app id keeps another app with the same callback from being taken for Track; and a
+ * `metadata` that is not JSON is passed over instead of failing the whole query.
+ */
+export function trackRegistrationSql(redirectUri: string): string {
+ return [
+ "SELECT client_id FROM oauth_client",
+ "WHERE reference_id IS NULL",
+ `AND (CASE WHEN json_valid(metadata) THEN json_extract(metadata, '$.app') END) = ${sqlString(TRACK_APP)}`,
+ `AND instr(redirect_uris, json_quote(${sqlString(redirectUri)})) > 0`,
+ ].join(" ");
+}
+
+/** The client ids in Wrangler's `d1 execute --json` answer, or null when it cannot be read. */
+export function readClientIds(stdout: string): string[] | null {
+ try {
+ const answer = json<{ results?: { client_id?: unknown }[] }[]>(stdout);
+ const rows = answer[0]?.results;
+ if (!Array.isArray(rows)) return null;
+ const ids = rows.map(({ client_id }) => client_id);
+ return ids.every((id): id is string => typeof id === "string") ? ids : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/cli/src/system.ts b/packages/cli/src/system.ts
index 571a759..25b895d 100644
--- a/packages/cli/src/system.ts
+++ b/packages/cli/src/system.ts
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
+import type { FileHandle } from "node:fs/promises";
import { homedir } from "node:os";
import { createInterface } from "node:readline";
import { setTimeout as delay } from "node:timers/promises";
@@ -64,14 +65,27 @@ export interface System {
/** Random bytes for a secret this tool makes itself; node:crypto's when unset. Tests set it. */
random?: (bytes: number) => Uint8Array;
/**
- * Writes a file a person is to keep; node:fs's when unset. Tests wrap it to see the mode asked
- * for, which Windows does not keep.
+ * Opens a new file a person is to keep; node:fs's `open` when unset. Tests wrap it to see the
+ * flags and the mode asked for, which Windows does not keep.
*/
- writeFile?: (
- path: string,
- data: string,
- options: { flag: string; mode: number },
- ) => Promise;
+ openNew?: (path: string, flags: number, mode: number) => Promise;
+}
+
+/**
+ * What a child is started with: the given environment without the two settings that make a child
+ * write what it is handed where this tool cannot filter it. NODE_DEBUG has Node print a process's
+ * internals, the environment of what it starts included; WRANGLER_LOG_SANITIZE=false has Wrangler
+ * keep request bodies, such as a secret's value, in its log file. Without it, Wrangler sanitises.
+ */
+export function childEnv(
+ env: Record,
+): Record {
+ // Windows matches names in any case, so they are compared in one.
+ return Object.fromEntries(
+ Object.entries(env).filter(
+ ([name]) => !["NODE_DEBUG", "WRANGLER_LOG_SANITIZE"].includes(name.toUpperCase()),
+ ),
+ );
}
export function realSystem(): System {
@@ -80,7 +94,7 @@ export function realSystem(): System {
return new Promise((resolve) => {
const common = {
cwd: options.cwd,
- env: options.env ?? process.env,
+ env: childEnv(options.env ?? process.env),
shell: false,
windowsHide: true,
} as const;
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index 78ec74d..53a651d 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -1,41 +1,52 @@
import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
import {
+ constants,
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
+ rmdirSync,
rmSync,
statSync,
+ symlinkSync,
+ unlinkSync,
writeFileSync,
} from "node:fs";
-import { writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { open } from "node:fs/promises";
+import { hostname, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { after, describe, test } from "node:test";
import { parse } from "jsonc-parser";
import { hideSecrets } from "../src/deploy-track.ts";
import { main } from "../src/main.ts";
-import { recordPath } from "../src/record.ts";
+import { configDir } from "../src/paths.ts";
+import { type ConnectionRecord, recordPath, saveConnection, saveRecord } from "../src/record.ts";
import type { HttpRequest, RunOptions } from "../src/system.ts";
import { type FakeOptions, fakeSystem, readsOnly, WRANGLER } from "./fake.ts";
-// Known fake secrets. Each must reach only what the test allows, and nothing else.
+// Known fake secrets, in the shapes ID makes them. Each must reach only what the test allows.
const PAIRWISE_BYTES = Buffer.from("pairwise-bytes-known-to-this-test-only-0123456789").subarray(
0,
48,
);
const PAIRWISE = PAIRWISE_BYTES.toString("base64");
-const CLIENT_ID = "dGVzdC1jbGllbnQtaWQtMDEyMzQ1Njc4OQ";
-const CLIENT_SECRET = "gwid_cs_c2VjcmV0LW9mLXRoZS10ZXN0LWNsaWVudC0wMTIzNDU2Nzg5";
+const CLIENT_ID = Buffer.from("test-client-id-012345678").toString("base64url");
+const OTHER_CLIENT_ID = Buffer.from("another-client-id-987654").toString("base64url");
+const CLIENT_SECRET = `gwid_cs_${Buffer.from("secret-of-the-test-client-012345").toString("base64url")}`;
const API_TOKEN = "api-token-known-to-this-test-0123456789";
const OAUTH_TOKEN = "oauth-token-known-to-this-test-abcdefghij";
const SECRETS = { PAIRWISE, CLIENT_SECRET, API_TOKEN, OAUTH_TOKEN };
+/** In Wrangler's deployment JSON, which is read and never shown. */
+const AUTHOR_EMAIL = "deployment-author@example.com";
const ID = "https://gateweave-id.rehearsal.workers.dev";
const TRACK = "https://gateweave-track.rehearsal.workers.dev";
const ADD_APP = join("scripts", "add-app.ts");
+const STRICT = "global_fetch_strictly_public";
+const LOCK = "connect-id-track.lock";
const cleanup: string[] = [];
after(() => {
@@ -46,17 +57,38 @@ interface ConnectFakeOptions extends FakeOptions {
/** Secrets each Worker has besides BETTER_AUTH_SECRET. */
idSecrets?: string[];
trackSecrets?: string[];
+ /** Text variables of each Worker, by name. */
+ idVars?: Record;
+ trackVars?: Record;
+ /** Other bindings of Track, by name and type. */
+ trackBindings?: Record;
+ /** Each Worker's compatibility flags. Default: Track has global_fetch_strictly_public, ID not. */
+ idFlags?: string[];
+ trackFlags?: string[];
/** Client ids already registered in ID for Track's redirect URI. */
registered?: string[];
- /** Replaces what the fake apps:add prints. */
- appsAddOutput?: string;
+ /** Replaces what the fake apps:add prints, and its status and stderr. */
+ appsAdd?: { stdout: string; status?: number; stderr?: string };
/** A `secret put` of this name fails, echoing its value and the tokens on stderr. */
failPut?: string;
+ /** Makes this look fail. */
+ failLook?: "deployments" | "versions";
+ /** A secret the secret list shows and the deployed version does not. */
+ missingFromVersion?: string;
+ /** How many versions the deployment spreads over. */
+ versions?: number;
+ /** ID's discovery never answers. */
+ discoveryDown?: boolean;
+ /** A button Track's sign-in page shows whatever is set. */
+ extraButton?: string;
+ /** The name on Track's provider button, instead of the one set. */
+ buttonName?: string;
}
/**
* Two deployments made by this tool in the fake account, ID and Track, and a fake that also knows
- * `wrangler secret put`, ID's apps:add, the registration query and the provider's two pages.
+ * `wrangler secret put`, the deployed version's bindings, ID's apps:add, the registration query and
+ * the two pages the checks read.
*/
async function connectFake(options: ConnectFakeOptions = {}) {
const fake = fakeSystem({ ...options, env: { CLOUDFLARE_API_TOKEN: API_TOKEN, ...options.env } });
@@ -72,12 +104,19 @@ async function connectFake(options: ConnectFakeOptions = {}) {
`oauth_token = "${OAUTH_TOKEN}"\nrefresh_token = "refresh-0123456789"\n`,
);
- const puts: { worker: string; name: string; input: string | undefined }[] = [];
+ const state = { failPut: options.failPut, beforeOpen: undefined as (() => void) | undefined };
+ const puts: { worker: string; name: string; input: string | undefined; errBefore: string }[] = [];
const appsAdd: { args: string[]; cwd: string }[] = [];
const registrations = [...(options.registered ?? [])];
+ /** What each put set, so the pages show what Track was given. */
+ const values = new Map();
+ const vars: Record> = {
+ "gateweave-id": { ...options.idVars },
+ "gateweave-track": { ...options.trackVars },
+ };
let randomCalls = 0;
- /** Each file written for a person to keep, with the options the write asked for. */
- const kept: { path: string; options: { flag: string; mode: number } }[] = [];
+ /** Each file opened for a person to keep, with the flags and mode asked for. */
+ const kept: { path: string; flags: number; mode: number }[] = [];
const secretsOf = (worker: string) => {
let set = fake.cloud.secrets.get(worker);
if (!set) {
@@ -86,6 +125,10 @@ async function connectFake(options: ConnectFakeOptions = {}) {
}
return set;
};
+ const setting = (worker: string, name: string) =>
+ vars[worker]?.[name] ?? (secretsOf(worker).has(name) ? values.get(`${worker} ${name}`) : null);
+ const isSet = (worker: string, name: string) =>
+ vars[worker]?.[name] !== undefined || secretsOf(worker).has(name);
const inner = fake.sys.run;
fake.sys.run = async (command: string, args: string[], runOptions: RunOptions) => {
@@ -97,12 +140,12 @@ async function connectFake(options: ConnectFakeOptions = {}) {
});
const at = args.indexOf(`wrangler@${WRANGLER}`);
const rest = at >= 0 ? args.slice(at + 1) : [];
+ const worker = rest[rest.indexOf("--name") + 1] ?? "";
if (command === fake.sys.execPath && rest[0] === "secret" && rest[1] === "put") {
record();
const name = rest[2] ?? "";
- const worker = rest[rest.indexOf("--name") + 1] ?? "";
- puts.push({ worker, name, input: runOptions.input });
- if (options.failPut === name) {
+ puts.push({ worker, name, input: runOptions.input, errBefore: fake.output.err });
+ if (state.failPut === name) {
return {
status: 1,
stdout: "",
@@ -110,12 +153,70 @@ async function connectFake(options: ConnectFakeOptions = {}) {
};
}
secretsOf(worker).add(name);
+ values.set(`${worker} ${name}`, runOptions.input ?? "");
return {
status: 0,
stdout: `🌀 Creating the secret for the Worker "${worker}"\n✨ Success! Uploaded secret ${name}\n`,
stderr: "",
};
}
+ if (command === fake.sys.execPath && rest[0] === "deployments" && rest[1] === "status") {
+ record();
+ if (options.failLook === "deployments") {
+ return {
+ status: 1,
+ stdout: "",
+ stderr: "✘ [ERROR] A request to the Cloudflare API failed.\n",
+ };
+ }
+ const versions = Array.from({ length: options.versions ?? 1 }, (_, index) => ({
+ version_id: `0000000${index}-aaaa-bbbb-cccc-${worker.length.toString().padStart(12, "0")}`,
+ percentage: 100 / (options.versions ?? 1),
+ }));
+ return {
+ status: 0,
+ stdout: JSON.stringify({ id: "d1", author_email: AUTHOR_EMAIL, versions }),
+ stderr: "",
+ };
+ }
+ if (command === fake.sys.execPath && rest[0] === "versions" && rest[1] === "view") {
+ record();
+ if (options.failLook === "versions") {
+ return {
+ status: 1,
+ stdout: "",
+ stderr: "✘ [ERROR] A request to the Cloudflare API failed.\n",
+ };
+ }
+ const flags =
+ worker === "gateweave-track" ? (options.trackFlags ?? [STRICT]) : (options.idFlags ?? []);
+ const bindings = [
+ { type: "d1", name: "DB", id: `uuid-${worker}` },
+ ...[...secretsOf(worker)]
+ .filter((name) => name !== options.missingFromVersion)
+ .map((name) => ({ type: "secret_text", name })),
+ ...Object.entries(vars[worker] ?? {}).map(([name, text]) => ({
+ type: "plain_text",
+ name,
+ text,
+ })),
+ ...Object.entries(worker === "gateweave-track" ? (options.trackBindings ?? {}) : {}).map(
+ ([name, type]) => ({ type, name }),
+ ),
+ ];
+ return {
+ status: 0,
+ stdout: JSON.stringify({
+ id: rest[2],
+ metadata: { author_email: AUTHOR_EMAIL },
+ resources: {
+ bindings,
+ script_runtime: { compatibility_date: "2026-01-01", compatibility_flags: flags },
+ },
+ }),
+ stderr: "",
+ };
+ }
if (
command === fake.sys.execPath &&
rest[0] === "d1" &&
@@ -144,15 +245,18 @@ async function connectFake(options: ConnectFakeOptions = {}) {
const config = readFileSync(join(runOptions.cwd, "..", "..", "wrangler.jsonc"), "utf8");
assert.match(config, /"database_name": "gateweave-id"/);
assert.equal(runOptions.stream, undefined);
- if (options.appsAddOutput !== undefined) {
- registrations.push(CLIENT_ID);
- return { status: 0, stdout: options.appsAddOutput, stderr: "" };
- }
registrations.push(CLIENT_ID);
+ if (options.appsAdd !== undefined) {
+ return {
+ status: options.appsAdd.status ?? 0,
+ stdout: options.appsAdd.stdout,
+ stderr: options.appsAdd.stderr ?? "",
+ };
+ }
return {
status: 0,
stdout: `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\n`,
- stderr: "",
+ stderr: "(node) ExperimentalWarning: Type Stripping is an experimental feature\n",
};
}
const result = await inner(command, args, runOptions);
@@ -173,30 +277,40 @@ async function connectFake(options: ConnectFakeOptions = {}) {
const { pathname, origin } = new URL(url);
if (pathname === "/.well-known/openid-configuration") {
fake.events.push(`fetch GET ${url}`);
- const id = secretsOf("gateweave-id");
- return id.has("BETTER_AUTH_URL") && id.has("OIDC_PAIRWISE_SECRET")
+ return !options.discoveryDown &&
+ isSet("gateweave-id", "BETTER_AUTH_URL") &&
+ isSet("gateweave-id", "OIDC_PAIRWISE_SECRET")
? { status: 200, headers: {}, text: JSON.stringify({ issuer: origin }) }
: { status: 404, headers: {}, text: "" };
}
- if (pathname === "/login" && !url.startsWith(ID)) {
+ if (pathname === "/login" && !url.startsWith(ID) && !url.startsWith("https://id.")) {
fake.events.push(`fetch GET ${url}`);
- const track = secretsOf("gateweave-track");
+ const track = "gateweave-track";
const on = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"].every((name) =>
- track.has(name),
+ isSet(track, name),
);
+ const name = options.buttonName ?? setting(track, "OIDC_PROVIDER_NAME") ?? "single sign-on";
+ const issuer = setting(track, "OIDC_ISSUER");
+ const buttons = [
+ ...(on ? [`Continue with ${name} `] : []),
+ ...(options.extraButton ? [`Continue with ${options.extraButton} `] : []),
+ ].join("");
return {
status: 200,
- headers: {},
- text: `Gateweave Track ${on ? "Continue with Gateweave ID " : ""}`,
+ headers: {
+ "content-security-policy": `default-src 'none'; img-src 'self' data: blob: https://avatars.githubusercontent.com${issuer ? ` ${new URL(issuer).origin}` : ""}; font-src 'self'`,
+ },
+ text: `Gateweave Track ${buttons}`,
};
}
return innerFetch(url, request);
};
fake.sys.cwd = work;
- fake.sys.writeFile = async (path, data, writeOptions) => {
- kept.push({ path, options: writeOptions });
- await writeFile(path, data, writeOptions);
+ fake.sys.openNew = async (path, flags, mode) => {
+ kept.push({ path, flags, mode });
+ state.beforeOpen?.();
+ return open(path, flags, mode);
};
fake.sys.random = (bytes: number) => {
randomCalls++;
@@ -222,31 +336,34 @@ async function connectFake(options: ConnectFakeOptions = {}) {
return { code, result, out: fake.output.out, err: fake.output.err };
}
- /** Every file this run could have written to, outside the one the test allows. */
+ /** Every file this run could have written to, outside the ones the test allows. */
function writtenFiles(allowed: readonly string[] = []): string[] {
const files: string[] = [];
- const walk = (dir: string) => {
- let entries: string[];
+ const visit = (path: string) => {
+ let stat: ReturnType;
try {
- entries = readdirSync(dir);
+ stat = lstatSync(path);
} catch {
+ return; // Another test file removed it meanwhile.
+ }
+ if (stat.isFile()) {
+ files.push(path);
return;
}
- for (const entry of entries) {
- const path = join(dir, entry);
- try {
- const stat = lstatSync(path);
- if (stat.isDirectory()) walk(path);
- else if (stat.isFile()) files.push(path);
- } catch {
- // Another test file removed it meanwhile.
- }
+ if (!stat.isDirectory()) return;
+ let entries: string[] = [];
+ try {
+ entries = readdirSync(path);
+ } catch {
+ return;
}
+ for (const entry of entries) visit(join(path, entry));
};
- walk(work);
- walk(fake.home);
+ visit(work);
+ visit(fake.home);
+ // The OS temp folder: new folders, and new files at its top level too.
for (const entry of readdirSync(tmpdir())) {
- if (!tmpBefore.has(entry)) walk(join(tmpdir(), entry));
+ if (!tmpBefore.has(entry)) visit(join(tmpdir(), entry));
}
const skip = new Set([oauthFile, ...allowed].map((path) => resolve(path)));
return files.filter((path) => !skip.has(resolve(path)));
@@ -259,11 +376,18 @@ async function connectFake(options: ConnectFakeOptions = {}) {
puts,
appsAdd,
registrations,
+ values,
+ vars,
+ state,
connect,
writtenFiles,
randomCalls: () => randomCalls,
kept,
newCalls: () => fake.calls.slice(callsBefore),
+ changes: () =>
+ fake.calls
+ .slice(callsBefore)
+ .filter((call) => !readsOnly(call) && !call.argv.includes("clone")),
};
}
@@ -287,6 +411,24 @@ function leakedInFiles(files: string[], which: Record = SECRETS)
return found;
}
+/** A folder link that needs no rights on Windows: a junction there, a symlink elsewhere. */
+function linkFolder(target: string, path: string) {
+ symlinkSync(target, path, "junction");
+}
+
+function unlinkFolder(path: string) {
+ try {
+ unlinkSync(path);
+ } catch {
+ rmdirSync(path);
+ }
+}
+
+const keepArgs = (run: { keepDir: string }, name = "pairwise.txt") => [
+ "--keep-secret-at",
+ join(run.keepDir, name),
+];
+
describe("gateweave connect id track", () => {
test("the shared filter hides ID's client secret line, its prefix and OIDC secret assignments", () => {
assert.equal(hideSecrets("client secret: abcdefghijkl", []), "client secret: [secret]");
@@ -312,6 +454,7 @@ describe("gateweave connect id track", () => {
assert.equal(result.ok, true);
assert.equal(result.clientId, CLIENT_ID);
assert.equal(result.registeredNow, true);
+ assert.deepEqual(result.account, { id: "a1b2c3", name: "Rehearsal" });
assert.deepEqual(result.id, { worker: "gateweave-id", address: ID, issuer: ID });
assert.deepEqual(result.track, { worker: "gateweave-track", address: TRACK });
assert.deepEqual(result.pairwiseSecret, {
@@ -346,14 +489,24 @@ describe("gateweave connect id track", () => {
["OIDC_PAIRWISE_SECRET", "OIDC_CLIENT_SECRET"],
);
assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`);
- // Asked for on every platform: new only, and readable by its owner alone. Where the system
- // keeps modes, the file has it.
- assert.deepEqual(run.kept, [{ path: keep, options: { flag: "wx", mode: 0o600 } }]);
+ // Asked for on every platform: made new, never through a link in its last part, readable by
+ // its owner alone. Where the system keeps modes, the file has it.
+ assert.equal(run.kept.length, 1);
+ const [opened] = run.kept;
+ assert.equal(opened?.path, keep);
+ assert.equal(opened?.mode, 0o600);
+ for (const flag of [constants.O_CREAT, constants.O_EXCL, constants.O_WRONLY]) {
+ assert.equal((opened?.flags ?? 0) & flag, flag);
+ }
+ if (constants.O_NOFOLLOW !== undefined) {
+ assert.equal((opened?.flags ?? 0) & constants.O_NOFOLLOW, constants.O_NOFOLLOW);
+ }
if (process.platform !== "win32") assert.equal(statSync(keep).mode & 0o777, 0o600);
// Nowhere else: not the screen, not --json, not the record, not a file, not an argument.
assert.deepEqual(leaked(out), []);
assert.deepEqual(leaked(err), []);
+ assert.ok(!`${out}${err}`.includes(AUTHOR_EMAIL));
assert.deepEqual(leaked(readFileSync(recordPath(run.fake.sys), "utf8")), []);
assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []);
assert.deepEqual(
@@ -376,7 +529,7 @@ describe("gateweave connect id track", () => {
]);
assert.match(run.appsAdd[0]?.cwd ?? "", /[\\/]id[\\/]v0\.50\.0-gateweave-id[\\/]apps[\\/]web$/);
- // The record keeps the client id, never a secret.
+ // The record keeps the client id, never a secret, and the lock is gone again.
const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8"));
assert.equal(file.deployments.length, 2);
assert.deepEqual(
@@ -386,15 +539,43 @@ describe("gateweave connect id track", () => {
})),
[{ clientId: CLIENT_ID, steps: ["registered", "connected", "checked"] }],
);
+ assert.ok(!existsSync(join(configDir(run.fake.sys), LOCK)));
+ });
+
+ test("--no-account-name keeps the account's name out of the plan, the errors and --json", async () => {
+ const name = "owner@example.com's Account";
+ const run = await connectFake({ accounts: [{ id: "a1b2c3", name }] });
+ const { code, result, out, err } = await run.connect([
+ ...keepArgs(run),
+ "--no-account-name",
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 0, err);
+ assert.deepEqual(result.account, { id: "a1b2c3" });
+ assert.match(err, /Connect Track to ID in the Cloudflare account a1b2c3, so/);
+ for (const text of [out, err]) {
+ assert.ok(!text.includes("owner@example.com"), text);
+ assert.ok(!text.includes(name));
+ }
+ // An error that names the account names it by id alone.
+ const again = await connectFake({ accounts: [{ id: "a1b2c3", name }] });
+ const failed = await again.connect(["--no-account-name", "--id-name", "nope", "--json"]);
+ assert.equal(failed.code, 3);
+ assert.match(failed.result.reason, /in the Cloudflare account a1b2c3\./);
+ assert.ok(!`${failed.out}${failed.err}`.includes("owner@example.com"));
});
- test("without --keep-secret-at, a terminal shows the pairwise secret once, with words to keep it", async () => {
+ test("without --keep-secret-at, a terminal shows the pairwise secret once, before it is set", async () => {
const run = await connectFake({ interactive: true, answer: true });
const { code, out, err } = await run.connect([]);
assert.equal(code, 0, err);
assert.equal(err.split(PAIRWISE).length - 1, 1);
assert.match(err, /Keep this value now, in your password manager/);
assert.match(err, /gives everyone a new id in every app/);
+ // On the screen before ID has it, so a run cut short after the put leaves a copy.
+ const pairwisePut = run.puts.find(({ name }) => name === "OIDC_PAIRWISE_SECRET");
+ assert.ok(pairwisePut?.errBefore.includes(PAIRWISE));
assert.deepEqual(leaked(out), []);
assert.deepEqual(leaked(err, { CLIENT_SECRET, API_TOKEN, OAUTH_TOKEN }), []);
assert.deepEqual(leakedInFiles(run.writtenFiles()), []);
@@ -402,43 +583,50 @@ describe("gateweave connect id track", () => {
assert.match(out, /signs people in through ID \(gateweave-id\) now/);
});
- test("a second run registers nothing again and replaces no secret", async () => {
+ test("a second run registers nothing again, replaces no secret, and accepts the same keep file", async () => {
const run = await connectFake();
const keep = join(run.keepDir, "pairwise.txt");
assert.equal((await run.connect(["--keep-secret-at", keep, "--yes"])).code, 0);
const puts = run.puts.length;
- const second = await run.connect(["--yes", "--json"]);
+ // The same command again: the file it wrote exists, and nothing is made to go in it.
+ const second = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]);
assert.equal(second.code, 0, second.err);
assert.equal(second.result.changedNow, false);
assert.equal(second.result.registeredNow, false);
assert.equal(second.result.clientId, CLIENT_ID);
+ assert.equal(second.result.pairwiseSecret.keptAt, null);
assert.equal(run.appsAdd.length, 1);
assert.equal(run.puts.length, puts);
assert.equal(run.randomCalls(), 1);
assert.equal(run.registrations.length, 1);
+ assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`);
assert.match(second.err, /An earlier run connected these already; nothing will be changed/);
+ assert.match(
+ second.err,
+ /OIDC_PAIRWISE_SECRET is already set, so --keep-secret-at is not used/,
+ );
});
- test("apps:add output in another form stops, and nothing it printed is shown", async () => {
+ test("apps:add output in any other form stops, and nothing it printed is shown", async () => {
+ const tooLong = `${CLIENT_ID}xy`;
+ const secretAsId = `gwid_cs_${"a".repeat(24)}`;
for (const output of [
`Registered Gateweave Track.\nclient id ${CLIENT_ID}\nclient secret ${CLIENT_SECRET}\n`,
- `Registered Gateweave Track.\nclient id: ${CLIENT_ID}\nclient secret: plain-secret-without-its-prefix-0123456789\n`,
- `Registered Gateweave Track.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\nclient secret: ${CLIENT_SECRET}\n`,
+ `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: plain-secret-without-its-prefix-0123456789\n`,
+ `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\nclient secret: ${CLIENT_SECRET}\n`,
+ `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\nextra: something else\n`,
+ `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${tooLong}\nclient secret: ${CLIENT_SECRET}\n`,
+ `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${secretAsId}\nclient secret: ${CLIENT_SECRET}\n`,
]) {
- const run = await connectFake({ appsAddOutput: output });
- const keep = join(run.keepDir, "pairwise.txt");
- const { code, result, out, err } = await run.connect([
- "--keep-secret-at",
- keep,
- "--yes",
- "--json",
- ]);
- assert.equal(code, 8);
+ const run = await connectFake({ appsAdd: { stdout: output } });
+ const { code, result, out, err } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 8, output);
assert.equal(result.code, "register-output-unreadable");
for (const text of [out, err]) {
assert.doesNotMatch(text, /Registered Gateweave Track/);
- assert.ok(!text.includes(CLIENT_ID), "the captured client id is not shown");
- assert.ok(!text.includes("plain-secret-without-its-prefix"));
+ for (const value of [CLIENT_ID, tooLong, secretAsId, "plain-secret-without-its-prefix"]) {
+ assert.ok(!text.includes(value), "nothing captured is shown");
+ }
assert.deepEqual(leaked(text), []);
}
assert.deepEqual(
@@ -446,14 +634,40 @@ describe("gateweave connect id track", () => {
[],
"Track is given nothing",
);
- assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []);
+ assert.ok(!readFileSync(recordPath(run.fake.sys), "utf8").includes(secretAsId));
+ assert.deepEqual(leakedInFiles(run.writtenFiles([join(run.keepDir, "pairwise.txt")])), []);
}
});
- test("settings already set are left alone", async () => {
+ test("apps:add stopping says where to look and repeats none of its output", async () => {
const run = await connectFake({
- idSecrets: ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"],
- trackSecrets: ["BETTER_AUTH_URL", "OIDC_PROVIDER_NAME"],
+ appsAdd: {
+ status: 1,
+ stdout: "",
+ stderr: "✘ [ERROR] D1 said no: detail-from-the-child-0123 and plain-secret-zz-0123456789\n",
+ },
+ });
+ const { code, result, out, err } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 8);
+ assert.equal(result.code, "register-failed");
+ assert.match(result.reason, /exit 1/);
+ assert.match(result.reason, /d1 execute DB --remote --command "SELECT 1"/);
+ for (const text of [out, err]) {
+ assert.ok(!text.includes("detail-from-the-child"));
+ assert.ok(!text.includes("plain-secret-zz"));
+ }
+ assert.deepEqual(
+ run.puts.filter(({ worker }) => worker === "gateweave-track"),
+ [],
+ );
+ });
+
+ test("settings already set are left alone, text variables included, and their values used", async () => {
+ const run = await connectFake({
+ idSecrets: ["OIDC_PAIRWISE_SECRET"],
+ idVars: { BETTER_AUTH_URL: ID },
+ trackSecrets: ["BETTER_AUTH_URL"],
+ trackVars: { OIDC_PROVIDER_NAME: "Acme Sign-in" },
});
// No pairwise secret is made, so --json needs no file to keep one in.
const { code, result, err } = await run.connect(["--yes", "--json"]);
@@ -479,14 +693,74 @@ describe("gateweave connect id track", () => {
"track BETTER_AUTH_URL",
],
);
+ assert.match(err, /BETTER_AUTH_URL\s+\(already set as a text variable; left as it is\)/);
assert.match(err, /OIDC_PAIRWISE_SECRET\s+\(already set; left as it is\)/);
- assert.match(err, /OIDC_PROVIDER_NAME\s+\(already set; left as it is\)/);
+ assert.match(err, /OIDC_PROVIDER_NAME\s+\(already set as a text variable; left as it is\)/);
assert.doesNotMatch(err, /issuer, ID's BETTER_AUTH_URL .* can never change/);
+ // The button is looked for by the text variable's name.
+ assert.ok(
+ result.checks.some(({ name }: { name: string }) =>
+ name.includes('"Continue with Acme Sign-in"'),
+ ),
+ );
+ });
+
+ test("ID's BETTER_AUTH_URL as a text variable names the issuer, before anything changes", async () => {
+ const run = await connectFake({ idVars: { BETTER_AUTH_URL: "https://id.example.com" } });
+ const given = await run.connect(["--id-url", ID, ...keepArgs(run), "--yes", "--json"]);
+ assert.equal(given.code, 3);
+ assert.equal(given.result.code, "issuer-differs");
+ assert.deepEqual(run.changes(), []);
+ });
+
+ test("a setting held by another kind of binding stops the run, and replaces nothing", async () => {
+ const run = await connectFake({ trackBindings: { OIDC_ISSUER: "kv_namespace" } });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "name-in-use");
+ assert.deepEqual(run.changes(), []);
+ });
+
+ test("Track's BETTER_AUTH_URL as a text variable for another address stops the run", async () => {
+ const run = await connectFake({
+ trackVars: { BETTER_AUTH_URL: "https://elsewhere.example.com" },
+ });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "track-address-differs");
+ assert.deepEqual(run.changes(), []);
});
- test("the plan names both deployments, both addresses and every setting, and waits", async () => {
+ test("a look that fails, or listings that disagree, stop the run: nothing unseen counts as absent", async () => {
+ const looks: [ConnectFakeOptions, string][] = [
+ [{ failLook: "deployments" }, "lookup-failed"],
+ [{ failLook: "versions" }, "lookup-failed"],
+ [{ missingFromVersion: "BETTER_AUTH_SECRET" }, "lookup-failed"],
+ [{ versions: 2 }, "gradual-deployment"],
+ [
+ { idSecrets: ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"], discoveryDown: true },
+ "provider-unreachable",
+ ],
+ ];
+ for (const [fakeOptions, code] of looks) {
+ const run = await connectFake(fakeOptions);
+ const {
+ code: exit,
+ result,
+ out,
+ err,
+ } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(exit, 3, JSON.stringify(fakeOptions));
+ assert.equal(result.code, code);
+ assert.match(result.reason, /Nothing was changed/);
+ assert.deepEqual(run.changes(), []);
+ assert.ok(!`${out}${err}`.includes(AUTHOR_EMAIL));
+ }
+ });
+
+ test("the plan names both deployments, ID's database and every setting, and waits", async () => {
const run = await connectFake();
- const { code, err } = await run.connect(["--keep-secret-at", join(run.keepDir, "k")]);
+ const { code, err } = await run.connect(keepArgs(run, "k"));
assert.equal(code, 7);
for (const text of [
/Connect Track to ID in the Cloudflare account Rehearsal \(a1b2c3\)/,
@@ -494,6 +768,7 @@ describe("gateweave connect id track", () => {
/Track\s+gateweave-track\s+at https:\/\/gateweave-track\.rehearsal\.workers\.dev/,
/On ID \(gateweave-id\):\n\s+BETTER_AUTH_URL\s+https:\/\/gateweave-id\.rehearsal\.workers\.dev\s+\(set now\)/,
/OIDC_PAIRWISE_SECRET\s+generated here, kept at .*k, never shown\s+\(set now\)/,
+ /Register Track with ID, with ID's own apps:add, in ID's D1 database gateweave-id \(uuid-gateweave-id\):/,
/redirect URI\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev\/api\/auth\/callback\/oidc/,
/back-channel logout\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev\/api\/auth\/backchannel-logout\/oidc/,
/OIDC_CLIENT_SECRET\s+from the registration, never shown\s+\(set now\)/,
@@ -506,18 +781,51 @@ describe("gateweave connect id track", () => {
assert.match(err, text);
}
// Before the yes it only read: listings, the one SELECT, outside pages, and the release cache.
- const changes = run
- .newCalls()
- .filter((call) => !readsOnly(call) && !call.argv.includes("clone"));
- assert.deepEqual(changes, []);
+ assert.deepEqual(run.changes(), []);
assert.deepEqual(run.puts, []);
assert.equal(run.appsAdd.length, 0);
assert.ok(!existsSync(join(run.keepDir, "k")));
});
- test("on workers.dev the plan warns about the issuer and about Workers that cannot reach each other", async () => {
+ test("a deployment recorded as not made by this tool is used only when named", async () => {
+ const run = await connectFake();
+ const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8"));
+ for (const deployment of file.deployments) {
+ if (deployment.product === "id") deployment.external = true;
+ }
+ writeFileSync(recordPath(run.fake.sys), JSON.stringify(file));
+ const silent = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(silent.code, 2);
+ assert.equal(silent.result.code, "deployment-not-named");
+ assert.match(silent.result.reason, /--id-name gateweave-id/);
+ assert.deepEqual(run.changes(), []);
+ const named = await run.connect([
+ ...keepArgs(run),
+ "--id-name",
+ "gateweave-id",
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(named.code, 0, named.err);
+ });
+
+ test("ID's database is checked against the record before anything is registered in it", async () => {
+ const run = await connectFake();
+ const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8"));
+ for (const deployment of file.deployments) {
+ if (deployment.product === "id") deployment.databaseId = "uuid-from-before";
+ }
+ writeFileSync(recordPath(run.fake.sys), JSON.stringify(file));
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "database-differs");
+ assert.deepEqual(run.changes(), []);
+ });
+
+ test("the workers.dev warning names the Worker that calls the other and lacks the flag", async () => {
+ // As released: Track has global_fetch_strictly_public, ID does not.
const run = await connectFake();
- const { code, err } = await run.connect(["--keep-secret-at", join(run.keepDir, "k")]);
+ const { code, err } = await run.connect(keepArgs(run, "k"));
assert.equal(code, 7);
assert.match(
err,
@@ -529,10 +837,17 @@ describe("gateweave connect id track", () => {
);
assert.match(
err,
- /Two Workers on workers\.dev cannot reach each other unless each has global_fetch_strictly_public/,
+ /ID \(gateweave-id\) does not have global_fetch_strictly_public in its compatibility_flags, so its back-channel logout cannot reach Track on workers\.dev/,
+ );
+ assert.match(err, /Sign-in works, as there Track calls ID/);
+ assert.doesNotMatch(err, /sign-in through ID fails/);
+
+ const bare = await connectFake({ trackFlags: [] });
+ const without = await bare.connect(keepArgs(bare, "k"));
+ assert.match(
+ without.err,
+ /Track \(gateweave-track\) does not have global_fetch_strictly_public in its compatibility_flags, so it cannot reach ID on workers\.dev: sign-in through ID fails/,
);
- assert.match(err, /ID's back-channel logout cannot reach Track/);
- assert.match(err, /A Custom Domain on each Worker is the setup that works/);
const custom = await connectFake();
const own = await custom.connect([
@@ -540,8 +855,7 @@ describe("gateweave connect id track", () => {
"https://id.example.com",
"--track-url",
"https://track.example.com",
- "--keep-secret-at",
- join(custom.keepDir, "k"),
+ ...keepArgs(custom, "k"),
]);
assert.equal(own.code, 7);
assert.match(own.err, /can never change once any app has signed anyone in/);
@@ -552,7 +866,7 @@ describe("gateweave connect id track", () => {
);
});
- test("--json without --keep-secret-at refuses, as does a run with no terminal", async () => {
+ test("--json without --keep-secret-at refuses while the secret is to be made, as does no terminal", async () => {
const run = await connectFake();
const { code, result, err } = await run.connect(["--yes", "--json"]);
assert.equal(code, 2);
@@ -567,22 +881,52 @@ describe("gateweave connect id track", () => {
assert.equal(run.randomCalls(), 0);
});
- test("a --keep-secret-at path inside the working directory is refused before anything runs", async () => {
+ test("a --keep-secret-at path inside the working directory is refused before anything changes", async () => {
const run = await connectFake();
+ // Into the working directory through a folder link: only the real path shows it.
+ const linked = join(run.keepDir, "looks-outside");
+ linkFolder(run.work, linked);
for (const path of [
join(run.work, "pairwise.txt"),
"pairwise.txt",
join("..", "x", "..", run.work.split(/[\\/]/).at(-1) ?? "", "k"),
+ join(linked, "pairwise.txt"),
]) {
const { code, result } = await run.connect(["--keep-secret-at", path, "--yes", "--json"]);
assert.equal(code, 2, path);
assert.equal(result.code, "keep-path-inside", path);
}
- assert.deepEqual(run.newCalls(), []);
+ assert.deepEqual(run.changes(), []);
assert.deepEqual(readdirSync(run.work), []);
});
- test("a --keep-secret-at file that exists is never overwritten", async () => {
+ test("a folder changed after the plan cannot carry the kept secret into the working directory", async () => {
+ const run = await connectFake();
+ const outside = join(run.keepDir, "real");
+ mkdirSync(outside);
+ const folder = join(run.keepDir, "folder");
+ linkFolder(outside, folder);
+ // Between the plan and the write, the folder is pointed into the working directory.
+ run.state.beforeOpen = () => {
+ unlinkFolder(folder);
+ linkFolder(run.work, folder);
+ };
+ const { code, result, out, err } = await run.connect([
+ "--keep-secret-at",
+ join(folder, "pairwise.txt"),
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 2);
+ assert.equal(result.code, "keep-path-moved");
+ assert.deepEqual(readdirSync(run.work), [], "nothing is left in the working directory");
+ assert.ok(!run.puts.some(({ name }) => name === "OIDC_PAIRWISE_SECRET"));
+ assert.deepEqual(leaked(out), []);
+ assert.deepEqual(leaked(err), []);
+ assert.deepEqual(leakedInFiles(run.writtenFiles()), []);
+ });
+
+ test("a --keep-secret-at file that exists, or a link in its place, is never overwritten", async () => {
const run = await connectFake();
const keep = join(run.keepDir, "kept.txt");
writeFileSync(keep, "a value someone kept\n");
@@ -590,16 +934,27 @@ describe("gateweave connect id track", () => {
assert.equal(code, 2);
assert.equal(result.code, "keep-path-exists");
assert.equal(readFileSync(keep, "utf8"), "a value someone kept\n");
+ const link = join(run.keepDir, "a-link");
+ linkFolder(join(run.keepDir, "nowhere"), link);
+ const linked = await run.connect(["--keep-secret-at", link, "--yes", "--json"]);
+ assert.equal(linked.code, 2);
+ assert.equal(linked.result.code, "keep-path-exists");
+ // A file that appears after the plan is refused where it is opened.
+ const late = join(run.keepDir, "late.txt");
+ run.state.beforeOpen = () => writeFileSync(late, "someone else's\n");
+ const raced = await run.connect(["--keep-secret-at", late, "--yes", "--json"]);
+ assert.equal(raced.code, 2);
+ assert.equal(raced.result.code, "keep-path-exists");
+ assert.equal(readFileSync(late, "utf8"), "someone else's\n");
+ assert.ok(!run.puts.some(({ name }) => name === "OIDC_PAIRWISE_SECRET"));
});
- test("Track registered in ID without Track's secret stops, says how to recover and registers nothing", async () => {
- const run = await connectFake({ registered: [CLIENT_ID] });
- const { code, result } = await run.connect([
- "--keep-secret-at",
- join(run.keepDir, "k"),
- "--yes",
- "--json",
- ]);
+ test("Track registered in ID without Track's secret stops, with steps that end in a run that works", async () => {
+ const run = await connectFake({
+ registered: [CLIENT_ID],
+ trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID"],
+ });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
assert.equal(code, 3);
assert.equal(result.code, "registered-without-secret");
assert.match(result.reason, /never registers Track a second time/);
@@ -608,28 +963,72 @@ describe("gateweave connect id track", () => {
result.reason,
new RegExp(`DELETE FROM oauth_client WHERE client_id = '${CLIENT_ID}'`),
);
+ assert.match(result.reason, /secret delete OIDC_ISSUER --name gateweave-track/);
+ assert.match(result.reason, /secret delete OIDC_CLIENT_ID --name gateweave-track/);
assert.equal(run.appsAdd.length, 0);
assert.deepEqual(run.puts, []);
+
+ // Doing what it says, then running again, connects them.
+ run.registrations.splice(0);
+ const track = run.fake.cloud.secrets.get("gateweave-track");
+ track?.delete("OIDC_ISSUER");
+ track?.delete("OIDC_CLIENT_ID");
+ const again = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(again.code, 0, again.err);
+ assert.equal(again.result.registeredNow, true);
+ });
+
+ test("a visible button is not taken for Track's settings", async () => {
+ const run = await connectFake({ registered: [CLIENT_ID], extraButton: "single sign-on" });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "registered-without-secret");
+ });
+
+ test("an OIDC_PROVIDER_NAME secret this tool did not set stops before anything changes", async () => {
+ const run = await connectFake({ trackSecrets: ["OIDC_PROVIDER_NAME"] });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "provider-name-unknown");
+ assert.match(result.reason, /secret delete OIDC_PROVIDER_NAME --name gateweave-track/);
+ assert.deepEqual(run.changes(), []);
+ });
+
+ test("the button check needs the exact provider name", async () => {
+ const run = await connectFake({ buttonName: "Someone Else" });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 9);
+ assert.equal(result.code, "checks-failed");
+ assert.match(result.reason, /shows "Continue with Gateweave ID" \(the button is not there\)/);
+ });
+
+ test("a registration that differs from the one Track was given stops, with steps to start again", async () => {
+ const run = await connectFake();
+ assert.equal((await run.connect([...keepArgs(run), "--yes"])).code, 0);
+ run.registrations.splice(0, 1, OTHER_CLIENT_ID);
+ const { code, result } = await run.connect(["--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "client-differs");
+ assert.match(result.reason, new RegExp(`registered as client id ${OTHER_CLIENT_ID}`));
+ assert.match(result.reason, new RegExp(`gave Track the client id ${CLIENT_ID}`));
+ assert.match(result.reason, new RegExp(`client_id = '${OTHER_CLIENT_ID}'`));
+ assert.match(result.reason, /secret delete OIDC_CLIENT_SECRET --name gateweave-track/);
+ assert.equal(run.appsAdd.length, 1);
});
test("a Track that already has another provider's client is not changed", async () => {
const run = await connectFake({
trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"],
});
- const { code, result } = await run.connect([
- "--keep-secret-at",
- join(run.keepDir, "k"),
- "--yes",
- "--json",
- ]);
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
assert.equal(code, 3);
assert.equal(result.code, "track-has-provider");
- assert.match(result.reason, /replaces no secret/);
+ assert.match(result.reason, /replaces no setting/);
assert.equal(run.appsAdd.length, 0);
assert.deepEqual(run.puts, []);
});
- test("a child process that echoes a secret or a token is filtered", async () => {
+ test("a child process that echoes a secret or a token is filtered, and the client secret is tried again", async () => {
const run = await connectFake({ failPut: "OIDC_CLIENT_SECRET" });
const keep = join(run.keepDir, "pairwise.txt");
const { code, result, out, err } = await run.connect([
@@ -642,6 +1041,7 @@ describe("gateweave connect id track", () => {
assert.equal(result.code, "client-secret-not-set");
assert.match(result.reason, /the body \[secret\] was sent with \[secret\] and \[secret\]/);
assert.match(result.reason, /DELETE FROM oauth_client/);
+ assert.equal(run.puts.filter(({ name }) => name === "OIDC_CLIENT_SECRET").length, 3);
assert.deepEqual(leaked(out), []);
assert.deepEqual(leaked(err), []);
const [connection] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections;
@@ -660,37 +1060,175 @@ describe("gateweave connect id track", () => {
assert.deepEqual(leaked(failed.err), []);
assert.ok(!existsSync(kept), "a value that was never set is not left to be kept");
assert.equal(pairwise.appsAdd.length, 0);
+ // The rerun makes a new value and finishes.
+ pairwise.state.failPut = undefined;
+ const rerun = await pairwise.connect(["--keep-secret-at", kept, "--yes", "--json"]);
+ assert.equal(rerun.code, 0, rerun.err);
+ assert.equal(pairwise.randomCalls(), 2);
+ });
+
+ test("a run cut short after the registration is finished by the next, without registering again", async () => {
+ const run = await connectFake({ failPut: "OIDC_ISSUER" });
+ const first = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(first.code, 8);
+ assert.equal(first.result.code, "secret-put-failed");
+ // The client id was on record before Track was given anything; no secret ever is.
+ const recorded = readFileSync(recordPath(run.fake.sys), "utf8");
+ const [connection] = JSON.parse(recorded).connections;
+ assert.equal(connection.clientId, CLIENT_ID);
+ assert.deepEqual(connection.steps, ["registered"]);
+ assert.deepEqual(leaked(recorded), []);
+
+ run.state.failPut = undefined;
+ const before = run.puts.length;
+ const second = await run.connect(["--yes", "--json"]);
+ assert.equal(second.code, 0, second.err);
+ assert.equal(second.result.registeredNow, false);
+ assert.equal(run.appsAdd.length, 1);
+ assert.equal(run.randomCalls(), 1);
+ assert.deepEqual(
+ run.puts.slice(before).map(({ name }) => name),
+ ["OIDC_ISSUER", "OIDC_PROVIDER_NAME", "BETTER_AUTH_URL"],
+ );
+ });
+
+ test("a second run while one is going is refused, and a lock left by an ended run is cleared", async () => {
+ const run = await connectFake();
+ const lock = join(configDir(run.fake.sys), LOCK);
+ mkdirSync(configDir(run.fake.sys), { recursive: true });
+ const live = JSON.stringify({ pid: process.pid, host: hostname(), startedAt: "now" });
+ writeFileSync(lock, live);
+ const busy = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(busy.code, 3);
+ assert.equal(busy.result.code, "run-in-progress");
+ assert.match(busy.result.reason, new RegExp(`process ${process.pid}`));
+ assert.deepEqual(run.newCalls(), []);
+ assert.equal(readFileSync(lock, "utf8"), live, "another run's lock stays");
+
+ const ended = spawnSync(process.execPath, ["-e", ""]).pid;
+ writeFileSync(lock, JSON.stringify({ pid: ended, host: hostname(), startedAt: "then" }));
+ const after = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(after.code, 0, after.err);
+ assert.ok(!existsSync(lock));
+ assert.deepEqual(
+ readdirSync(configDir(run.fake.sys)).filter((name) => name.includes(".lock")),
+ [],
+ );
+ });
+
+ test("an address with a name and password in it is refused without repeating it", async () => {
+ const run = await connectFake();
+ for (const args of [
+ ["--id-url", "https://admin:pa55word-zz@id.example.com"],
+ ["--track-url", "https://admin:pa55word-zz@bad host"],
+ ["--track-url", "https://track'example.com"],
+ ]) {
+ const { code, out, err } = await run.connect([...args, "--json"]);
+ assert.equal(code, 2, args.join(" "));
+ assert.ok(!`${out}${err}`.includes("pa55word-zz"));
+ }
+ run.fake.output.out = "";
+ assert.equal(
+ await main(["doctor", "track", "--url", "admin:pa55word-zz@x", "--json"], run.fake.sys),
+ 2,
+ );
+ assert.ok(!`${run.fake.output.out}${run.fake.output.err}`.includes("pa55word-zz"));
+ assert.deepEqual(run.newCalls(), []);
+ });
+
+ test("NODE_DEBUG stops every command before it starts anything", async () => {
+ const run = await connectFake();
+ run.fake.sys.env.NODE_DEBUG = "child_process";
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "node-debug-set");
+ assert.equal(await main(["doctor", "track"], run.fake.sys), 3);
+ assert.deepEqual(run.newCalls(), []);
});
- test("doctor reports the connection on both sides", async () => {
+ test("the record keeps only its known fields, whatever is handed to it", async () => {
+ const run = await connectFake();
+ await saveConnection(run.fake.sys, {
+ kind: "id-track",
+ accountId: "a1b2c3",
+ idWorker: "x-id",
+ trackWorker: "x-track",
+ issuer: ID,
+ trackAddress: TRACK,
+ providerName: "Gateweave ID",
+ clientId: CLIENT_ID,
+ steps: ["registered"],
+ updatedAt: "now",
+ clientSecret: CLIENT_SECRET,
+ pairwiseSecret: PAIRWISE,
+ } as ConnectionRecord);
+ const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8"));
+ const [deployment] = file.deployments;
+ await saveRecord(run.fake.sys, { ...deployment, worker: "y", secret: API_TOKEN });
+ const text = readFileSync(recordPath(run.fake.sys), "utf8");
+ assert.deepEqual(leaked(text), []);
+ assert.doesNotMatch(text, /clientSecret|pairwiseSecret|"secret"/);
+ });
+
+ test("doctor reports what it can see of the connection on both sides, and what it cannot", async () => {
const run = await connectFake();
assert.equal(
- (await run.connect(["--keep-secret-at", join(run.keepDir, "k"), "--yes"])).code,
+ (
+ await run.connect([
+ "--id-url",
+ "https://id.example.com",
+ "--track-url",
+ "https://track.example.com",
+ ...keepArgs(run, "k"),
+ "--yes",
+ ])
+ ).code,
0,
);
const findings = async (product: string) => {
run.fake.output.out = "";
+ run.fake.events.length = 0;
await main(["doctor", product, "--json"], run.fake.sys);
return JSON.parse(run.fake.output.out) as { id: string; status: string; message: string }[];
};
const track = (await findings("track")).find(({ id }) => id === "sign-in-provider");
+ // At the address the connection was made on, not only the deployment's.
+ assert.ok(run.fake.events.includes("fetch GET https://track.example.com/login"));
assert.equal(track?.status, "ok");
- assert.match(
- track?.message ?? "",
- new RegExp(
- `through ID gateweave-id \\(${ID.replaceAll(".", "\\.")}, client id ${CLIENT_ID}\\)`,
- ),
- );
+ assert.match(track?.message ?? "", /shows "Continue with Gateweave ID"/);
+ assert.match(track?.message ?? "", /Track names the issuer https:\/\/id\.example\.com/);
+ assert.match(track?.message ?? "", /a secret, which cannot be read back/);
+ assert.doesNotMatch(track?.message ?? "", /connected/);
const id = (await findings("id")).find(({ id: found }) => found === "oidc-provider");
+ assert.ok(
+ run.fake.events.includes("fetch GET https://id.example.com/.well-known/openid-configuration"),
+ );
assert.equal(id?.status, "ok");
+ assert.match(id?.message ?? "", /with the issuer https:\/\/id\.example\.com/);
assert.match(
id?.message ?? "",
- /with the issuer https:\/\/gateweave-id\.rehearsal\.workers\.dev/,
+ new RegExp(`Track gateweave-track is registered, as client id ${CLIENT_ID}`),
);
+
+ // ID's database has another client for Track: doctor id says so.
+ run.registrations.splice(0, 1, OTHER_CLIENT_ID);
+ const other = (await findings("id")).find(({ id: found }) => found === "oidc-provider");
+ assert.equal(other?.status, "fail");
assert.match(
- id?.message ?? "",
- new RegExp(`Track gateweave-track \\(client id ${CLIENT_ID}\\)`),
+ other?.message ?? "",
+ new RegExp(`registered as client id ${OTHER_CLIENT_ID}, not ${CLIENT_ID}`),
+ );
+ run.registrations.splice(0, 1, CLIENT_ID);
+
+ // Track names another issuer: doctor track says so.
+ run.values.set("gateweave-track OIDC_ISSUER", "https://other.example.com");
+ const moved = (await findings("track")).find(({ id: found }) => found === "sign-in-provider");
+ assert.equal(moved?.status, "fail");
+ assert.match(
+ moved?.message ?? "",
+ /names the issuer https:\/\/other\.example\.com, not https:\/\/id\.example\.com/,
);
+ run.values.set("gateweave-track OIDC_ISSUER", "https://id.example.com");
// Half a setup is a fail, with the command that finishes it.
run.fake.cloud.secrets.get("gateweave-track")?.delete("OIDC_CLIENT_SECRET");
@@ -709,6 +1247,7 @@ describe("gateweave connect id track", () => {
2,
);
assert.equal(await main(["doctor", "id", "--keep-secret-at", "x"], run.fake.sys), 2);
+ assert.equal(await main(["doctor", "id", "--no-account-name"], run.fake.sys), 2);
assert.deepEqual(run.newCalls(), []);
});
});
diff --git a/packages/cli/test/fake.ts b/packages/cli/test/fake.ts
index 4c8e612..3a91f82 100644
--- a/packages/cli/test/fake.ts
+++ b/packages/cli/test/fake.ts
@@ -380,6 +380,8 @@ const READ_ONLY = [
/npx-cli\.js --version$/,
/ wrangler@[\d.]+ whoami --json$/,
/ wrangler@[\d.]+ secret list --name \S+ --format json$/,
+ / wrangler@[\d.]+ deployments status --name \S+ --json$/,
+ / wrangler@[\d.]+ versions view \S+ --name \S+ --json$/,
/ wrangler@[\d.]+ d1 list --json$/,
/ wrangler@[\d.]+ d1 migrations list DB --remote$/,
/ wrangler@[\d.]+ d1 execute DB --remote --json --command SELECT [^;]*$/,
diff --git a/packages/cli/test/registration.test.ts b/packages/cli/test/registration.test.ts
new file mode 100644
index 0000000..13bd659
--- /dev/null
+++ b/packages/cli/test/registration.test.ts
@@ -0,0 +1,110 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ callbackUri,
+ readClientIds,
+ sqlString,
+ trackRegistrationSql,
+} from "../src/registration.ts";
+
+// The query runs on D1, which is SQLite. node:sqlite (Node 22.5 and later) runs the very text this
+// tool sends, against the columns of ID's oauth_client that it reads.
+type Database = {
+ exec(sql: string): void;
+ prepare(sql: string): { all(): unknown[] };
+};
+let open: (() => Database) | null = null;
+let missing = "";
+try {
+ const { DatabaseSync } = await import("node:sqlite");
+ open = () => new DatabaseSync(":memory:") as unknown as Database;
+} catch (error) {
+ missing = `node:sqlite is not in Node ${process.versions.node}: ${(error as Error).message}`;
+}
+
+/** The columns of ID's `oauth_client` (migrations/0001) the query reads, as ID declares them. */
+const SCHEMA = `CREATE TABLE oauth_client (
+ id text PRIMARY KEY NOT NULL,
+ client_id text NOT NULL,
+ redirect_uris text NOT NULL,
+ reference_id text,
+ metadata text
+)`;
+
+/** A row as ID's apps:add writes it: the URIs as a JSON list, the app id in the metadata. */
+function insert(
+ db: Database,
+ row: { clientId: string; uris: string[]; app?: string; workspace?: string; metadata?: string },
+) {
+ const metadata =
+ row.metadata ??
+ JSON.stringify(
+ row.workspace ? { app: row.clientId, workspace: row.workspace } : { app: row.app },
+ );
+ db.exec(
+ `INSERT INTO "oauth_client" ("id", "client_id", "redirect_uris", "reference_id", "metadata") VALUES (${[
+ sqlString(`row-${row.clientId}`),
+ sqlString(row.clientId),
+ sqlString(JSON.stringify(row.uris)),
+ row.workspace ? sqlString(row.workspace) : "NULL",
+ sqlString(metadata),
+ ].join(", ")});`,
+ );
+}
+
+function lookup(db: Database, trackAddress: string): string[] {
+ return db
+ .prepare(trackRegistrationSql(callbackUri(trackAddress)))
+ .all()
+ .map((row) => (row as { client_id: string }).client_id);
+}
+
+const TRACK = "https://track.example.com";
+
+test("the registration query finds Track's own row and nothing else", {
+ skip: open ? false : missing,
+}, () => {
+ const db = (open as () => Database)();
+ db.exec(SCHEMA);
+ // Nothing registered: nothing found.
+ assert.deepEqual(lookup(db, TRACK), []);
+ insert(db, { clientId: "track-client", app: "track", uris: [callbackUri(TRACK)] });
+ // Another first-party app with the same callback is not Track.
+ insert(db, { clientId: "other-app", app: "wiki", uris: [callbackUri(TRACK)] });
+ // A workspace's own app with the same callback is not Track either.
+ insert(db, { clientId: "workspace-app", workspace: "org-1", uris: [callbackUri(TRACK)] });
+ // A longer URI on the same host is another URI.
+ insert(db, {
+ clientId: "longer-uri",
+ app: "track",
+ uris: [`${callbackUri(TRACK)}/more`, `${TRACK}/api/auth/callback/oidcx`],
+ });
+ // A row whose metadata is not JSON is passed over, and does not fail the query.
+ insert(db, { clientId: "broken", uris: [callbackUri(TRACK)], metadata: "{not json" });
+ assert.deepEqual(lookup(db, TRACK), ["track-client"]);
+ // Another Track elsewhere is not this one.
+ assert.deepEqual(lookup(db, "https://track.other.example.com"), []);
+});
+
+test("the registration query takes an address with quotes as text", {
+ skip: open ? false : missing,
+}, () => {
+ const db = (open as () => Database)();
+ db.exec(SCHEMA);
+ const quoted = "https://it's.example.com";
+ insert(db, { clientId: "quoted", app: "track", uris: [callbackUri(quoted)] });
+ insert(db, { clientId: "plain", app: "track", uris: [callbackUri(TRACK)] });
+ assert.deepEqual(lookup(db, quoted), ["quoted"]);
+ // What would end the string and widen the query finds nothing, and changes nothing.
+ assert.deepEqual(lookup(db, "https://x') OR 1=1 OR ('"), []);
+ assert.deepEqual(lookup(db, `https://x'; DELETE FROM oauth_client; --`), []);
+ assert.deepEqual(lookup(db, TRACK), ["plain"]);
+});
+
+test("Wrangler's answer is read as client ids, or not at all", () => {
+ assert.deepEqual(readClientIds(JSON.stringify([{ results: [{ client_id: "a" }] }])), ["a"]);
+ assert.deepEqual(readClientIds(JSON.stringify([{ results: [] }])), []);
+ assert.equal(readClientIds("not json"), null);
+ assert.equal(readClientIds(JSON.stringify([{ success: true }])), null);
+ assert.equal(readClientIds(JSON.stringify([{ results: [{ client_id: 7 }] }])), null);
+});
diff --git a/packages/cli/test/system.test.ts b/packages/cli/test/system.test.ts
new file mode 100644
index 0000000..bf12e32
--- /dev/null
+++ b/packages/cli/test/system.test.ts
@@ -0,0 +1,61 @@
+import assert from "node:assert/strict";
+import { tmpdir } from "node:os";
+import { test } from "node:test";
+import { childEnv, realSystem } from "../src/system.ts";
+
+/** A tiny child that says what it was given: its arguments, its stdin and three settings. */
+const ECHO = `let input = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", (chunk) => { input += chunk; });
+process.stdin.on("end", () => {
+ process.stdout.write(JSON.stringify({
+ argv: process.argv.slice(1),
+ input,
+ debug: process.env.NODE_DEBUG ?? null,
+ sanitize: process.env.WRANGLER_LOG_SANITIZE ?? null,
+ kept: process.env.GATEWEAVE_TEST_KEPT ?? null,
+ }));
+});`;
+
+const SECRET = "a-secret-handed-on-stdin-0123456789";
+
+test("realSystem().run hands a value to the child on stdin, never as an argument", async () => {
+ const sys = realSystem();
+ const result = await sys.run(process.execPath, ["-e", ECHO, "--", "one"], {
+ cwd: tmpdir(),
+ env: { ...process.env, GATEWEAVE_TEST_KEPT: "yes" },
+ input: SECRET,
+ });
+ assert.equal(result.status, 0, result.stderr);
+ const seen = JSON.parse(result.stdout);
+ assert.equal(seen.input, SECRET);
+ assert.ok(!seen.argv.some((arg: string) => arg.includes(SECRET)), "not in the process list");
+ assert.deepEqual(seen.argv.slice(-1), ["one"]);
+ // Without a value, the child's stdin is closed: nothing it asks can be answered.
+ const none = JSON.parse(
+ (await sys.run(process.execPath, ["-e", ECHO], { cwd: tmpdir(), env: process.env })).stdout,
+ );
+ assert.equal(none.input, "");
+});
+
+test("a child starts without NODE_DEBUG and without WRANGLER_LOG_SANITIZE turned off", async () => {
+ const sys = realSystem();
+ const result = await sys.run(process.execPath, ["-e", ECHO], {
+ cwd: tmpdir(),
+ env: {
+ ...process.env,
+ NODE_DEBUG: "gateweave-test-nothing",
+ WRANGLER_LOG_SANITIZE: "false",
+ GATEWEAVE_TEST_KEPT: "yes",
+ },
+ input: "",
+ });
+ const seen = JSON.parse(result.stdout);
+ assert.equal(seen.debug, null);
+ assert.equal(seen.sanitize, null);
+ assert.equal(seen.kept, "yes");
+ // In any case: Windows does not tell names apart by case.
+ assert.deepEqual(childEnv({ node_debug: "x", Wrangler_Log_Sanitize: "false", PATH: "p" }), {
+ PATH: "p",
+ });
+});
From 75ced985de4e884ecb60ea2c9b82afff54aa7646 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:09:15 +0100
Subject: [PATCH 04/14] docs(cli): what connect proves, what a rerun does, and
the workers.dev limit
---
packages/cli/README.md | 137 +++++++++++++++++++++++++++--------------
1 file changed, 91 insertions(+), 46 deletions(-)
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 2d71203..0779655 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -30,81 +30,126 @@ See the [repository](https://github.com/gateweavehq/cli) for what the commands d
```
gateweave connect id track [--id-url ] [--track-url ] [--keep-secret-at ]
- [--id-name ] [--track-name ] [--account ] [--yes] [--json]
+ [--id-name ] [--track-name ] [--account ]
+ [--no-account-name] [--yes] [--json]
```
Connects a Track deployment to an ID deployment, so Track signs people in through ID. Both must be
-deployments this tool made and recorded (`gateweave deploy id`, `gateweave deploy track`). With
-several of one product in the account, choose with `--id-name` or `--track-name`. `--id-url` and
-`--track-url` replace the recorded addresses, such as a Custom Domain you added since.
-
-1. **Looks, changing nothing:** the secrets each Worker has (by name), whether ID's
- `/.well-known/openid-configuration` answers and with which issuer, whether Track's sign-in page
- already shows a provider, and whether Track is already registered with ID, with one fixed
- `SELECT` on ID's database.
-2. **Shows the plan and waits for a yes:** both deployments and their addresses, and every setting
- by name, each marked `set now` or `already set; left as it is`. `--yes` answers for you; without
- a terminal and without `--yes` it stops at once.
+on this tool's record (`gateweave deploy id`, `gateweave deploy track`). With several of one product
+in the account, choose with `--id-name` or `--track-name`. A deployment that `gateweave update`
+recorded without having made it is used only when named that way, never picked on its own.
+`--id-url` and `--track-url` replace the recorded addresses, such as a Custom Domain you added since.
+`--no-account-name` keeps the Cloudflare account's name out of the plan, the errors and `--json`,
+which then name the account by its id.
+
+1. **Looks, changing nothing.** For each Worker: its secrets (`secret list`), and every binding of
+ its deployed version (`deployments status`, `versions view`), so a setting kept as a text
+ variable in `vars` counts as set too, and its compatibility flags. Then ID's
+ `/.well-known/openid-configuration`, ID's D1 database by name, and whether Track is already
+ registered with ID, with one fixed `SELECT` on that database. A look that fails, listings that
+ disagree, or a deployment split across versions stop the run with exit 3: a setting this tool
+ could not see is never taken for one that is not there.
+2. **Shows the plan and waits for a yes:** both deployments and their addresses, ID's database by
+ name and id, and every setting by name, each marked `set now`, `already set; left as it is` or
+ `already set as a text variable; left as it is`. `--yes` answers for you; without a terminal and
+ without `--yes` it stops at once.
3. **On ID:** sets `BETTER_AUTH_URL` to ID's address if it is unset, and `OIDC_PAIRWISE_SECRET` if it
is unset, to 48 random bytes in base64, made here.
-4. **Registers Track with ID's own `apps:add`**, from ID's release in your cache folder, against the
- deployed database: app `track`, redirect URI `/api/auth/callback/oidc` and back-channel
- logout URI `/api/auth/backchannel-logout/oidc`. Its output stays in memory; the command
- reads the client id and secret from its `client id:` and `client secret:` lines, and if the
- output has another form it stops and shows none of it.
+4. **Registers Track with ID's own `apps:add`**, from ID's release in your cache folder, in ID's
+ database: app `track`, redirect URI `/api/auth/callback/oidc` and back-channel logout URI
+ `/api/auth/backchannel-logout/oidc`. Its output stays in memory. It is read only when it is
+ exactly the three lines `apps:add` prints, with a client id and a secret of the shapes ID makes;
+ anything else stops the run, and no part of the output is shown, whatever the exit code.
5. **On Track:** sets `OIDC_CLIENT_SECRET`, `OIDC_CLIENT_ID`, `OIDC_ISSUER` and `OIDC_PROVIDER_NAME`
(`Gateweave ID`), and `BETTER_AUTH_URL` if it is unset, which also turns MCP on.
-6. **Checks:** ID's discovery answers with the issuer, Track's sign-in page shows "Continue with
- Gateweave ID", and the findings `doctor id` (`oidc-provider`) and `doctor track`
+6. **Checks:** ID's discovery answers with the issuer, Track's sign-in page shows the button with the
+ exact provider name, and the findings `doctor id` (`oidc-provider`) and `doctor track`
(`sign-in-provider`) report for the connection are all `ok`.
Every value goes to `wrangler secret put` on stdin, never as an argument. A setting that is already
-set is left alone, so a second run registers nothing again and replaces no secret; it only checks.
-If ID already has Track registered but Track's `OIDC_CLIENT_SECRET` is not set (a run cut short in
-between), the command stops and says how to recover, because ID shows a client secret once and keeps
-only its hash. If Track already has a client of another provider, it stops and changes nothing.
+set, as a secret or as a text variable, is left alone and never replaced. A text variable's value
+is used where it matters: ID's `BETTER_AUTH_URL` names the issuer, and Track's `OIDC_PROVIDER_NAME`
+is the button the check looks for. A secret cannot be read back, so the command stops where it
+would have to guess one: Track's `OIDC_PROVIDER_NAME` set as a secret by someone else, or a client
+id on record that differs from the one ID has registered for Track. Each stop says what to do, and
+changes nothing.
+
+Only one run at a time: a run takes the lock file `connect-id-track.lock` beside the record, and a
+second run stops while it is there. A lock left by a run that ended without removing it (its
+process is gone, or it is hours old) is cleared by the next run.
**The issuer cannot change.** ID's `BETTER_AUTH_URL` becomes the issuer that apps compare, and
passkeys are bound to it for good. Once any app has signed anyone in, it can never change. Choose
the address people will always use before you run this: give ID a Custom Domain first and pass it
with `--id-url`.
-**`workers.dev` has a limit.** Two Workers on `workers.dev` cannot reach each other unless each has
-`global_fetch_strictly_public` in its `compatibility_flags`. Until then Track's sign-in through ID
-fails with Cloudflare's error 1042, and ID's back-channel logout cannot reach Track. A
+**`workers.dev` has a limit.** A Worker reaches another Worker's `workers.dev` address only when
+the calling Worker has `global_fetch_strictly_public` in its `compatibility_flags`. Track has it, so
+Track's calls to ID, the sign-in, work. ID does not, so ID's back-channel logout cannot reach Track
+on `workers.dev`: signing out of ID does not end Track's sessions. The plan reads both Workers'
+flags and warns about the one that lacks it. A
[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) on
-each Worker is the setup that works. The plan warns about both whenever an address is on
-`workers.dev`.
+Track, or on both, is the setup that works.
**What to keep, and where.** `OIDC_PAIRWISE_SECRET` is the one value you must keep: it gives each app
its own id for each person, and losing or changing it gives everybody a new id in every app.
Cloudflare cannot show a secret back. When this run makes it:
-- with `--keep-secret-at `, it is written to that new file (mode 600 where the system has file
- modes) before it is set on ID. The path must be outside the folder you run the command from, and
- the file must not exist yet. Move the value into your password manager.
-- without it, it is shown once on the terminal, with words to keep it. With `--json`, or without a
- terminal, the command refuses instead and asks for `--keep-secret-at`, so the value never lands
- in JSON or a log.
+- with `--keep-secret-at `, it is written to that new file, readable by its owner alone where
+ the system has file modes, before it is set on ID. The path must be outside the folder you run the
+ command from, and the file must not exist yet. Both are checked for the plan and again when the
+ file is opened: it is made new, never through a link in its last part, and then looked for where
+ its folder really leads, so a folder changed in between cannot carry the value into the working
+ directory. Move the value into your password manager.
+- without it, it is shown once on the terminal, with words to keep it, before it is set on ID. With
+ `--json`, or without a terminal, the command refuses instead and asks for `--keep-secret-at`, so
+ the value never lands in JSON or a log.
+
+When ID already has `OIDC_PAIRWISE_SECRET`, nothing is made: `--json` and a run without a terminal
+need no `--keep-secret-at`, and a `--keep-secret-at` given anyway is not used, so a rerun with the
+same path, whose file the first run wrote, works.
Nothing else needs keeping. The client secret goes from `apps:add` to Track and is never shown. No
secret, token or Wrangler sign-in is printed, logged, written to the record, to the working
directory or to the system's temporary folder; the generated and captured values join the output
-filter, so even a child process that echoes one shows `[secret]`. The record keeps which Track
-is connected to which ID, the issuer and the client id.
+filter, so even a child process that echoes one shows `[secret]`. Every program this tool starts
+gets its environment without `NODE_DEBUG` and without `WRANGLER_LOG_SANITIZE`, so Wrangler keeps
+its log sanitised; and since Node prints what it hands a child once `NODE_DEBUG` asks for it, every
+command stops at once while `NODE_DEBUG` is set. The record keeps which Track is connected to which
+ID, the address and issuer, the provider name and the client id, and no field for a secret.
+
+**A run cut short, and what the next run does.** Each run looks again before it changes anything,
+so running the same command again is the way to finish:
+
+| Where it stopped | What the next run does |
+| ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Before the yes | Starts over; nothing was changed. |
+| Setting ID's `BETTER_AUTH_URL` | Sets it. |
+| Writing the keep file, or setting the pairwise secret | Nothing was set on ID, and a keep file that held the unset value is removed; it makes a new value. A put that Cloudflare took although Wrangler failed counts as set. |
+| ID's discovery not answering yet | Leaves ID's settings alone and registers Track once discovery answers. |
+| `apps:add` failing before it registered | Registers Track. |
+| After `apps:add` registered, before Track had the secret (output unreadable, or three failed tries to set it) | Stops and says how to recover: set the secret yourself if you have it, or remove the registration and Track's OIDC settings; then the run after registers anew. |
+| Setting Track's other settings | The client id is on record before Track is given anything, and ID has the registration: it sets what is missing and registers nothing again. |
+| The checks | Changes nothing and checks again. |
+
+`gateweave doctor track` and `gateweave doctor id` report the connection at the addresses it was made
+on. Doctor track says what it can see from outside: the button by its exact name, and the issuer
+Track names in its sign-in page's Content-Security-Policy. The client id Track holds is a secret it
+cannot read, and it says so. Doctor id reads ID's database and says whether Track is still
+registered with the client id this tool gave it.
With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`.
-| Exit code | Meaning |
-| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 0 | Connected, or already connected, and every check passed |
-| 1 | Something unexpected; the reason says what |
-| 2 | Wrong usage: an unknown option, an address that is not `https://`, a `--keep-secret-at` inside the working directory or already there, or none given where it is needed |
-| 3 | A requirement is missing: a deployment not recorded, a Worker gone, a list it could not read, an issuer other than the one given, Track registered without its secret, or Track with another provider |
-| 4 | The account: several to choose from, or the one named is not reachable |
-| 7 | No yes: declined, or no terminal and no `--yes`; nothing was changed |
-| 8 | Setting a secret, installing ID's release or its `apps:add` failed; the reason says what to do |
-| 9 | Connected, but a check failed, or ID's discovery did not answer before registering |
+| Exit code | Meaning |
+| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 0 | Connected, or already connected, and every check passed |
+| 1 | Something unexpected; the reason says what |
+| 2 | Wrong usage: an unknown option, an address that is not `https://`, an external deployment not named, a `--keep-secret-at` inside the working directory, already there or moved, or none given where it is needed |
+| 3 | A requirement is missing: a deployment not recorded, a Worker or database gone, a look that failed, another run going, `NODE_DEBUG` set, an issuer other than the one given, a setting it cannot read, Track registered without its secret, or Track with another provider |
+| 4 | The account: several to choose from, or the one named is not reachable |
+| 7 | No yes: declined, or no terminal and no `--yes`; nothing was changed |
+| 8 | Setting a secret, installing ID's release or its `apps:add` failed; the reason says what to do |
+| 9 | Connected, but a check failed, or ID's discovery did not answer before registering |
## License
From 4292f128405e335c2d7884d2d4050bd255d27d63 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:10:31 +0100
Subject: [PATCH 05/14] test(cli): doctor track looks for ID's button by its
exact name
---
packages/cli/test/connect-id-track.test.ts | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index 53a651d..5616957 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -1230,6 +1230,13 @@ describe("gateweave connect id track", () => {
);
run.values.set("gateweave-track OIDC_ISSUER", "https://id.example.com");
+ // A button with another name is not ID's.
+ run.values.set("gateweave-track OIDC_PROVIDER_NAME", "Someone Else");
+ const renamed = (await findings("track")).find(({ id: found }) => found === "sign-in-provider");
+ assert.equal(renamed?.status, "fail");
+ assert.match(renamed?.message ?? "", /shows no "Continue with Gateweave ID" button/);
+ run.values.set("gateweave-track OIDC_PROVIDER_NAME", "Gateweave ID");
+
// Half a setup is a fail, with the command that finishes it.
run.fake.cloud.secrets.get("gateweave-track")?.delete("OIDC_CLIENT_SECRET");
const half = (await findings("track")).find(({ id: found }) => found === "sign-in-provider");
From 0d5493eaf51d6d27030625ca509211b5b9b466b5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:48:37 +0100
Subject: [PATCH 06/14] fix(cli): connect never guesses what a failed look or a
foreign setting means
- Once the pairwise put was tried, the keep file is never removed. A put
that failed with a listing that failed too is reported as unknown: the
value may be set, keep the file and run again.
- A lock that is there is never cleared, whatever its age. The run stops
with its path, the holder's pid and start time, and whether that pid is
alive on this machine.
- Track's OIDC_CLIENT_ID or OIDC_ISSUER that the record does not show this
tool set stops the run before any change, with the recovery steps. The
record names each Track setting this tool set, before it is put, and
doctor says "this tool gave it" only from that.
- A text OIDC_ISSUER is compared whole with the issuer, path included.
- Every message strips a name and password from any address in it, read
or given, through one helper.
- Each workers.dev warning speaks only for its own direction.
- Button names are compared with HTML character references decoded.
- apps:add output is matched as captured, line endings aside; only the
secret's own prefix is refused as a client id.
- The keep file is written in the folder the plan checked, or nowhere.
- A printed rerun repeats the names and addresses given.
- The client-secret-not-set stop says the registration needs cleaning up.
---
packages/cli/src/checks.ts | 17 +-
packages/cli/src/connect.ts | 164 +++++++---
packages/cli/src/deploy-track.ts | 11 +-
packages/cli/src/doctor-track.ts | 6 +-
packages/cli/src/lock.ts | 99 +++---
packages/cli/src/main.ts | 18 +-
packages/cli/src/record.ts | 6 +
packages/cli/test/connect-id-track.test.ts | 360 +++++++++++++++++++--
8 files changed, 546 insertions(+), 135 deletions(-)
diff --git a/packages/cli/src/checks.ts b/packages/cli/src/checks.ts
index 52f09f0..d7ac2a6 100644
--- a/packages/cli/src/checks.ts
+++ b/packages/cli/src/checks.ts
@@ -164,6 +164,21 @@ export async function discoveredIssuer(sys: System, address: string): Promise = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
+
+/**
+ * Text as the page shows it: HTML's character references decoded, by name for the five a page
+ * escapes text with, and by number. "Acme & Co" reads "Acme & Co". One pass, so "<"
+ * is "<", as a browser shows it.
+ */
+export function decodeEntities(text: string): string {
+ return text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|([a-zA-Z]+));/g, (whole, dec, hex, name) => {
+ if (name !== undefined) return ENTITIES[name] ?? whole;
+ const code = Number.parseInt(dec ?? hex, dec !== undefined ? 10 : 16);
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
+ });
+}
+
/**
* The names on the provider buttons of Track's sign-in page, other than GitHub's. Track shows its
* OpenID Connect button only while OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are all set.
@@ -174,7 +189,7 @@ export async function providerButtons(sys: System, address: string): Promise \s*Continue with ([^<]+?)\s* match[1] ?? "")
+ .map((match) => decodeEntities(match[1] ?? ""))
.filter((name) => name !== "" && name !== "GitHub");
} catch {
return null;
diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts
index ab19cbe..d783f24 100644
--- a/packages/cli/src/connect.ts
+++ b/packages/cli/src/connect.ts
@@ -3,7 +3,15 @@ import { constants, type Stats } from "node:fs";
import { access, type FileHandle, lstat, mkdir, open, realpath, rm } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { type CheckResult, discoveredIssuer, ID_PROVIDER_NAME, providerButtons } from "./checks.ts";
-import { type Account, chooseAccount, confirm, json, outputGuard, plain } from "./deploy-track.ts";
+import {
+ type Account,
+ chooseAccount,
+ confirm,
+ json,
+ outputGuard,
+ plain,
+ withoutCredentials,
+} from "./deploy-track.ts";
import {
databaseId,
ensureCheckout,
@@ -146,12 +154,18 @@ function inside(base: string, target: string): boolean {
* be committed with a project, in a folder that exists, and new: a kept secret is never overwritten.
* Checked here for the plan, and again where it is opened.
*/
-async function keepPath(sys: System, given: string): Promise {
+interface KeepPath {
+ path: string;
+ /** Where its folder really was when the plan was shown. The file is written there or nowhere. */
+ folder: string;
+}
+
+async function keepPath(sys: System, given: string): Promise {
const cwd = resolve(sys.cwd ?? process.cwd());
const path = resolve(cwd, given);
- let real: string;
+ let folder: string;
try {
- real = join(await realpath(dirname(path)), basename(path));
+ folder = await realpath(dirname(path));
} catch {
throw new CliError(
"usage",
@@ -160,7 +174,7 @@ async function keepPath(sys: System, given: string): Promise {
);
}
const realCwd = await realpath(cwd).catch(() => cwd);
- if (inside(cwd, path) || inside(realCwd, real)) {
+ if (inside(cwd, path) || inside(realCwd, folder)) {
throw new CliError(
"usage",
"keep-path-inside",
@@ -178,7 +192,7 @@ async function keepPath(sys: System, given: string): Promise {
`${path} already exists. This tool never overwrites a file that may hold a kept secret; choose a new path.`,
);
}
- return path;
+ return { path, folder };
}
const sameFile = (a: Stats, b: Stats) => a.ino === b.ino && a.dev === b.dev;
@@ -186,10 +200,12 @@ const sameFile = (a: Stats, b: Stats) => a.ino === b.ino && a.dev === b.dev;
/**
* Writes the value a person is to keep. The file is made new (never through a link in its last
* part, never over a file), readable by its owner alone; then, opened, it is looked for again
- * where its folder really is now, so a folder changed since the plan cannot carry it into the
- * working directory unseen. Nothing is written until that holds.
+ * where its folder really is now. That must be the folder the plan checked: a link in the path
+ * retargeted since, into the working directory or anywhere else, is refused, and nothing is
+ * written in the new place.
*/
-async function writeKept(sys: System, path: string, value: string): Promise {
+async function writeKept(sys: System, keep: KeepPath, value: string): Promise {
+ const { path } = keep;
const cwd = resolve(sys.cwd ?? process.cwd());
const realCwd = await realpath(cwd).catch(() => cwd);
const flags =
@@ -218,11 +234,11 @@ async function writeKept(sys: System, path: string, value: string): Promise {
- const say = (line = "") => sys.err(`${line}\n`);
+ const say = (line = "") => sys.err(`${withoutCredentials(line)}\n`);
+ // The command to run again: with the names and addresses given, as a bare rerun would not
+ // pick an external deployment or the same addresses.
+ const rerun = `\`${[
+ "gateweave connect id track",
+ ...(options.account ? ["--account", options.account] : []),
+ ...(options.idName ? ["--id-name", options.idName] : []),
+ ...(options.trackName ? ["--track-name", options.trackName] : []),
+ ...(idGiven ? ["--id-url", idGiven] : []),
+ ...(trackGiven ? ["--track-url", trackGiven] : []),
+ ...(options.accountName ? [] : ["--no-account-name"]),
+ ].join(" ")}\``;
const npx = npxCli(sys);
const cache = cacheDir(sys);
await mkdir(cache, { recursive: true });
@@ -683,9 +710,9 @@ async function connect(
: `npx wrangler@${trackPins.wrangler} secret delete ${name} --name ${trackRecord.worker}`;
/** The steps that start the connection again from nothing, ending in a run that works. */
const startAgain = (clientId: string, onTrack: readonly string[]) =>
- `remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = ${sqlString(clientId)}"${onTrack.length ? `; remove ${onTrack.join(", ")} from Track: ${onTrack.map(deleteOnTrack).join("; ")}` : ""}; then run \`gateweave connect id track\` again, which registers Track anew.`;
+ `remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = ${sqlString(clientId)}"${onTrack.length ? `; remove ${onTrack.join(", ")} from Track: ${onTrack.map(deleteOnTrack).join("; ")}` : ""}; then run ${rerun} again, which registers Track anew.`;
const recovery = (clientId: string, onTrack: readonly string[]) =>
- `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track (npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker}, which asks for the value) and run \`gateweave connect id track\` again. If not, ${startAgain(clientId, onTrack)}`;
+ `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track (npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker}, which asks for the value) and run ${rerun} again. If not, ${startAgain(clientId, onTrack)}`;
if (registered.length > 1) {
throw new CliError(
@@ -708,13 +735,14 @@ async function connect(
// a text variable shows its value. A secret cannot be read, so a record that disagrees stops.
const idText = textOf(trackDeployed, "OIDC_CLIENT_ID");
const issuerText = textOf(trackDeployed, "OIDC_ISSUER");
+ const wantedIssuer = issuerBefore ?? idAddress;
const differs =
previous?.clientId && previous.clientId !== existingClient
? `this tool gave Track the client id ${previous.clientId}, as its record says`
: idText !== undefined && idText !== existingClient
? `Track's OIDC_CLIENT_ID is ${idText}`
- : issuerText !== undefined && originOrNull(issuerText) !== idAddress
- ? `Track's OIDC_ISSUER is ${issuerText}, not ${idAddress}`
+ : issuerText !== undefined && issuerText !== wantedIssuer
+ ? `Track's OIDC_ISSUER is ${issuerText}, not ${wantedIssuer}`
: null;
if (differs) {
throw new CliError(
@@ -723,6 +751,20 @@ async function connect(
`ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but ${differs}. Which client Track signs in with cannot be told, so nothing is changed. To start again, ${startAgain(existingClient, trackHeld)}`,
);
}
+ // OIDC_CLIENT_ID or OIDC_ISSUER that this tool did not set, as its record shows, may name
+ // another client: a setting that cannot be read is not taken for this registration's.
+ const notOurs = trackHeld.filter(
+ (name) =>
+ name !== "OIDC_CLIENT_SECRET" &&
+ !(previous?.clientId === existingClient && previous.trackSet?.includes(name)),
+ );
+ if (notOurs.length > 0) {
+ throw new CliError(
+ "requirement",
+ "track-settings-not-ours",
+ `ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but Track already had ${notOurs.join(" and ")} before this tool set ${notOurs.length === 1 ? "it" : "them"}, so which client Track signs in with cannot be told. Nothing was changed. To start again, ${startAgain(existingClient, trackHeld)}`,
+ );
+ }
}
const register = existingClient === null;
if (register) {
@@ -730,7 +772,7 @@ async function connect(
throw new CliError(
"requirement",
"track-has-provider",
- `Track ${trackRecord.worker} already has ${trackHeld.join(", ")} set, but ID ${idRecord.worker} has no app registered as Track for ${redirectUri}: Track signs in through another provider, or its registration was removed. This tool replaces no setting. To connect it to ID instead, remove those first (${trackHeld.map(deleteOnTrack).join("; ")}), then run it again. Nothing was changed.`,
+ `Track ${trackRecord.worker} already has ${trackHeld.join(", ")} set, but ID ${idRecord.worker} has no app registered as Track for ${redirectUri}: Track signs in through another provider, or its registration was removed. This tool replaces no setting. To connect it to ID instead, remove those first (${trackHeld.map(deleteOnTrack).join("; ")}), then run ${rerun} again. Nothing was changed.`,
);
}
if (!stripsTypes(sys.nodeVersion)) {
@@ -762,7 +804,7 @@ async function connect(
throw new CliError(
"requirement",
"provider-name-unknown",
- `Track's OIDC_PROVIDER_NAME is set as a secret this tool did not set, and a secret cannot be read back, so the check that Track's sign-in page shows ID's button could not be made. Remove it (${deleteOnTrack("OIDC_PROVIDER_NAME")}) to have this tool set it to "${ID_PROVIDER_NAME}", or make it a text variable in Track's configuration; then run again. Nothing was changed.`,
+ `Track's OIDC_PROVIDER_NAME is set as a secret this tool did not set, and a secret cannot be read back, so the check that Track's sign-in page shows ID's button could not be made. Remove it (${deleteOnTrack("OIDC_PROVIDER_NAME")}) to have this tool set it to "${ID_PROVIDER_NAME}", or make it a text variable in Track's configuration; then run ${rerun} again. Nothing was changed.`,
);
}
@@ -794,7 +836,7 @@ async function connect(
worker: idRecord.worker,
name: PAIRWISE,
value: keepAt
- ? `generated here, kept at ${keepAt}, never shown`
+ ? `generated here, kept at ${keepAt.path}, never shown`
: "generated here and shown once on this terminal, before it is set, for you to keep",
held: held(idDeployed, PAIRWISE),
},
@@ -864,6 +906,8 @@ async function connect(
}
// A Worker reaches another on workers.dev only with this flag, and it is the calling Worker's
// that counts: Track calls ID to sign people in, and ID calls Track to sign them out.
+ // Each direction is told from its own Worker's flag alone, so one warning never speaks for the
+ // other direction.
const customDomains =
"https://developers.cloudflare.com/workers/configuration/routing/custom-domains/";
if (onWorkersDev(idAddress) && !trackDeployed.flags.includes(STRICTLY_PUBLIC)) {
@@ -873,7 +917,7 @@ async function connect(
}
if (onWorkersDev(trackAddress) && !idDeployed.flags.includes(STRICTLY_PUBLIC)) {
warnings.push(
- `ID (${idRecord.worker}) does not have ${STRICTLY_PUBLIC} in its compatibility_flags, so its back-channel logout cannot reach Track on workers.dev: signing out of ID does not end Track's sessions. Sign-in works, as there Track calls ID. A Custom Domain on Track is the setup that works: ${customDomains}`,
+ `ID (${idRecord.worker}) does not have ${STRICTLY_PUBLIC} in its compatibility_flags, so its back-channel logout cannot reach Track on workers.dev: signing out of ID does not end Track's sessions. A Custom Domain on Track is the setup that works: ${customDomains}`,
);
}
@@ -918,6 +962,11 @@ async function connect(
// "checked" is earned again by this run's own checks.
let steps: ConnectionStep[] = (previous?.steps ?? []).filter((step) => step !== "checked");
+ // The Track settings this tool set, for this client: what doctor may say this tool gave Track.
+ let trackSet: string[] =
+ existingClient !== null && previous?.clientId === existingClient
+ ? (previous.trackSet ?? [])
+ : [];
let clientId = existingClient;
const save = async () => {
try {
@@ -930,6 +979,7 @@ async function connect(
trackAddress,
providerName,
clientId,
+ trackSet,
steps,
updatedAt: new Date(sys.now()).toISOString(),
});
@@ -956,6 +1006,8 @@ async function connect(
let generatedNow = false;
let shownOnTerminal = false;
let keptAt: string | null = null;
+ /** A record save that failed after ID registered Track; it is tried again at the end. */
+ let recordFailure: CliError | null = null;
let issuer = idAddress;
const put = async (
@@ -972,23 +1024,39 @@ async function connect(
detail: hide(lastLine(result.stderr) || lastLine(result.stdout) || `exit ${result.status}`),
};
};
- /** A failed put can come after Cloudflare took the value; then the value is set. */
- const listedNow = (wrangler: ReturnType, worker: string, name: string) =>
+ /**
+ * Whether a setting is on the Worker now: true, false, or null when the listing failed. A put
+ * whose answer was lost may still have been taken, so a failed listing proves nothing either way.
+ */
+ const listedNow = (
+ wrangler: ReturnType,
+ worker: string,
+ name: string,
+ ): Promise =>
listSecrets(wrangler, worker).then(
(names) => names.has(name),
- () => false,
+ () => null,
);
const putOrStop = async (
item: Planned,
wrangler: ReturnType,
value: string,
) => {
+ if (item.product === "track") {
+ // On record before it is tried: a put whose answer is lost may still have set it, and
+ // what Track then holds under this name is this run's value.
+ trackSet = [...new Set([...trackSet, item.name])];
+ recordFailure = await save().then(
+ () => null,
+ (error: CliError) => error,
+ );
+ }
const { done, detail } = await put(wrangler, item.worker, item.name, value);
- if (!done && !(await listedNow(wrangler, item.worker, item.name))) {
+ if (!done && (await listedNow(wrangler, item.worker, item.name)) !== true) {
throw new CliError(
"deploy-failed",
"secret-put-failed",
- `Could not set ${item.name} on ${item.worker}: ${detail}. Run the command again to finish; what is set stays, and nothing is registered twice.`,
+ `Could not set ${item.name} on ${item.worker}: ${detail}. Run ${rerun} to finish; what is set stays, and nothing is registered twice.`,
);
}
say(` set ${item.name} on ${item.worker}`);
@@ -1019,21 +1087,29 @@ async function connect(
say(` ${value}`);
say();
}
- let { done, detail } = await put(idWrangler, idRecord.worker, PAIRWISE, value);
- if (!done) done = await listedNow(idWrangler, idRecord.worker, PAIRWISE);
- if (!done) {
- if (keepAt) await rm(keepAt, { force: true });
+ // From here the file is never removed: once a put was tried, the value may be on ID.
+ const kept = keepAt ? keepAt.path : "the value shown above";
+ const { done, detail } = await put(idWrangler, idRecord.worker, PAIRWISE, value);
+ const listed = done ? true : await listedNow(idWrangler, idRecord.worker, PAIRWISE);
+ if (listed === null) {
+ throw new CliError(
+ "deploy-failed",
+ "secret-put-unknown",
+ `Setting ${PAIRWISE} on ${idRecord.worker} failed (${detail}), and listing its secrets afterwards failed too, so whether ID has the value is unknown: it may be set. Keep ${kept}, and run ${rerun}: it looks again, and makes no new value if ID has this one.`,
+ );
+ }
+ if (!listed) {
throw new CliError(
"deploy-failed",
"secret-put-failed",
- `Could not set ${PAIRWISE} on ${idRecord.worker}: ${detail}. ${keepAt ? `${keepAt} was removed again, as it held a value that was never set. ` : "The value shown above was never set: do not keep it. "}Run the command again; it makes a new one.`,
+ `Could not set ${PAIRWISE} on ${idRecord.worker}: ${detail}. ID's list of secrets shows it is not set, so ${kept} holds a value ID does not have. ${keepAt ? `This tool does not remove it; delete it yourself, and run ${rerun} with a new --keep-secret-at path.` : `Do not keep it, and run ${rerun}.`} The next run makes a new one.`,
);
}
say(` set ${PAIRWISE} on ${idRecord.worker}`);
if (keepAt) {
- keptAt = keepAt;
+ keptAt = keepAt.path;
say(
- ` Keep ${keepAt}: it holds ${PAIRWISE}, the one value of this connection you must keep. Move it into your password manager. Losing or changing it gives everyone a new id in every app, and Cloudflare cannot show it again.`,
+ ` Keep ${keepAt.path}: it holds ${PAIRWISE}, the one value of this connection you must keep. Move it into your password manager. Losing or changing it gives everyone a new id in every app, and Cloudflare cannot show it again.`,
);
} else {
say(` The value shown above is set on ID now; it is the one to keep.`);
@@ -1050,7 +1126,7 @@ async function connect(
throw new CliError(
"checks-failed",
"provider-off",
- `ID's settings are set, but ${idAddress}/.well-known/openid-configuration does not answer, so Track was not registered. Wait a minute and run the command again.`,
+ `ID's settings are set, but ${idAddress}/.well-known/openid-configuration does not answer, so Track was not registered. Wait a minute and run ${rerun} again.`,
);
}
if (discovered !== idAddress) {
@@ -1063,7 +1139,6 @@ async function connect(
issuer = discovered;
let clientSecret: string | null = null;
- let recordFailure: CliError | null = null;
if (register) {
const install = await sys.run(
sys.execPath,
@@ -1113,12 +1188,12 @@ async function connect(
throw new CliError(
"deploy-failed",
"register-failed",
- `ID's apps:add stopped (exit ${added.status}), and Track was given nothing. What it printed is not shown, as it may hold the client secret. ${where} Then run this again: it first looks whether Track was registered.`,
+ `ID's apps:add stopped (exit ${added.status}), and Track was given nothing. What it printed is not shown, as it may hold the client secret. ${where} Then run ${rerun} again: it first looks whether Track was registered.`,
);
}
- const output = APPS_ADD_OUTPUT.exec(plain(added.stdout).replace(/\r\n/g, "\n"));
+ const output = APPS_ADD_OUTPUT.exec(added.stdout.replace(/\r\n/g, "\n"));
const [, givenId, givenSecret] = output ?? [];
- if (!givenId || !givenSecret || givenId.startsWith("gwid_")) {
+ if (!givenId || !givenSecret || givenId.startsWith("gwid_cs_")) {
throw new CliError(
"deploy-failed",
"register-output-unreadable",
@@ -1150,21 +1225,24 @@ async function connect(
if (item.name === "OIDC_CLIENT_SECRET") {
if (clientSecret === null) throw new Error("no client secret");
// First, and tried again: it lives only in this run's memory until Track has it.
- let done = false;
+ let listed: boolean | null = false;
let detail = "";
- for (let attempt = 0; attempt < 3 && !done; attempt++) {
+ for (let attempt = 0; attempt < 3 && listed !== true; attempt++) {
if (attempt > 0) await sys.sleep(5_000);
- ({ done, detail } = await put(trackWrangler, item.worker, item.name, clientSecret));
- if (!done) done = await listedNow(trackWrangler, item.worker, item.name);
+ const tried = await put(trackWrangler, item.worker, item.name, clientSecret);
+ detail = tried.detail;
+ listed = tried.done ? true : await listedNow(trackWrangler, item.worker, item.name);
}
- if (!done) {
+ if (listed !== true) {
+ // The secret lived only in this run's memory, so the registration it belongs to has to go.
throw new CliError(
"deploy-failed",
"client-secret-not-set",
- `Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker}: ${detail}. ${recovery(clientId, [])}`,
+ `Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker} in three tries: ${detail}.${listed === null ? ` Listing Track's secrets failed too, so it may be set after all: run ${rerun} first, which finishes if Track has it.` : ""} The client secret is gone with this run, so the registration needs cleaning up: ${startAgain(clientId, [])}`,
);
}
say(` set ${item.name} on ${item.worker}`);
+ trackSet = [...new Set([...trackSet, item.name])];
continue;
}
const value = values[item.name];
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index c9a0ad0..ce667f3 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -545,9 +545,18 @@ export function hideAccountNames(text: string, names: readonly string[]): string
const REDACTED = "[secret]";
+/**
+ * Takes the name and password out of every address in a text, so `https://user:pass@host` reads
+ * `https://host`. Every message passes through it: an address read from a Worker's settings or
+ * from a child's output can hold them as well as one a person typed.
+ */
+export function withoutCredentials(text: string): string {
+ return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#@"'`<>]*@/gi, "$1");
+}
+
/** Hides exact secret values and secret assignments in child output or an error message. */
export function hideSecrets(text: string, values: readonly string[]): string {
- let clean = text;
+ let clean = withoutCredentials(text);
for (const value of new Set(values.filter((secret) => secret.length >= 8))) {
clean = clean.replaceAll(value, REDACTED);
}
diff --git a/packages/cli/src/doctor-track.ts b/packages/cli/src/doctor-track.ts
index 0819c5c..ab3fea7 100644
--- a/packages/cli/src/doctor-track.ts
+++ b/packages/cli/src/doctor-track.ts
@@ -377,7 +377,11 @@ export async function trackSignInFindings(
}
// Track names the issuer in its page's policy, the one place OIDC_ISSUER shows from outside.
const issuers = await pagePolicyIssuers(sys, at);
- const unread = `The client id Track holds is a secret, which cannot be read back; this tool gave it ${connection.clientId}, and \`gateweave doctor id\` checks that ID still has that one.`;
+ // Only a value this tool's record shows it set is said to come from it.
+ const unread =
+ connection.clientId && connection.trackSet?.includes("OIDC_CLIENT_ID")
+ ? `The client id Track holds is a secret, which cannot be read back; this tool gave it ${connection.clientId}, and \`gateweave doctor id\` checks that ID still has that one.`
+ : "The client id Track holds is a secret this tool's record does not show it set, so which client Track signs in as cannot be told here.";
if (issuers === null) {
return finding(
"warn",
diff --git a/packages/cli/src/lock.ts b/packages/cli/src/lock.ts
index e655d8c..e942eb0 100644
--- a/packages/cli/src/lock.ts
+++ b/packages/cli/src/lock.ts
@@ -1,4 +1,4 @@
-import { link, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
+import { mkdir, open, readFile, rm } from "node:fs/promises";
import { hostname } from "node:os";
import { join } from "node:path";
import { CliError } from "./errors.ts";
@@ -11,15 +11,12 @@ interface Holder {
startedAt: string;
}
-/** A lock older than this is taken for one whose run ended without removing it. */
-const STALE_AFTER_MS = 6 * 60 * 60 * 1000;
-
+/** Whether a process of this machine is running. EPERM: it is, only someone else's. */
function isAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
- // EPERM: the process exists, it is only someone else's.
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
@@ -38,10 +35,10 @@ function holderOf(text: string): Holder | null {
}
/**
- * One run of a command at a time: an exclusive lock file beside the record. A second run is
- * refused in words. A lock whose process has ended on this machine, or that is hours old, is stale:
- * it is moved aside and checked to be the one judged stale before it is removed, so two runs that
- * both find it stale cannot remove a lock a third has just taken. Returns the release.
+ * One run of a command at a time: an exclusive lock file beside the record. A lock that is there
+ * is never cleared by this tool, however old, and whether or not its process still runs: a run
+ * stops, says who holds it, and leaves the file to the person, who alone can tell that no run is
+ * going. Returns the release, which removes only this run's own lock.
*/
export async function takeLock(sys: System, command: string): Promise<() => Promise> {
const dir = configDir(sys);
@@ -52,59 +49,41 @@ export async function takeLock(sys: System, command: string): Promise<() => Prom
host: hostname(),
startedAt: new Date(Date.now()).toISOString(),
} satisfies Holder);
- const busy = (held: Holder | null) =>
- new CliError(
- "requirement",
- "run-in-progress",
- `Another \`gateweave ${command.replaceAll("-", " ")}\` is running${held ? ` (process ${held.pid} on ${held.host}, since ${held.startedAt})` : ""}. Two at once could both make ID's pairwise secret or both register Track, so this one stops; nothing was changed. Run it again when the other has finished. If none is running, remove ${path}.`,
- );
-
- for (let attempt = 0; attempt < 3; attempt++) {
- try {
- const handle = await open(path, "wx", 0o600);
- try {
- await handle.writeFile(mine);
- } finally {
- await handle.close();
- }
- return async () => {
- // Only its own lock: one a later run took after this one's was cleared stays.
- const now = await readFile(path, "utf8").catch(() => null);
- if (now === mine) await rm(path, { force: true });
- };
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
- throw new CliError(
- "requirement",
- "lock-unwritable",
- `Could not take the lock ${path} (${(error as NodeJS.ErrnoException).code ?? "error"}).`,
- );
- }
- }
- const text = await readFile(path, "utf8").catch(() => null);
- if (text === null) continue; // Removed meanwhile: try again.
- const held = holderOf(text);
- const age = await stat(path).then(
- (found) => Date.now() - found.mtimeMs,
- () => 0,
- );
- const ended = held !== null && held.host === hostname() && !isAlive(held.pid);
- // A lock that cannot be read is one being written: it is stale only once it is old.
- if (!ended && age < STALE_AFTER_MS) throw busy(held);
- const aside = `${path}.stale-${process.pid}-${Date.now()}`;
+ try {
+ const handle = await open(path, "wx", 0o600);
try {
- await rename(path, aside);
- } catch {
- continue; // Another run moved it first.
+ await handle.writeFile(mine);
+ } finally {
+ await handle.close();
}
- const moved = await readFile(aside, "utf8").catch(() => null);
- if (moved !== text) {
- // A live lock was taken between the read and the move: put it back, never remove it.
- await link(aside, path).catch(() => undefined);
- await rm(aside, { force: true });
- throw busy(holderOf(moved ?? ""));
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "EEXIST") {
+ throw new CliError(
+ "requirement",
+ "lock-unwritable",
+ `Could not take the lock ${path} (${code ?? "error"}).`,
+ );
}
- await rm(aside, { force: true });
+ const held = holderOf((await readFile(path, "utf8").catch(() => null)) ?? "");
+ const who = held
+ ? `It was taken by process ${held.pid} on ${held.host}, at ${held.startedAt}; ${
+ held.host !== hostname()
+ ? "that is another machine, so whether it still runs cannot be told here"
+ : isAlive(held.pid)
+ ? "a process with that id is running on this machine now"
+ : "no process with that id is running on this machine now"
+ }.`
+ : "Who took it cannot be read from it.";
+ throw new CliError(
+ "requirement",
+ "run-in-progress",
+ `Another \`gateweave ${command.replaceAll("-", " ")}\` may be running: its lock ${path} is there. ${who} Two at once could both make ID's pairwise secret or both register Track, so this one stops; nothing was changed. This tool never removes a lock it did not take. Delete ${path} yourself only once you are sure no such run is going, then run this again.`,
+ );
}
- throw busy(null);
+ return async () => {
+ // Only its own lock: a file someone replaced meanwhile stays.
+ const now = await readFile(path, "utf8").catch(() => null);
+ if (now === mine) await rm(path, { force: true });
+ };
}
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index b7095fa..d229d6a 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -1,6 +1,11 @@
import { parseArgs } from "node:util";
import { connectIdTrack, describeConnect } from "./connect.ts";
-import { type DeployTrackResult, deployId, deployTrack } from "./deploy-track.ts";
+import {
+ type DeployTrackResult,
+ deployId,
+ deployTrack,
+ withoutCredentials,
+} from "./deploy-track.ts";
import { type DoctorTrackResult, doctorId, doctorTrack } from "./doctor-track.ts";
import { CliError } from "./errors.ts";
import { PRODUCTS } from "./products.ts";
@@ -82,7 +87,9 @@ Options:
--track-name The recorded Track Worker, when the account has several.
--account The Cloudflare account, when the sign-in reaches several.
Default: CLOUDFLARE_ACCOUNT_ID.
- --no-account-name Print only the Cloudflare account id, never its name.
+ --no-account-name Print only the Cloudflare account id, never its name. Addresses
+ are still shown, so an account named after its workers.dev
+ subdomain shows through a workers.dev address.
--yes Make the changes without asking. Needed when there is no terminal.
--json Print the result, or the failure, as one JSON object on stdout.
--help Show this.
@@ -230,9 +237,10 @@ function describeDoctor(result: DoctorTrackResult, label = "Track"): string {
export async function main(argv: string[], sys: System): Promise {
let json = argv.includes("--json");
const fail = (error: CliError): number => {
- if (json)
- sys.out(`${JSON.stringify({ ok: false, code: error.code, reason: error.message })}\n`);
- else sys.err(`gateweave: ${error.message}\n`);
+ // Whatever address a reason holds, read or given, goes without a name and password.
+ const reason = withoutCredentials(error.message);
+ if (json) sys.out(`${JSON.stringify({ ok: false, code: error.code, reason })}\n`);
+ else sys.err(`gateweave: ${reason}\n`);
return error.exitCode;
};
diff --git a/packages/cli/src/record.ts b/packages/cli/src/record.ts
index 5decba0..eb5175c 100644
--- a/packages/cli/src/record.ts
+++ b/packages/cli/src/record.ts
@@ -72,6 +72,11 @@ export interface ConnectionRecord {
/** The OIDC_PROVIDER_NAME this tool set, or null when Track already had one and kept it. */
providerName: string | null;
clientId: string | null;
+ /**
+ * The Track settings this tool set for that client, by name. Only what is named here may be said
+ * to come from this tool: a secret cannot be read back to tell.
+ */
+ trackSet?: string[];
steps: ConnectionStep[];
updatedAt: string;
}
@@ -85,6 +90,7 @@ export const CONNECTION_FIELDS: readonly (keyof ConnectionRecord)[] = [
"trackAddress",
"providerName",
"clientId",
+ "trackSet",
"steps",
"updatedAt",
];
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index 5616957..831be8e 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -13,6 +13,7 @@ import {
statSync,
symlinkSync,
unlinkSync,
+ utimesSync,
writeFileSync,
} from "node:fs";
import { open } from "node:fs/promises";
@@ -20,7 +21,8 @@ import { hostname, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { after, describe, test } from "node:test";
import { parse } from "jsonc-parser";
-import { hideSecrets } from "../src/deploy-track.ts";
+import { decodeEntities } from "../src/checks.ts";
+import { hideSecrets, withoutCredentials } from "../src/deploy-track.ts";
import { main } from "../src/main.ts";
import { configDir } from "../src/paths.ts";
import { type ConnectionRecord, recordPath, saveConnection, saveRecord } from "../src/record.ts";
@@ -69,6 +71,8 @@ interface ConnectFakeOptions extends FakeOptions {
registered?: string[];
/** Replaces what the fake apps:add prints, and its status and stderr. */
appsAdd?: { stdout: string; status?: number; stderr?: string };
+ /** The client id ID keeps for the app apps:add registers. Default: CLIENT_ID. */
+ registerAs?: string;
/** A `secret put` of this name fails, echoing its value and the tokens on stderr. */
failPut?: string;
/** Makes this look fail. */
@@ -104,8 +108,23 @@ async function connectFake(options: ConnectFakeOptions = {}) {
`oauth_token = "${OAUTH_TOKEN}"\nrefresh_token = "refresh-0123456789"\n`,
);
- const state = { failPut: options.failPut, beforeOpen: undefined as (() => void) | undefined };
- const puts: { worker: string; name: string; input: string | undefined; errBefore: string }[] = [];
+ const state = {
+ failPut: options.failPut,
+ beforeOpen: undefined as (() => void) | undefined,
+ /** A put of this name is taken by Cloudflare, but its answer is lost: Wrangler fails. */
+ lostPut: undefined as string | undefined,
+ /** Every `secret list` after a put of this name fails. */
+ failListAfter: undefined as string | undefined,
+ listFails: false,
+ };
+ const puts: {
+ worker: string;
+ name: string;
+ input: string | undefined;
+ errBefore: string;
+ /** The record file as it was when this put ran, or null. */
+ recordBefore: string | null;
+ }[] = [];
const appsAdd: { args: string[]; cwd: string }[] = [];
const registrations = [...(options.registered ?? [])];
/** What each put set, so the pages show what Track was given. */
@@ -141,10 +160,37 @@ async function connectFake(options: ConnectFakeOptions = {}) {
const at = args.indexOf(`wrangler@${WRANGLER}`);
const rest = at >= 0 ? args.slice(at + 1) : [];
const worker = rest[rest.indexOf("--name") + 1] ?? "";
+ if (
+ command === fake.sys.execPath &&
+ rest[0] === "secret" &&
+ rest[1] === "list" &&
+ state.listFails
+ ) {
+ record();
+ return {
+ status: 1,
+ stdout: "",
+ stderr: "✘ [ERROR] A request to the Cloudflare API failed.\n",
+ };
+ }
if (command === fake.sys.execPath && rest[0] === "secret" && rest[1] === "put") {
record();
const name = rest[2] ?? "";
- puts.push({ worker, name, input: runOptions.input, errBefore: fake.output.err });
+ puts.push({
+ worker,
+ name,
+ input: runOptions.input,
+ errBefore: fake.output.err,
+ recordBefore: existsSync(recordPath(fake.sys))
+ ? readFileSync(recordPath(fake.sys), "utf8")
+ : null,
+ });
+ if (state.failListAfter === name) state.listFails = true;
+ if (state.lostPut === name) {
+ secretsOf(worker).add(name);
+ values.set(`${worker} ${name}`, runOptions.input ?? "");
+ return { status: 1, stdout: "", stderr: "✘ [ERROR] The connection was reset.\n" };
+ }
if (state.failPut === name) {
return {
status: 1,
@@ -245,7 +291,7 @@ async function connectFake(options: ConnectFakeOptions = {}) {
const config = readFileSync(join(runOptions.cwd, "..", "..", "wrangler.jsonc"), "utf8");
assert.match(config, /"database_name": "gateweave-id"/);
assert.equal(runOptions.stream, undefined);
- registrations.push(CLIENT_ID);
+ registrations.push(options.registerAs ?? CLIENT_ID);
if (options.appsAdd !== undefined) {
return {
status: options.appsAdd.status ?? 0,
@@ -839,15 +885,27 @@ describe("gateweave connect id track", () => {
err,
/ID \(gateweave-id\) does not have global_fetch_strictly_public in its compatibility_flags, so its back-channel logout cannot reach Track on workers\.dev/,
);
- assert.match(err, /Sign-in works, as there Track calls ID/);
assert.doesNotMatch(err, /sign-in through ID fails/);
+ assert.doesNotMatch(err, /Sign-in works/);
+ // Neither Worker has the flag: each direction is told once, and nothing says the other works.
const bare = await connectFake({ trackFlags: [] });
const without = await bare.connect(keepArgs(bare, "k"));
assert.match(
without.err,
/Track \(gateweave-track\) does not have global_fetch_strictly_public in its compatibility_flags, so it cannot reach ID on workers\.dev: sign-in through ID fails/,
);
+ assert.match(
+ without.err,
+ /ID \(gateweave-id\) does not have global_fetch_strictly_public in its compatibility_flags, so its back-channel logout cannot reach Track/,
+ );
+ assert.doesNotMatch(without.err, /Sign-in works|sign-in works/);
+
+ // Only ID has it: sign-in fails, and back-channel logout is not warned about.
+ const idOnly = await connectFake({ trackFlags: [], idFlags: [STRICT] });
+ const fromId = await idOnly.connect(keepArgs(idOnly, "k"));
+ assert.match(fromId.err, /sign-in through ID fails/);
+ assert.doesNotMatch(fromId.err, /back-channel logout cannot reach/);
const custom = await connectFake();
const own = await custom.connect([
@@ -1041,6 +1099,12 @@ describe("gateweave connect id track", () => {
assert.equal(result.code, "client-secret-not-set");
assert.match(result.reason, /the body \[secret\] was sent with \[secret\] and \[secret\]/);
assert.match(result.reason, /DELETE FROM oauth_client/);
+ assert.match(result.reason, /in three tries/);
+ assert.match(
+ result.reason,
+ /The client secret is gone with this run, so the registration needs cleaning up: remove the registration from ID/,
+ );
+ assert.match(result.reason, /then run `gateweave connect id track` again, which registers/);
assert.equal(run.puts.filter(({ name }) => name === "OIDC_CLIENT_SECRET").length, 3);
assert.deepEqual(leaked(out), []);
assert.deepEqual(leaked(err), []);
@@ -1049,20 +1113,24 @@ describe("gateweave connect id track", () => {
assert.deepEqual(connection.steps, ["registered"]);
assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []);
- // The generated value, echoed by a failed put, is filtered too, and its file goes again.
+ // The generated value, echoed by a failed put, is filtered too. ID's list shows it is not set;
+ // even so its file stays, as only the person removes a file that held a secret.
const pairwise = await connectFake({ failPut: "OIDC_PAIRWISE_SECRET" });
const kept = join(pairwise.keepDir, "pairwise.txt");
const failed = await pairwise.connect(["--keep-secret-at", kept, "--yes", "--json"]);
assert.equal(failed.code, 8);
assert.equal(failed.result.code, "secret-put-failed");
assert.match(failed.result.reason, /the body \[secret\] was sent/);
+ assert.match(failed.result.reason, /ID's list of secrets shows it is not set/);
+ assert.match(failed.result.reason, /This tool does not remove it; delete it yourself/);
assert.deepEqual(leaked(failed.out), []);
assert.deepEqual(leaked(failed.err), []);
- assert.ok(!existsSync(kept), "a value that was never set is not left to be kept");
+ assert.ok(existsSync(kept), "the file is never removed once the put was tried");
assert.equal(pairwise.appsAdd.length, 0);
- // The rerun makes a new value and finishes.
+ // The rerun, with a new path, makes a new value and finishes.
pairwise.state.failPut = undefined;
- const rerun = await pairwise.connect(["--keep-secret-at", kept, "--yes", "--json"]);
+ const again = join(pairwise.keepDir, "pairwise-2.txt");
+ const rerun = await pairwise.connect(["--keep-secret-at", again, "--yes", "--json"]);
assert.equal(rerun.code, 0, rerun.err);
assert.equal(pairwise.randomCalls(), 2);
});
@@ -1092,30 +1160,263 @@ describe("gateweave connect id track", () => {
);
});
- test("a second run while one is going is refused, and a lock left by an ended run is cleared", async () => {
+ test("a put whose answer is lost, with no listing after it, keeps the file and says the value may be set", async () => {
+ const run = await connectFake();
+ run.state.lostPut = "OIDC_PAIRWISE_SECRET";
+ run.state.failListAfter = "OIDC_PAIRWISE_SECRET";
+ const keep = join(run.keepDir, "pairwise.txt");
+ const first = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]);
+ assert.equal(first.code, 8);
+ assert.equal(first.result.code, "secret-put-unknown");
+ assert.match(first.result.reason, /whether ID has the value is unknown: it may be set/);
+ assert.ok(first.result.reason.includes(`Keep ${keep}`));
+ assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`, "the only copy stays");
+ assert.deepEqual(leaked(first.out), []);
+ assert.deepEqual(leaked(first.err), []);
+ assert.equal(run.appsAdd.length, 0);
+
+ // The rerun sees ID has it, makes nothing new, and finishes with the kept value.
+ run.state.lostPut = undefined;
+ run.state.failListAfter = undefined;
+ run.state.listFails = false;
+ const second = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]);
+ assert.equal(second.code, 0, second.err);
+ assert.equal(run.randomCalls(), 1);
+ assert.equal(run.values.get("gateweave-id OIDC_PAIRWISE_SECRET"), PAIRWISE);
+ assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`);
+
+ // A lost answer whose listing shows the value is a put that worked.
+ const listed = await connectFake();
+ listed.state.lostPut = "OIDC_PAIRWISE_SECRET";
+ const kept = await listed.connect([...keepArgs(listed), "--yes", "--json"]);
+ assert.equal(kept.code, 0, kept.err);
+ });
+
+ test("a lock that is there is never cleared: the run says who holds it and stops", async () => {
const run = await connectFake();
const lock = join(configDir(run.fake.sys), LOCK);
mkdirSync(configDir(run.fake.sys), { recursive: true });
- const live = JSON.stringify({ pid: process.pid, host: hostname(), startedAt: "now" });
- writeFileSync(lock, live);
- const busy = await run.connect([...keepArgs(run), "--yes", "--json"]);
- assert.equal(busy.code, 3);
- assert.equal(busy.result.code, "run-in-progress");
- assert.match(busy.result.reason, new RegExp(`process ${process.pid}`));
- assert.deepEqual(run.newCalls(), []);
- assert.equal(readFileSync(lock, "utf8"), live, "another run's lock stays");
-
const ended = spawnSync(process.execPath, ["-e", ""]).pid;
- writeFileSync(lock, JSON.stringify({ pid: ended, host: hostname(), startedAt: "then" }));
+ const cases: [Record, RegExp][] = [
+ [
+ { pid: process.pid, host: hostname(), startedAt: "2026-01-02T03:04:05.000Z" },
+ /a process with that id is running on this machine now/,
+ ],
+ [
+ { pid: ended, host: hostname(), startedAt: "2026-01-02T03:04:05.000Z" },
+ /no process with that id is running on this machine now/,
+ ],
+ [
+ { pid: ended, host: `not-${hostname()}`, startedAt: "2026-01-02T03:04:05.000Z" },
+ /that is another machine, so whether it still runs cannot be told here/,
+ ],
+ ];
+ for (const [holder, alive] of cases) {
+ const text = JSON.stringify(holder);
+ writeFileSync(lock, text);
+ // Days old: age clears nothing.
+ const old = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
+ utimesSync(lock, old, old);
+ const busy = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(busy.code, 3);
+ assert.equal(busy.result.code, "run-in-progress");
+ assert.ok(busy.result.reason.includes(lock), "the lock's path");
+ assert.match(busy.result.reason, new RegExp(`process ${holder.pid}`));
+ assert.match(busy.result.reason, /at 2026-01-02T03:04:05\.000Z/);
+ assert.match(busy.result.reason, alive);
+ assert.match(busy.result.reason, /only once you are sure no such run is going/);
+ assert.equal(readFileSync(lock, "utf8"), text, "the lock stays as it was");
+ assert.deepEqual(run.newCalls(), []);
+ }
+ assert.deepEqual(
+ readdirSync(configDir(run.fake.sys)).filter((name) => name.includes(".lock")),
+ [LOCK],
+ );
+ // Removed by the person, the next run goes, and removes its own lock.
+ rmSync(lock);
const after = await run.connect([...keepArgs(run), "--yes", "--json"]);
assert.equal(after.code, 0, after.err);
assert.ok(!existsSync(lock));
- assert.deepEqual(
- readdirSync(configDir(run.fake.sys)).filter((name) => name.includes(".lock")),
- [],
+ });
+
+ test("Track's OIDC_CLIENT_ID or OIDC_ISSUER that this tool did not set stops before any change", async () => {
+ for (const held of [["OIDC_CLIENT_ID"], ["OIDC_ISSUER"], ["OIDC_ISSUER", "OIDC_CLIENT_ID"]]) {
+ const run = await connectFake({
+ registered: [CLIENT_ID],
+ trackSecrets: ["OIDC_CLIENT_SECRET", ...held],
+ });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3, held.join());
+ assert.equal(result.code, "track-settings-not-ours");
+ assert.match(result.reason, new RegExp(`Track already had ${held.join(" and ")}`));
+ assert.match(result.reason, /Nothing was changed/);
+ // The same steps as for a registration without its secret.
+ assert.match(
+ result.reason,
+ new RegExp(`DELETE FROM oauth_client WHERE client_id = '${CLIENT_ID}'`),
+ );
+ for (const name of ["OIDC_CLIENT_SECRET", ...held]) {
+ assert.match(result.reason, new RegExp(`secret delete ${name} --name gateweave-track`));
+ }
+ assert.deepEqual(run.changes(), []);
+ }
+ // One the record shows this tool set is its own: a rerun goes on.
+ const ours = await connectFake();
+ assert.equal((await ours.connect([...keepArgs(ours), "--yes"])).code, 0);
+ const again = await ours.connect(["--yes", "--json"]);
+ assert.equal(again.code, 0, again.err);
+ });
+
+ test("a text OIDC_ISSUER is compared whole with the issuer, its path included", async () => {
+ for (const issuer of [`${ID}/wrong`, `${ID}/`, "https://elsewhere.example.com"]) {
+ const run = await connectFake({
+ registered: [CLIENT_ID],
+ trackSecrets: ["OIDC_CLIENT_SECRET"],
+ trackVars: { OIDC_ISSUER: issuer },
+ });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3, issuer);
+ assert.equal(result.code, "client-differs");
+ assert.ok(result.reason.includes(`Track's OIDC_ISSUER is ${issuer}, not ${ID}`));
+ assert.deepEqual(run.changes(), []);
+ }
+ });
+
+ test("an address read from a Worker is repeated without its name and password", async () => {
+ const run = await connectFake({
+ trackVars: { BETTER_AUTH_URL: "https://admin:pa55word-zz@elsewhere.example.com" },
+ });
+ const json = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(json.code, 3);
+ assert.equal(json.result.code, "track-address-differs");
+ assert.ok(
+ json.result.reason.includes("Track's BETTER_AUTH_URL is https://elsewhere.example.com,"),
+ );
+ const plainRun = await run.connect([...keepArgs(run), "--yes"]);
+ for (const text of [json.out, json.err, plainRun.out, plainRun.err]) {
+ assert.ok(!text.includes("pa55word"), "no password");
+ assert.ok(!text.includes("admin"), "no name");
+ }
+ assert.equal(
+ withoutCredentials(
+ "at https://u:p@a.example.com/x and http://u@b.example.com, not mailto:u@c.example.com",
+ ),
+ "at https://a.example.com/x and http://b.example.com, not mailto:u@c.example.com",
);
});
+ test("Track's button is read as the page shows it, character references decoded", async () => {
+ const run = await connectFake({
+ trackVars: { OIDC_PROVIDER_NAME: "Acme & Co" },
+ buttonName: "Acme & Co",
+ });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 0, JSON.stringify(result));
+ assert.equal(
+ decodeEntities("<b> "A" 'B' & & < "),
+ ` "A" 'B' & & < `,
+ );
+ });
+
+ test("apps:add output is read as captured: control characters are not stripped first", async () => {
+ const lines = `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\n`;
+ for (const output of [
+ `\u001b[32m${lines}`,
+ lines.replace("client id:", "client\u001b[0m id:"),
+ ]) {
+ const run = await connectFake({ appsAdd: { stdout: output } });
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 8);
+ assert.equal(result.code, "register-output-unreadable");
+ assert.deepEqual(
+ run.puts.filter(({ worker }) => worker === "gateweave-track"),
+ [],
+ );
+ }
+ // Windows line endings are the same output.
+ const crlf = await connectFake({ appsAdd: { stdout: lines.replaceAll("\n", "\r\n") } });
+ assert.equal((await crlf.connect([...keepArgs(crlf), "--yes", "--json"])).code, 0);
+ // ID's random ids can start with "gwid_"; only the secret's own prefix is refused as an id.
+ const gwid = `gwid_${CLIENT_ID.slice(5)}`;
+ const lucky = await connectFake({
+ appsAdd: { stdout: lines.replace(CLIENT_ID, gwid) },
+ registerAs: gwid,
+ });
+ const taken = await lucky.connect([...keepArgs(lucky), "--yes", "--json"]);
+ assert.equal(taken.code, 0, taken.err);
+ assert.equal(taken.result.clientId, gwid);
+ });
+
+ test("a folder link retargeted after the plan, to another folder outside, is refused", async () => {
+ const run = await connectFake();
+ const first = join(run.keepDir, "first");
+ const second = join(run.keepDir, "second");
+ mkdirSync(first);
+ mkdirSync(second);
+ const folder = join(run.keepDir, "folder");
+ linkFolder(first, folder);
+ run.state.beforeOpen = () => {
+ unlinkFolder(folder);
+ linkFolder(second, folder);
+ };
+ const { code, result, out, err } = await run.connect([
+ "--keep-secret-at",
+ join(folder, "pairwise.txt"),
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 2);
+ assert.equal(result.code, "keep-path-moved");
+ assert.deepEqual(readdirSync(second), [], "nothing is written in the new place");
+ assert.deepEqual(readdirSync(first), []);
+ assert.ok(!run.puts.some(({ name }) => name === "OIDC_PAIRWISE_SECRET"));
+ assert.deepEqual(leaked(out), []);
+ assert.deepEqual(leaked(err), []);
+ });
+
+ test("the rerun a message gives repeats the names and addresses given", async () => {
+ const run = await connectFake({ registered: [CLIENT_ID] });
+ const { code, result } = await run.connect([
+ "--id-name",
+ "gateweave-id",
+ "--track-name",
+ "gateweave-track",
+ "--id-url",
+ ID,
+ "--track-url",
+ TRACK,
+ "--no-account-name",
+ ...keepArgs(run),
+ "--yes",
+ "--json",
+ ]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "registered-without-secret");
+ const rerun = `\`gateweave connect id track --id-name gateweave-id --track-name gateweave-track --id-url ${ID} --track-url ${TRACK} --no-account-name\``;
+ assert.ok(result.reason.includes(`and run ${rerun} again. If not,`), result.reason);
+ assert.ok(result.reason.includes(`then run ${rerun} again, which registers Track anew`));
+ });
+
+ test("the record holds the client id before Track's first secret is put", async () => {
+ const run = await connectFake();
+ const { code, err } = await run.connect([...keepArgs(run), "--yes"]);
+ assert.equal(code, 0, err);
+ const onTrack = run.puts.filter(({ worker }) => worker === "gateweave-track");
+ assert.equal(onTrack[0]?.name, "OIDC_CLIENT_SECRET");
+ const before = JSON.parse(onTrack[0]?.recordBefore ?? "{}") as {
+ connections?: { clientId: string; steps: string[] }[];
+ };
+ assert.equal(before.connections?.[0]?.clientId, CLIENT_ID);
+ assert.deepEqual(before.connections?.[0]?.steps, ["registered"]);
+ // And each later setting is on record as this tool's before it is put.
+ for (const put of onTrack.slice(1)) {
+ const record = JSON.parse(put.recordBefore ?? "{}") as {
+ connections?: { trackSet?: string[] }[];
+ };
+ assert.ok(record.connections?.[0]?.trackSet?.includes(put.name), put.name);
+ }
+ });
+
test("an address with a name and password in it is refused without repeating it", async () => {
const run = await connectFake();
for (const args of [
@@ -1199,6 +1500,17 @@ describe("gateweave connect id track", () => {
assert.match(track?.message ?? "", /Track names the issuer https:\/\/id\.example\.com/);
assert.match(track?.message ?? "", /a secret, which cannot be read back/);
assert.doesNotMatch(track?.message ?? "", /connected/);
+ assert.ok((track?.message ?? "").includes(`this tool gave it ${CLIENT_ID}`));
+ // A record that does not show this tool set OIDC_CLIENT_ID makes no such claim.
+ const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8"));
+ const saved = file.connections[0].trackSet;
+ file.connections[0].trackSet = saved.filter((name: string) => name !== "OIDC_CLIENT_ID");
+ writeFileSync(recordPath(run.fake.sys), JSON.stringify(file));
+ const unclaimed = (await findings("track")).find(({ id }) => id === "sign-in-provider");
+ assert.doesNotMatch(unclaimed?.message ?? "", /this tool gave it/);
+ assert.match(unclaimed?.message ?? "", /this tool's record does not show it set/);
+ file.connections[0].trackSet = saved;
+ writeFileSync(recordPath(run.fake.sys), JSON.stringify(file));
const id = (await findings("id")).find(({ id: found }) => found === "oidc-provider");
assert.ok(
run.fake.events.includes("fetch GET https://id.example.com/.well-known/openid-configuration"),
From 4b866c784d95151b3145dbe79c0abe8352c7582b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:48:37 +0100
Subject: [PATCH 07/14] docs(cli): locks, lost puts, foreign Track settings and
what addresses show
---
packages/cli/README.md | 79 +++++++++++++++++++++++-------------------
1 file changed, 44 insertions(+), 35 deletions(-)
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 0779655..6a33ab9 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -40,7 +40,8 @@ in the account, choose with `--id-name` or `--track-name`. A deployment that `ga
recorded without having made it is used only when named that way, never picked on its own.
`--id-url` and `--track-url` replace the recorded addresses, such as a Custom Domain you added since.
`--no-account-name` keeps the Cloudflare account's name out of the plan, the errors and `--json`,
-which then name the account by its id.
+which then name the account by its id. Addresses are still shown, so an account named after its
+`workers.dev` subdomain still shows through a `workers.dev` address.
1. **Looks, changing nothing.** For each Worker: its secrets (`secret list`), and every binding of
its deployed version (`deployments status`, `versions view`), so a setting kept as a text
@@ -69,14 +70,19 @@ which then name the account by its id.
Every value goes to `wrangler secret put` on stdin, never as an argument. A setting that is already
set, as a secret or as a text variable, is left alone and never replaced. A text variable's value
is used where it matters: ID's `BETTER_AUTH_URL` names the issuer, and Track's `OIDC_PROVIDER_NAME`
-is the button the check looks for. A secret cannot be read back, so the command stops where it
-would have to guess one: Track's `OIDC_PROVIDER_NAME` set as a secret by someone else, or a client
-id on record that differs from the one ID has registered for Track. Each stop says what to do, and
-changes nothing.
-
-Only one run at a time: a run takes the lock file `connect-id-track.lock` beside the record, and a
-second run stops while it is there. A lock left by a run that ended without removing it (its
-process is gone, or it is hours old) is cleared by the next run.
+is the button the check looks for, read as the page shows it (`Acme & Co` is `Acme & Co`).
+Track's `OIDC_ISSUER` as a text variable must be the issuer exactly, path and all. A secret cannot
+be read back, so the command stops where it would have to guess one: Track's `OIDC_PROVIDER_NAME`
+set as a secret by someone else, a client id on record that differs from the one ID has registered
+for Track, or Track's `OIDC_CLIENT_ID` or `OIDC_ISSUER` there before this tool set them (its record
+names each Track setting it set). Each stop says what to do, and changes nothing. Every address in
+a message, whether given or read from a Worker, is shown without a name and password.
+
+Only one run at a time: a run takes the lock file `connect-id-track.lock` beside the record, and
+removes it when it ends. A run that finds the file stops, whatever its age: it gives the file's
+path, the process id and start time of the run that took it, and whether that process is running
+on this machine now. This tool never removes a lock it did not take; delete the file yourself only
+once you are sure no run is going.
**The issuer cannot change.** ID's `BETTER_AUTH_URL` becomes the issuer that apps compare, and
passkeys are bound to it for good. Once any app has signed anyone in, it can never change. Choose
@@ -84,10 +90,10 @@ the address people will always use before you run this: give ID a Custom Domain
with `--id-url`.
**`workers.dev` has a limit.** A Worker reaches another Worker's `workers.dev` address only when
-the calling Worker has `global_fetch_strictly_public` in its `compatibility_flags`. Track has it, so
-Track's calls to ID, the sign-in, work. ID does not, so ID's back-channel logout cannot reach Track
-on `workers.dev`: signing out of ID does not end Track's sessions. The plan reads both Workers'
-flags and warns about the one that lacks it. A
+the calling Worker has `global_fetch_strictly_public` in its `compatibility_flags`. Track calls ID
+to sign people in, and ID calls Track for back-channel logout. As released, Track has the flag and
+ID does not, so signing out of ID does not end Track's sessions on `workers.dev`. The plan reads
+each Worker's own flag and warns once for each direction that lacks it. A
[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) on
Track, or on both, is the setup that works.
@@ -121,35 +127,38 @@ ID, the address and issuer, the provider name and the client id, and no field fo
**A run cut short, and what the next run does.** Each run looks again before it changes anything,
so running the same command again is the way to finish:
-| Where it stopped | What the next run does |
-| ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Before the yes | Starts over; nothing was changed. |
-| Setting ID's `BETTER_AUTH_URL` | Sets it. |
-| Writing the keep file, or setting the pairwise secret | Nothing was set on ID, and a keep file that held the unset value is removed; it makes a new value. A put that Cloudflare took although Wrangler failed counts as set. |
-| ID's discovery not answering yet | Leaves ID's settings alone and registers Track once discovery answers. |
-| `apps:add` failing before it registered | Registers Track. |
-| After `apps:add` registered, before Track had the secret (output unreadable, or three failed tries to set it) | Stops and says how to recover: set the secret yourself if you have it, or remove the registration and Track's OIDC settings; then the run after registers anew. |
-| Setting Track's other settings | The client id is on record before Track is given anything, and ID has the registration: it sets what is missing and registers nothing again. |
-| The checks | Changes nothing and checks again. |
+| Where it stopped | What the next run does |
+| ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Before the yes | Starts over; nothing was changed. |
+| Setting ID's `BETTER_AUTH_URL` | Sets it. |
+| Writing the keep file | Nothing was set on ID; it makes a new value. |
+| Setting the pairwise secret | The keep file is never removed once the put was tried. If ID's list shows the value, the put counted. If the list failed too, the value may be set: keep the file and run again, which makes no new value when ID has one. If the list shows it is not set, delete the file and run again with a new path. |
+| ID's discovery not answering yet | Leaves ID's settings alone and registers Track once discovery answers. |
+| `apps:add` failing before it registered | Registers Track. |
+| After `apps:add` registered, before Track had the secret (output unreadable, or three failed tries to set it) | The registration needs cleaning up, as the client secret is gone with the run; the message gives the steps: remove the registration (and any Track OIDC settings), then the run after registers anew. |
+| Setting Track's other settings | The client id is on record before Track is given anything, and ID has the registration: it sets what is missing and registers nothing again. |
+| The checks | Changes nothing and checks again. |
`gateweave doctor track` and `gateweave doctor id` report the connection at the addresses it was made
on. Doctor track says what it can see from outside: the button by its exact name, and the issuer
Track names in its sign-in page's Content-Security-Policy. The client id Track holds is a secret it
-cannot read, and it says so. Doctor id reads ID's database and says whether Track is still
-registered with the client id this tool gave it.
+cannot read, and it says so; it says this tool gave Track its client id only when the record shows
+this tool set `OIDC_CLIENT_ID`. Doctor id reads ID's database and says whether Track is still
+registered with the client id on record. A message that says to run again gives the command with
+the names and addresses you gave (`--id-name`, `--track-name`, `--id-url`, `--track-url`).
With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`.
-| Exit code | Meaning |
-| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 0 | Connected, or already connected, and every check passed |
-| 1 | Something unexpected; the reason says what |
-| 2 | Wrong usage: an unknown option, an address that is not `https://`, an external deployment not named, a `--keep-secret-at` inside the working directory, already there or moved, or none given where it is needed |
-| 3 | A requirement is missing: a deployment not recorded, a Worker or database gone, a look that failed, another run going, `NODE_DEBUG` set, an issuer other than the one given, a setting it cannot read, Track registered without its secret, or Track with another provider |
-| 4 | The account: several to choose from, or the one named is not reachable |
-| 7 | No yes: declined, or no terminal and no `--yes`; nothing was changed |
-| 8 | Setting a secret, installing ID's release or its `apps:add` failed; the reason says what to do |
-| 9 | Connected, but a check failed, or ID's discovery did not answer before registering |
+| Exit code | Meaning |
+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 0 | Connected, or already connected, and every check passed |
+| 1 | Something unexpected; the reason says what |
+| 2 | Wrong usage: an unknown option, an address that is not `https://`, an external deployment not named, a `--keep-secret-at` inside the working directory, already there or moved, or none given where it is needed |
+| 3 | A requirement is missing: a deployment not recorded, a Worker or database gone, a look that failed, another run going, `NODE_DEBUG` set, an issuer other than the one given, a setting it cannot read, Track registered without its secret or holding OIDC settings this tool did not set, or Track with another provider |
+| 4 | The account: several to choose from, or the one named is not reachable |
+| 7 | No yes: declined, or no terminal and no `--yes`; nothing was changed |
+| 8 | Setting a secret (or not knowing whether it was set), installing ID's release or its `apps:add` failed; the reason says what to do |
+| 9 | Connected, but a check failed, or ID's discovery did not answer before registering |
## License
From 53fc4c698c3bb418ddb85b97422c9bbdc4fd93c5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:49:10 +0100
Subject: [PATCH 08/14] test(cli): a record of the client that does not name a
Track setting does not make it this tool's
---
packages/cli/test/connect-id-track.test.ts | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index 831be8e..d65bcfd 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -1265,6 +1265,17 @@ describe("gateweave connect id track", () => {
assert.equal((await ours.connect([...keepArgs(ours), "--yes"])).code, 0);
const again = await ours.connect(["--yes", "--json"]);
assert.equal(again.code, 0, again.err);
+ // A record of this client that does not name the setting is not enough.
+ const file = JSON.parse(readFileSync(recordPath(ours.fake.sys), "utf8"));
+ assert.equal(file.connections[0].clientId, CLIENT_ID);
+ file.connections[0].trackSet = file.connections[0].trackSet.filter(
+ (name: string) => name !== "OIDC_ISSUER",
+ );
+ writeFileSync(recordPath(ours.fake.sys), JSON.stringify(file));
+ const unnamed = await ours.connect(["--yes", "--json"]);
+ assert.equal(unnamed.code, 3);
+ assert.equal(unnamed.result.code, "track-settings-not-ours");
+ assert.match(unnamed.result.reason, /Track already had OIDC_ISSUER before/);
});
test("a text OIDC_ISSUER is compared whole with the issuer, its path included", async () => {
From 12dae809a4ef5211e895baeca0c647d1ec57f250 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 15:16:18 +0100
Subject: [PATCH 09/14] fix(cli): ownership only once a put is confirmed, and a
restore that finishes
- A Track setting is recorded as pending while its put is tried and as
this tool's only once Wrangler or Track's list confirms it, the client
secret included. A failed put leaves no claim, so neither connect nor
doctor takes a value set by someone else for this tool's.
- Track's text OIDC_CLIENT_ID and OIDC_ISSUER that match ID's registration
are consistent and kept. The advice to restore a known client secret
names the settings that cannot be shown to match, so following it and
running again finishes.
- Credentials are taken out of an address by its structure: everything up
to the last "@" before the host ends, whatever the password holds.
- A printed rerun also repeats --keep-secret-at with its path, --yes and
--json when they were given.
---
packages/cli/README.md | 19 +--
packages/cli/src/connect.ts | 80 ++++++++----
packages/cli/src/deploy-track.ts | 7 +-
packages/cli/src/record.ts | 3 +
packages/cli/test/connect-id-track.test.ts | 140 +++++++++++++++++++--
5 files changed, 208 insertions(+), 41 deletions(-)
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 6a33ab9..8d89a85 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -71,12 +71,16 @@ Every value goes to `wrangler secret put` on stdin, never as an argument. A sett
set, as a secret or as a text variable, is left alone and never replaced. A text variable's value
is used where it matters: ID's `BETTER_AUTH_URL` names the issuer, and Track's `OIDC_PROVIDER_NAME`
is the button the check looks for, read as the page shows it (`Acme & Co` is `Acme & Co`).
-Track's `OIDC_ISSUER` as a text variable must be the issuer exactly, path and all. A secret cannot
-be read back, so the command stops where it would have to guess one: Track's `OIDC_PROVIDER_NAME`
-set as a secret by someone else, a client id on record that differs from the one ID has registered
-for Track, or Track's `OIDC_CLIENT_ID` or `OIDC_ISSUER` there before this tool set them (its record
-names each Track setting it set). Each stop says what to do, and changes nothing. Every address in
-a message, whether given or read from a Worker, is shown without a name and password.
+Track's `OIDC_CLIENT_ID` and `OIDC_ISSUER` as text variables are kept when they are exactly ID's
+client id and issuer, path and all. A secret cannot be read back, so the command stops where it
+would have to guess one: Track's `OIDC_PROVIDER_NAME` set as a secret by someone else, a client id
+on record that differs from the one ID has registered for Track, or Track's `OIDC_CLIENT_ID` or
+`OIDC_ISSUER` as a secret this tool's record does not show it set. The record names a Track setting
+as this tool's only once its put is confirmed, by Wrangler or by Track's list; one tried and never
+confirmed makes no claim. Each stop says what to do, and changes nothing; the advice to restore a
+known client secret also names the settings to remove so the rerun finishes. Every address in a
+message, whether given or read from a Worker, is shown without a name and password, whatever
+characters the password holds.
Only one run at a time: a run takes the lock file `connect-id-track.lock` beside the record, and
removes it when it ends. A run that finds the file stops, whatever its age: it gives the file's
@@ -145,7 +149,8 @@ Track names in its sign-in page's Content-Security-Policy. The client id Track h
cannot read, and it says so; it says this tool gave Track its client id only when the record shows
this tool set `OIDC_CLIENT_ID`. Doctor id reads ID's database and says whether Track is still
registered with the client id on record. A message that says to run again gives the command with
-the names and addresses you gave (`--id-name`, `--track-name`, `--id-url`, `--track-url`).
+the options you gave (`--id-name`, `--track-name`, `--id-url`, `--track-url`, `--keep-secret-at`
+with its path, `--yes`, `--json`).
With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`.
diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts
index d783f24..e36d262 100644
--- a/packages/cli/src/connect.ts
+++ b/packages/cli/src/connect.ts
@@ -392,6 +392,15 @@ async function connect(
...(idGiven ? ["--id-url", idGiven] : []),
...(trackGiven ? ["--track-url", trackGiven] : []),
...(options.accountName ? [] : ["--no-account-name"]),
+ // The path as given: it is where a value is kept, not a value.
+ ...(options.keepSecretAt !== undefined
+ ? [
+ "--keep-secret-at",
+ /\s/.test(options.keepSecretAt) ? `"${options.keepSecretAt}"` : options.keepSecretAt,
+ ]
+ : []),
+ ...(options.yes ? ["--yes"] : []),
+ ...(options.json ? ["--json"] : []),
].join(" ")}\``;
const npx = npxCli(sys);
const cache = cacheDir(sys);
@@ -711,8 +720,8 @@ async function connect(
/** The steps that start the connection again from nothing, ending in a run that works. */
const startAgain = (clientId: string, onTrack: readonly string[]) =>
`remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = ${sqlString(clientId)}"${onTrack.length ? `; remove ${onTrack.join(", ")} from Track: ${onTrack.map(deleteOnTrack).join("; ")}` : ""}; then run ${rerun} again, which registers Track anew.`;
- const recovery = (clientId: string, onTrack: readonly string[]) =>
- `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track (npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker}, which asks for the value) and run ${rerun} again. If not, ${startAgain(clientId, onTrack)}`;
+ const recovery = (clientId: string, onTrack: readonly string[], unproven: readonly string[]) =>
+ `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track (npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker}, which asks for the value)${unproven.length ? `, remove ${unproven.join(" and ")}, which cannot be shown to be this registration's (${unproven.map(deleteOnTrack).join("; ")}),` : ""} and run ${rerun} again, which sets what is missing. If not, ${startAgain(clientId, onTrack)}`;
if (registered.length > 1) {
throw new CliError(
@@ -723,11 +732,26 @@ async function connect(
}
const existingClient = registered[0] ?? null;
const trackHeld = TRACK_OIDC.filter(trackHas);
+ const wantedIssuer = issuerBefore ?? idAddress;
+ /** What Track's setting must be to belong to the registration ID has. */
+ const expected = (name: string) =>
+ name === "OIDC_CLIENT_ID" ? existingClient : name === "OIDC_ISSUER" ? wantedIssuer : null;
+ /**
+ * Whether Track's setting is shown to belong to that registration: a text variable with the
+ * value it must have, or a secret this tool's record shows it set, confirmed, for this client.
+ * Anything else, a secret nobody can read or a value that differs, is not taken for it.
+ */
+ const proven = (name: string) =>
+ name === "OIDC_CLIENT_SECRET" ||
+ (held(trackDeployed, name) === "text"
+ ? textOf(trackDeployed, name) === expected(name)
+ : previous?.clientId === existingClient && previous.trackSet?.includes(name) === true);
+ const unproven = existingClient === null ? [] : trackHeld.filter((name) => !proven(name));
if (existingClient && !trackHas("OIDC_CLIENT_SECRET")) {
throw new CliError(
"requirement",
"registered-without-secret",
- `Track ${trackRecord.worker} is already registered with ID ${idRecord.worker} (client id ${existingClient}), but Track's OIDC_CLIENT_SECRET is not set. This tool never registers Track a second time. ${recovery(existingClient, trackHeld)} Nothing was changed.`,
+ `Track ${trackRecord.worker} is already registered with ID ${idRecord.worker} (client id ${existingClient}), but Track's OIDC_CLIENT_SECRET is not set. This tool never registers Track a second time. ${recovery(existingClient, trackHeld, unproven)} Nothing was changed.`,
);
}
if (existingClient) {
@@ -735,7 +759,6 @@ async function connect(
// a text variable shows its value. A secret cannot be read, so a record that disagrees stops.
const idText = textOf(trackDeployed, "OIDC_CLIENT_ID");
const issuerText = textOf(trackDeployed, "OIDC_ISSUER");
- const wantedIssuer = issuerBefore ?? idAddress;
const differs =
previous?.clientId && previous.clientId !== existingClient
? `this tool gave Track the client id ${previous.clientId}, as its record says`
@@ -753,16 +776,12 @@ async function connect(
}
// OIDC_CLIENT_ID or OIDC_ISSUER that this tool did not set, as its record shows, may name
// another client: a setting that cannot be read is not taken for this registration's.
- const notOurs = trackHeld.filter(
- (name) =>
- name !== "OIDC_CLIENT_SECRET" &&
- !(previous?.clientId === existingClient && previous.trackSet?.includes(name)),
- );
+ const notOurs = unproven;
if (notOurs.length > 0) {
throw new CliError(
"requirement",
"track-settings-not-ours",
- `ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but Track already had ${notOurs.join(" and ")} before this tool set ${notOurs.length === 1 ? "it" : "them"}, so which client Track signs in with cannot be told. Nothing was changed. To start again, ${startAgain(existingClient, trackHeld)}`,
+ `ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but Track holds ${notOurs.join(" and ")} as ${notOurs.length === 1 ? "a secret" : "secrets"} this tool's record does not show it set${notOurs.some((name) => previous?.trackPending?.includes(name)) ? " (it tried to, but the put was never confirmed)" : ""}, so which client Track signs in with cannot be told. Nothing was changed. To start again, ${startAgain(existingClient, trackHeld)}`,
);
}
}
@@ -963,10 +982,10 @@ async function connect(
// "checked" is earned again by this run's own checks.
let steps: ConnectionStep[] = (previous?.steps ?? []).filter((step) => step !== "checked");
// The Track settings this tool set, for this client: what doctor may say this tool gave Track.
- let trackSet: string[] =
- existingClient !== null && previous?.clientId === existingClient
- ? (previous.trackSet ?? [])
- : [];
+ const sameClient = existingClient !== null && previous?.clientId === existingClient;
+ let trackSet: string[] = sameClient ? (previous.trackSet ?? []) : [];
+ // The ones tried and not confirmed: a put whose answer was lost. They make no claim.
+ let trackPending: string[] = sameClient ? (previous.trackPending ?? []) : [];
let clientId = existingClient;
const save = async () => {
try {
@@ -980,6 +999,7 @@ async function connect(
providerName,
clientId,
trackSet,
+ trackPending,
steps,
updatedAt: new Date(sys.now()).toISOString(),
});
@@ -1037,20 +1057,30 @@ async function connect(
(names) => names.has(name),
() => null,
);
+ /** Saves the record, best effort: a failure is told, and tried again, at the end. */
+ const saveQuietly = async () => {
+ recordFailure = await save().then(
+ () => null,
+ (error: CliError) => error,
+ );
+ };
+ // A Track setting is pending while its put is tried, and this tool's only once confirmed:
+ // the put succeeded, or Track's list shows it. A failed put leaves no claim.
+ const trying = async (name: string) => {
+ trackPending = [...new Set([...trackPending, name])];
+ await saveQuietly();
+ };
+ const confirmed = async (name: string) => {
+ trackPending = trackPending.filter((other) => other !== name);
+ trackSet = [...new Set([...trackSet, name])];
+ await saveQuietly();
+ };
const putOrStop = async (
item: Planned,
wrangler: ReturnType,
value: string,
) => {
- if (item.product === "track") {
- // On record before it is tried: a put whose answer is lost may still have set it, and
- // what Track then holds under this name is this run's value.
- trackSet = [...new Set([...trackSet, item.name])];
- recordFailure = await save().then(
- () => null,
- (error: CliError) => error,
- );
- }
+ if (item.product === "track") await trying(item.name);
const { done, detail } = await put(wrangler, item.worker, item.name, value);
if (!done && (await listedNow(wrangler, item.worker, item.name)) !== true) {
throw new CliError(
@@ -1059,6 +1089,7 @@ async function connect(
`Could not set ${item.name} on ${item.worker}: ${detail}. Run ${rerun} to finish; what is set stays, and nothing is registered twice.`,
);
}
+ if (item.product === "track") await confirmed(item.name);
say(` set ${item.name} on ${item.worker}`);
};
@@ -1225,6 +1256,7 @@ async function connect(
if (item.name === "OIDC_CLIENT_SECRET") {
if (clientSecret === null) throw new Error("no client secret");
// First, and tried again: it lives only in this run's memory until Track has it.
+ await trying(item.name);
let listed: boolean | null = false;
let detail = "";
for (let attempt = 0; attempt < 3 && listed !== true; attempt++) {
@@ -1241,8 +1273,8 @@ async function connect(
`Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker} in three tries: ${detail}.${listed === null ? ` Listing Track's secrets failed too, so it may be set after all: run ${rerun} first, which finishes if Track has it.` : ""} The client secret is gone with this run, so the registration needs cleaning up: ${startAgain(clientId, [])}`,
);
}
+ await confirmed(item.name);
say(` set ${item.name} on ${item.worker}`);
- trackSet = [...new Set([...trackSet, item.name])];
continue;
}
const value = values[item.name];
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index ce667f3..4e8ae9e 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -551,7 +551,12 @@ const REDACTED = "[secret]";
* from a child's output can hold them as well as one a person typed.
*/
export function withoutCredentials(text: string): string {
- return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#@"'`<>]*@/gi, "$1");
+ return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/?#]*)/gi, (whole, scheme, authority) => {
+ // The authority ends at the first "/", "?" or "#"; what comes before its last "@" is
+ // userinfo, whatever characters a password holds.
+ const at = authority.lastIndexOf("@");
+ return at < 0 ? whole : `${scheme}${authority.slice(at + 1)}`;
+ });
}
/** Hides exact secret values and secret assignments in child output or an error message. */
diff --git a/packages/cli/src/record.ts b/packages/cli/src/record.ts
index eb5175c..410c15b 100644
--- a/packages/cli/src/record.ts
+++ b/packages/cli/src/record.ts
@@ -77,6 +77,8 @@ export interface ConnectionRecord {
* to come from this tool: a secret cannot be read back to tell.
*/
trackSet?: string[];
+ /** Track settings whose put was tried and never confirmed. They are not this tool's. */
+ trackPending?: string[];
steps: ConnectionStep[];
updatedAt: string;
}
@@ -91,6 +93,7 @@ export const CONNECTION_FIELDS: readonly (keyof ConnectionRecord)[] = [
"providerName",
"clientId",
"trackSet",
+ "trackPending",
"steps",
"updatedAt",
];
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index d65bcfd..f83f45c 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -1104,7 +1104,12 @@ describe("gateweave connect id track", () => {
result.reason,
/The client secret is gone with this run, so the registration needs cleaning up: remove the registration from ID/,
);
- assert.match(result.reason, /then run `gateweave connect id track` again, which registers/);
+ assert.ok(
+ result.reason.includes(
+ `then run \`gateweave connect id track --keep-secret-at ${keep} --yes --json\` again, which registers`,
+ ),
+ result.reason,
+ );
assert.equal(run.puts.filter(({ name }) => name === "OIDC_CLIENT_SECRET").length, 3);
assert.deepEqual(leaked(out), []);
assert.deepEqual(leaked(err), []);
@@ -1248,7 +1253,12 @@ describe("gateweave connect id track", () => {
const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
assert.equal(code, 3, held.join());
assert.equal(result.code, "track-settings-not-ours");
- assert.match(result.reason, new RegExp(`Track already had ${held.join(" and ")}`));
+ assert.match(
+ result.reason,
+ new RegExp(
+ `Track holds ${held.join(" and ")} as (a secret|secrets) this tool's record does not show it set`,
+ ),
+ );
assert.match(result.reason, /Nothing was changed/);
// The same steps as for a registration without its secret.
assert.match(
@@ -1275,7 +1285,7 @@ describe("gateweave connect id track", () => {
const unnamed = await ours.connect(["--yes", "--json"]);
assert.equal(unnamed.code, 3);
assert.equal(unnamed.result.code, "track-settings-not-ours");
- assert.match(unnamed.result.reason, /Track already had OIDC_ISSUER before/);
+ assert.match(unnamed.result.reason, /Track holds OIDC_ISSUER as a secret this tool's record/);
});
test("a text OIDC_ISSUER is compared whole with the issuer, its path included", async () => {
@@ -1403,8 +1413,11 @@ describe("gateweave connect id track", () => {
]);
assert.equal(code, 3);
assert.equal(result.code, "registered-without-secret");
- const rerun = `\`gateweave connect id track --id-name gateweave-id --track-name gateweave-track --id-url ${ID} --track-url ${TRACK} --no-account-name\``;
- assert.ok(result.reason.includes(`and run ${rerun} again. If not,`), result.reason);
+ const rerun = `\`gateweave connect id track --id-name gateweave-id --track-name gateweave-track --id-url ${ID} --track-url ${TRACK} --no-account-name --keep-secret-at ${keepArgs(run)[1]} --yes --json\``;
+ assert.ok(
+ result.reason.includes(`and run ${rerun} again, which sets what is missing. If not,`),
+ result.reason,
+ );
assert.ok(result.reason.includes(`then run ${rerun} again, which registers Track anew`));
});
@@ -1419,15 +1432,124 @@ describe("gateweave connect id track", () => {
};
assert.equal(before.connections?.[0]?.clientId, CLIENT_ID);
assert.deepEqual(before.connections?.[0]?.steps, ["registered"]);
- // And each later setting is on record as this tool's before it is put.
- for (const put of onTrack.slice(1)) {
+ // Each setting is on record as tried before its put, and as this tool's only once confirmed.
+ for (const put of onTrack) {
const record = JSON.parse(put.recordBefore ?? "{}") as {
- connections?: { trackSet?: string[] }[];
+ connections?: { trackSet?: string[]; trackPending?: string[] }[];
};
- assert.ok(record.connections?.[0]?.trackSet?.includes(put.name), put.name);
+ assert.ok(record.connections?.[0]?.trackPending?.includes(put.name), put.name);
+ assert.ok(!record.connections?.[0]?.trackSet?.includes(put.name), put.name);
+ }
+ const [after] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections;
+ assert.deepEqual(after.trackPending, []);
+ assert.deepEqual([...after.trackSet].sort(), onTrack.map(({ name }) => name).sort());
+ });
+
+ test("a Track setting whose put failed is not this tool's, and makes no claim", async () => {
+ const run = await connectFake({ failPut: "OIDC_CLIENT_ID" });
+ const first = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(first.code, 8);
+ assert.equal(first.result.code, "secret-put-failed");
+ const [connection] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections;
+ assert.ok(!connection.trackSet.includes("OIDC_CLIENT_ID"));
+ assert.deepEqual(connection.trackPending, ["OIDC_CLIENT_ID"]);
+ assert.ok(connection.trackSet.includes("OIDC_CLIENT_SECRET"), "the confirmed one is");
+
+ // Someone sets a client id of their own meanwhile: it is not taken for this tool's.
+ run.fake.cloud.secrets.get("gateweave-track")?.add("OIDC_CLIENT_ID");
+ run.values.set("gateweave-track OIDC_CLIENT_ID", OTHER_CLIENT_ID);
+ run.state.failPut = undefined;
+ const second = await run.connect(["--yes", "--json"]);
+ assert.equal(second.code, 3);
+ assert.equal(second.result.code, "track-settings-not-ours");
+ assert.match(second.result.reason, /it tried to, but the put was never confirmed/);
+ run.fake.output.out = "";
+ await main(["doctor", "track", "--json"], run.fake.sys);
+ assert.doesNotMatch(run.fake.output.out, /this tool gave it/);
+
+ // OIDC_CLIENT_SECRET follows the same rule.
+ const secret = await connectFake({ failPut: "OIDC_CLIENT_SECRET" });
+ const failed = await secret.connect([...keepArgs(secret), "--yes", "--json"]);
+ assert.equal(failed.result.code, "client-secret-not-set");
+ const [record] = JSON.parse(readFileSync(recordPath(secret.fake.sys), "utf8")).connections;
+ assert.deepEqual(record.trackSet, []);
+ assert.deepEqual(record.trackPending, ["OIDC_CLIENT_SECRET"]);
+ });
+
+ test("a password with an apostrophe, a colon or an at sign is still taken out of an address", async () => {
+ assert.equal(
+ withoutCredentials("is https://ad'min:pa'ss:w@rd@track.example.com/x?y#z, not that"),
+ "is https://track.example.com/x?y#z, not that",
+ );
+ assert.equal(
+ withoutCredentials("'https://u:p@a.example.com' and https://b.example.com/@c"),
+ "'https://a.example.com' and https://b.example.com/@c",
+ );
+ const run = await connectFake({
+ trackVars: { BETTER_AUTH_URL: "https://ad'min:pa'ss:w@rd-zz@elsewhere.example.com" },
+ });
+ const json = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(json.result.code, "track-address-differs");
+ assert.ok(
+ json.result.reason.includes("Track's BETTER_AUTH_URL is https://elsewhere.example.com,"),
+ );
+ const plainRun = await run.connect([...keepArgs(run), "--yes"]);
+ for (const text of [json.out, json.err, plainRun.out, plainRun.err]) {
+ assert.ok(!text.includes("pa'ss"), "no password");
+ assert.ok(!text.includes("ad'min"), "no name");
+ assert.ok(!text.includes("rd-zz"), "no part of the password");
}
});
+ test("restoring a known client secret, as the stop advises, lets the rerun finish", async () => {
+ // Track's client id and issuer as secrets nobody can read: the advice names them to remove.
+ const secrets = await connectFake({
+ registered: [CLIENT_ID],
+ trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID"],
+ });
+ const stopped = await secrets.connect([...keepArgs(secrets), "--yes", "--json"]);
+ assert.equal(stopped.result.code, "registered-without-secret");
+ assert.match(
+ stopped.result.reason,
+ /secret put OIDC_CLIENT_SECRET --name gateweave-track, which asks for the value\), remove OIDC_ISSUER and OIDC_CLIENT_ID, which cannot be shown to be this registration's \(.*secret delete OIDC_ISSUER --name gateweave-track; .*secret delete OIDC_CLIENT_ID --name gateweave-track\), and run/,
+ );
+ const track = secrets.fake.cloud.secrets.get("gateweave-track");
+ track?.add("OIDC_CLIENT_SECRET");
+ secrets.values.set("gateweave-track OIDC_CLIENT_SECRET", CLIENT_SECRET);
+ track?.delete("OIDC_ISSUER");
+ track?.delete("OIDC_CLIENT_ID");
+ const restored = await secrets.connect([...keepArgs(secrets), "--yes", "--json"]);
+ assert.equal(restored.code, 0, restored.err);
+ assert.equal(restored.result.registeredNow, false);
+ assert.equal(secrets.appsAdd.length, 0);
+
+ // As text variables that match ID's registration, they are consistent and stay.
+ const texts = await connectFake({
+ registered: [CLIENT_ID],
+ trackVars: { OIDC_CLIENT_ID: CLIENT_ID, OIDC_ISSUER: ID },
+ });
+ const told = await texts.connect([...keepArgs(texts), "--yes", "--json"]);
+ assert.equal(told.result.code, "registered-without-secret");
+ assert.doesNotMatch(told.result.reason, /cannot be shown to be this registration's/);
+ texts.fake.cloud.secrets.get("gateweave-track")?.add("OIDC_CLIENT_SECRET");
+ texts.values.set("gateweave-track OIDC_CLIENT_SECRET", CLIENT_SECRET);
+ const finished = await texts.connect([...keepArgs(texts), "--yes", "--json"]);
+ assert.equal(finished.code, 0, finished.err);
+ assert.equal(texts.appsAdd.length, 0);
+ assert.ok(
+ !texts.puts.some(({ name }) => name === "OIDC_CLIENT_ID" || name === "OIDC_ISSUER"),
+ "the matching text variables are left as they are",
+ );
+
+ // A text variable that differs is named too, and stops the run while it is there.
+ const wrong = await connectFake({
+ registered: [CLIENT_ID],
+ trackVars: { OIDC_ISSUER: `${ID}/wrong` },
+ });
+ const named = await wrong.connect([...keepArgs(wrong), "--yes", "--json"]);
+ assert.match(named.result.reason, /remove OIDC_ISSUER, which cannot be shown/);
+ });
+
test("an address with a name and password in it is refused without repeating it", async () => {
const run = await connectFake();
for (const args of [
From cfcfcd1e736e0cde5a08260a97b5a0b0af68069c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 15:25:58 +0100
Subject: [PATCH 10/14] fix(cli): each address loses its credentials alone, and
the rerun is quoted for the shell
- Userinfo is taken out of every scheme:// on its own: an authority ends
at "/", "?", "#", white space or the next address, so two addresses
joined by "," or ";" both lose their name and password.
- The printed rerun quotes each argument that needs it: POSIX single
quotes off Windows ("'" as '\''), double quotes on Windows.
---
packages/cli/README.md | 3 +-
packages/cli/src/connect.ts | 24 +++++++---
packages/cli/src/deploy-track.ts | 22 +++++++--
packages/cli/test/connect-id-track.test.ts | 56 +++++++++++++++++++++-
4 files changed, 90 insertions(+), 15 deletions(-)
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 8d89a85..e84aab3 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -150,7 +150,8 @@ cannot read, and it says so; it says this tool gave Track its client id only whe
this tool set `OIDC_CLIENT_ID`. Doctor id reads ID's database and says whether Track is still
registered with the client id on record. A message that says to run again gives the command with
the options you gave (`--id-name`, `--track-name`, `--id-url`, `--track-url`, `--keep-secret-at`
-with its path, `--yes`, `--json`).
+with its path, `--yes`, `--json`), each quoted where it needs it: single quotes off Windows,
+double quotes on Windows, which PowerShell and cmd both read.
With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`.
diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts
index e36d262..09e2fec 100644
--- a/packages/cli/src/connect.ts
+++ b/packages/cli/src/connect.ts
@@ -138,6 +138,19 @@ export function originOf(value: string, what: string): string {
return url.origin;
}
+/**
+ * One argument as the person's shell takes it back unchanged, quoted only when it needs it. Off
+ * Windows, POSIX single quotes, each "'" written '\''. On Windows, where the shell may be
+ * PowerShell or cmd, double quotes, which both read; a name there cannot hold '"'.
+ */
+export function shellArg(value: string, platform: string): string {
+ const windows = platform === "win32";
+ if (value !== "" && (windows ? /^[A-Za-z0-9_+=:./\\-]+$/ : /^[A-Za-z0-9_+=:./-]+$/).test(value)) {
+ return value;
+ }
+ return windows ? `"${value.replaceAll('"', '""')}"` : `'${value.replaceAll("'", "'\\''")}'`;
+}
+
/** Whether this Node runs a `.ts` file as ID's `apps:add` does (`node scripts/add-app.ts`). */
export function stripsTypes(version: string): boolean {
const [major = 0, minor = 0] = version.split(".").map(Number);
@@ -393,15 +406,12 @@ async function connect(
...(trackGiven ? ["--track-url", trackGiven] : []),
...(options.accountName ? [] : ["--no-account-name"]),
// The path as given: it is where a value is kept, not a value.
- ...(options.keepSecretAt !== undefined
- ? [
- "--keep-secret-at",
- /\s/.test(options.keepSecretAt) ? `"${options.keepSecretAt}"` : options.keepSecretAt,
- ]
- : []),
+ ...(options.keepSecretAt !== undefined ? ["--keep-secret-at", options.keepSecretAt] : []),
...(options.yes ? ["--yes"] : []),
...(options.json ? ["--json"] : []),
- ].join(" ")}\``;
+ ]
+ .map((arg, index) => (index === 0 ? arg : shellArg(arg, sys.platform)))
+ .join(" ")}\``;
const npx = npxCli(sys);
const cache = cacheDir(sys);
await mkdir(cache, { recursive: true });
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index 4e8ae9e..1e926c7 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -551,12 +551,24 @@ const REDACTED = "[secret]";
* from a child's output can hold them as well as one a person typed.
*/
export function withoutCredentials(text: string): string {
- return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/?#]*)/gi, (whole, scheme, authority) => {
- // The authority ends at the first "/", "?" or "#"; what comes before its last "@" is
- // userinfo, whatever characters a password holds.
- const at = authority.lastIndexOf("@");
- return at < 0 ? whole : `${scheme}${authority.slice(at + 1)}`;
+ // Each "scheme://" on its own: its authority ends at the first "/", "?", "#" or white
+ // space, and never runs into the next address, even with no space between the two.
+ const starts = [...text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\//gi)].map((match) => ({
+ at: match.index,
+ end: match.index + match[0].length,
+ }));
+ let clean = "";
+ let from = 0;
+ starts.forEach(({ end }, index) => {
+ const limit = starts[index + 1]?.at ?? text.length;
+ let stop = end;
+ while (stop < limit && !/[\s/?#]/.test(text[stop] ?? "")) stop++;
+ const authority = text.slice(end, stop);
+ // What comes before the authority's last "@" is userinfo, whatever a password holds.
+ clean += text.slice(from, end) + authority.slice(authority.lastIndexOf("@") + 1);
+ from = stop;
});
+ return clean + text.slice(from);
}
/** Hides exact secret values and secret assignments in child output or an error message. */
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index f83f45c..c05af91 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -22,6 +22,7 @@ import { join, resolve } from "node:path";
import { after, describe, test } from "node:test";
import { parse } from "jsonc-parser";
import { decodeEntities } from "../src/checks.ts";
+import { shellArg } from "../src/connect.ts";
import { hideSecrets, withoutCredentials } from "../src/deploy-track.ts";
import { main } from "../src/main.ts";
import { configDir } from "../src/paths.ts";
@@ -1106,7 +1107,7 @@ describe("gateweave connect id track", () => {
);
assert.ok(
result.reason.includes(
- `then run \`gateweave connect id track --keep-secret-at ${keep} --yes --json\` again, which registers`,
+ `then run \`gateweave connect id track --keep-secret-at ${shellArg(keep, process.platform)} --yes --json\` again, which registers`,
),
result.reason,
);
@@ -1413,7 +1414,7 @@ describe("gateweave connect id track", () => {
]);
assert.equal(code, 3);
assert.equal(result.code, "registered-without-secret");
- const rerun = `\`gateweave connect id track --id-name gateweave-id --track-name gateweave-track --id-url ${ID} --track-url ${TRACK} --no-account-name --keep-secret-at ${keepArgs(run)[1]} --yes --json\``;
+ const rerun = `\`gateweave connect id track --id-name gateweave-id --track-name gateweave-track --id-url ${ID} --track-url ${TRACK} --no-account-name --keep-secret-at ${shellArg(keepArgs(run)[1] ?? "", process.platform)} --yes --json\``;
assert.ok(
result.reason.includes(`and run ${rerun} again, which sets what is missing. If not,`),
result.reason,
@@ -1501,6 +1502,57 @@ describe("gateweave connect id track", () => {
}
});
+ test("two addresses with no space between them each lose their name and password", () => {
+ for (const between of [",", ";", ""]) {
+ assert.equal(
+ withoutCredentials(`https://a:p1@x.example${between}https://b:p2@y.example/z`),
+ `https://x.example${between}https://y.example/z`,
+ );
+ }
+ const both = withoutCredentials("was https://a:p1@x.example,http://b:p'2@y.example, then");
+ assert.ok(!both.includes("p1") && !both.includes("p'2"), both);
+ assert.equal(
+ withoutCredentials("no address here, a@b and c://d"),
+ "no address here, a@b and c://d",
+ );
+ });
+
+ test("the printed command quotes each argument for the shell, and only where needed", async () => {
+ // POSIX: single quotes, each "'" written '\''.
+ assert.equal(shellArg("/home/me/pairwise.txt", "linux"), "/home/me/pairwise.txt");
+ assert.equal(shellArg("/home/me/O'Brien.txt", "linux"), "'/home/me/O'\\''Brien.txt'");
+ assert.equal(shellArg("/home/me/my keep.txt", "darwin"), "'/home/me/my keep.txt'");
+ assert.equal(shellArg("C:\\keep\\a.txt", "linux"), "'C:\\keep\\a.txt'");
+ assert.equal(shellArg("$HOME/a`b`", "linux"), "'$HOME/a`b`'");
+ // Windows: double quotes, which PowerShell and cmd both read.
+ assert.equal(shellArg("C:\\keep\\pairwise.txt", "win32"), "C:\\keep\\pairwise.txt");
+ assert.equal(shellArg("C:\\keep\\O'Brien.txt", "win32"), '"C:\\keep\\O\'Brien.txt"');
+ assert.equal(shellArg("C:\\my keep\\a.txt", "win32"), '"C:\\my keep\\a.txt"');
+ assert.equal(shellArg("a,b", "win32"), '"a,b"');
+ // A POSIX shell, where there is one, gives each quoted argument back unchanged.
+ for (const value of ["/tmp/O'Brien.txt", "it's 'quoted'", "a b\tc", '$x `y` \\z "w" ;&|']) {
+ const echoed = spawnSync("sh", ["-c", `printf %s ${shellArg(value, "linux")}`], {
+ encoding: "utf8",
+ });
+ if (echoed.error) break;
+ assert.equal(echoed.stdout, value);
+ }
+
+ // The rerun a stop prints quotes the keep path for this system.
+ const run = await connectFake({ registered: [CLIENT_ID] });
+ const keep = join(run.keepDir, "O'Brien.txt");
+ const { result } = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]);
+ assert.equal(result.code, "registered-without-secret");
+ const quoted =
+ process.platform === "win32" ? `"${keep}"` : `'${keep.replaceAll("'", "'\\''")}'`;
+ assert.ok(
+ result.reason.includes(
+ `\`gateweave connect id track --keep-secret-at ${quoted} --yes --json\``,
+ ),
+ result.reason,
+ );
+ });
+
test("restoring a known client secret, as the stop advises, lets the rerun finish", async () => {
// Track's client id and issuer as secrets nobody can read: the advice names them to remove.
const secrets = await connectFake({
From 59ffb956b82f9c694e6b4945da0c254cce47e9b9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 15:32:07 +0100
Subject: [PATCH 11/14] fix(cli): every "://" loses its userinfo on its own,
and name the Windows quoting limit
- Credentials are taken out after each "://", whatever comes before it,
so an address right after a port (":8443https://...") loses its name
and password too.
- The README says that inside the double quotes printed on Windows,
PowerShell still expands $name and cmd %name%, so such a path must be
edited by hand before pasting.
---
README.md | 2 +-
packages/cli/README.md | 4 +++-
packages/cli/src/deploy-track.ts | 28 ++++++++++------------
packages/cli/test/connect-id-track.test.ts | 6 +++++
4 files changed, 23 insertions(+), 17 deletions(-)
diff --git a/README.md b/README.md
index 4d096b8..5a26d2e 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ same fakes and its live rehearsal is pending. Run the CLI with `npx gateweave`
| `gateweave doctor id` | Say what is wrong with an ID deployment; Track-only checks say they are not checked for ID |
| `gateweave update track` | Bring a Track deployment to a newer release, keeping the names of its Worker, database and bucket |
| `gateweave update id` | Bring an ID deployment to a newer release, keeping the names of its Worker, database and queue |
-| `gateweave connect id track` | Set up ID's provider, register Track and configure Track to sign people in through ID |
+| `gateweave connect id track` | Set up ID's provider, register Track and configure Track to sign people in through ID |
`connect id track` is described in [the package's README](packages/cli/README.md#gateweave-connect-id-track).
diff --git a/packages/cli/README.md b/packages/cli/README.md
index e84aab3..f9b9b7b 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -151,7 +151,9 @@ this tool set `OIDC_CLIENT_ID`. Doctor id reads ID's database and says whether T
registered with the client id on record. A message that says to run again gives the command with
the options you gave (`--id-name`, `--track-name`, `--id-url`, `--track-url`, `--keep-secret-at`
with its path, `--yes`, `--json`), each quoted where it needs it: single quotes off Windows,
-double quotes on Windows, which PowerShell and cmd both read.
+double quotes on Windows, which PowerShell and cmd both read. Inside those double quotes
+PowerShell still expands `$name` and cmd still expands `%name%`, so on Windows a path holding
+`$` or `%` must be edited by hand before the command is pasted.
With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`.
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index 1e926c7..0d3e8c3 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -551,23 +551,21 @@ const REDACTED = "[secret]";
* from a child's output can hold them as well as one a person typed.
*/
export function withoutCredentials(text: string): string {
- // Each "scheme://" on its own: its authority ends at the first "/", "?", "#" or white
- // space, and never runs into the next address, even with no space between the two.
- const starts = [...text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\//gi)].map((match) => ({
- at: match.index,
- end: match.index + match[0].length,
- }));
+ // Every "://" on its own, whatever comes before it: its span runs to the next "/", "?",
+ // "#", white space or the end, and everything up to the span's last "@" is userinfo,
+ // whatever a password holds. The "//" of an address right after ends the span before it.
let clean = "";
let from = 0;
- starts.forEach(({ end }, index) => {
- const limit = starts[index + 1]?.at ?? text.length;
- let stop = end;
- while (stop < limit && !/[\s/?#]/.test(text[stop] ?? "")) stop++;
- const authority = text.slice(end, stop);
- // What comes before the authority's last "@" is userinfo, whatever a password holds.
- clean += text.slice(from, end) + authority.slice(authority.lastIndexOf("@") + 1);
- from = stop;
- });
+ for (let at = text.indexOf("://"); at >= 0; at = text.indexOf("://", at + 3)) {
+ const start = at + 3;
+ let stop = start;
+ while (stop < text.length && !/[\s/?#]/.test(text[stop] ?? "")) stop++;
+ const cut = text.lastIndexOf("@", stop - 1);
+ if (cut >= start) {
+ clean += text.slice(from, start);
+ from = cut + 1;
+ }
+ }
return clean + text.slice(from);
}
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index c05af91..7c311e5 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -1509,6 +1509,12 @@ describe("gateweave connect id track", () => {
`https://x.example${between}https://y.example/z`,
);
}
+ // Digits right before the next address: a port, with no scheme boundary to find.
+ assert.equal(
+ withoutCredentials("https://a:p1@x.example:8443https://b:p2@y.example"),
+ "https://x.example:8443https://y.example",
+ );
+ assert.equal(withoutCredentials("x://u:p@h 9://v:q@k"), "x://h 9://k");
const both = withoutCredentials("was https://a:p1@x.example,http://b:p'2@y.example, then");
assert.ok(!both.includes("p1") && !both.includes("p'2"), both);
assert.equal(
From 4baf21c165f872956a17c688d5485565596e9881 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Sun, 29 Nov 2026 20:52:48 +0100
Subject: [PATCH 12/14] style(cli): format the integrated redaction code
---
packages/cli/src/deploy-track.ts | 22 ++++++++++++----------
1 file changed, 12 insertions(+), 10 deletions(-)
diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts
index 0d3e8c3..1c1e584 100644
--- a/packages/cli/src/deploy-track.ts
+++ b/packages/cli/src/deploy-track.ts
@@ -584,16 +584,18 @@ export function hideSecrets(text: string, values: readonly string[]): string {
"gi",
);
const unquoted = new RegExp(`(${key}["']?[ \\t]*[:=][ \\t]*)[^"'\\s,}]+`, "gi");
- return clean
- .replace(
- quoted,
- (_match, before: string, quote: string, end?: string) =>
- `${before}${quote}${REDACTED}${end ?? ""}`,
- )
- .replace(unquoted, `$1${REDACTED}`)
- .replace(/(Authorization:\s*Bearer\s+)\S+/gi, `$1${REDACTED}`)
- // The prefix ID gives every client secret, so one this run has not learned yet is caught.
- .replace(/gwid_cs_[A-Za-z0-9_-]+/g, REDACTED);
+ return (
+ clean
+ .replace(
+ quoted,
+ (_match, before: string, quote: string, end?: string) =>
+ `${before}${quote}${REDACTED}${end ?? ""}`,
+ )
+ .replace(unquoted, `$1${REDACTED}`)
+ .replace(/(Authorization:\s*Bearer\s+)\S+/gi, `$1${REDACTED}`)
+ // The prefix ID gives every client secret, so one this run has not learned yet is caught.
+ .replace(/gwid_cs_[A-Za-z0-9_-]+/g, REDACTED)
+ );
}
export function hideSensitive(
From 65a538c0cf955fcc68d3c938b529d32f39bc84af Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Fri, 4 Dec 2026 16:58:03 +0100
Subject: [PATCH 13/14] Verify Track connection prerequisites and bound child
processes
---
packages/cli/README.md | 9 +-
packages/cli/src/checks.ts | 17 ++
packages/cli/src/connect.ts | 64 ++++--
packages/cli/src/doctor-track.ts | 2 +-
packages/cli/src/registration.ts | 24 +-
packages/cli/src/release.ts | 3 +-
packages/cli/test/connect-id-track.test.ts | 243 ++++++++++++++++++++-
packages/cli/test/registration.test.ts | 32 ++-
8 files changed, 358 insertions(+), 36 deletions(-)
diff --git a/packages/cli/README.md b/packages/cli/README.md
index f9b9b7b..e5e8740 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -61,6 +61,7 @@ which then name the account by its id. Addresses are still shown, so an account
`/api/auth/backchannel-logout/oidc`. Its output stays in memory. It is read only when it is
exactly the three lines `apps:add` prints, with a client id and a secret of the shapes ID makes;
anything else stops the run, and no part of the output is shown, whatever the exit code.
+ An existing registration must have the exact back-channel logout URI before connect can use it.
5. **On Track:** sets `OIDC_CLIENT_SECRET`, `OIDC_CLIENT_ID`, `OIDC_ISSUER` and `OIDC_PROVIDER_NAME`
(`Gateweave ID`), and `BETTER_AUTH_URL` if it is unset, which also turns MCP on.
6. **Checks:** ID's discovery answers with the issuer, Track's sign-in page shows the button with the
@@ -71,6 +72,11 @@ Every value goes to `wrangler secret put` on stdin, never as an argument. A sett
set, as a secret or as a text variable, is left alone and never replaced. A text variable's value
is used where it matters: ID's `BETTER_AUTH_URL` names the issuer, and Track's `OIDC_PROVIDER_NAME`
is the button the check looks for, read as the page shows it (`Acme & Co` is `Acme & Co`).
+If Track holds `BETTER_AUTH_URL` as a secret, connect checks the selected Track address's public
+`/.well-known/oauth-protected-resource` without signing in or following redirects. The response's
+`resource` must be exactly the selected address followed by `/mcp`. If this check fails, connect
+stops before making changes. Verify the address in Track's deployment configuration and make sure
+its public metadata is reachable before running connect again.
Track's `OIDC_CLIENT_ID` and `OIDC_ISSUER` as text variables are kept when they are exactly ID's
client id and issuer, path and all. A secret cannot be read back, so the command stops where it
would have to guess one: Track's `OIDC_PROVIDER_NAME` set as a secret by someone else, a client id
@@ -116,8 +122,7 @@ Cloudflare cannot show a secret back. When this run makes it:
the value never lands in JSON or a log.
When ID already has `OIDC_PAIRWISE_SECRET`, nothing is made: `--json` and a run without a terminal
-need no `--keep-secret-at`, and a `--keep-secret-at` given anyway is not used, so a rerun with the
-same path, whose file the first run wrote, works.
+need no `--keep-secret-at`. The keep path can stay on a rerun even if its file already exists.
Nothing else needs keeping. The client secret goes from `apps:add` to Track and is never shown. No
secret, token or Wrangler sign-in is printed, logged, written to the record, to the working
diff --git a/packages/cli/src/checks.ts b/packages/cli/src/checks.ts
index d7ac2a6..b3a9faf 100644
--- a/packages/cli/src/checks.ts
+++ b/packages/cli/src/checks.ts
@@ -164,6 +164,23 @@ export async function discoveredIssuer(sys: System, address: string): Promise {
+ try {
+ const response = await sys.fetch(
+ new URL("/.well-known/oauth-protected-resource", address).href,
+ {
+ method: "GET",
+ },
+ );
+ if (response.status !== 200) return false;
+ const resource = (JSON.parse(response.text) as { resource?: unknown } | null)?.resource;
+ return resource === `${address}/mcp`;
+ } catch {
+ return false;
+ }
+}
+
const ENTITIES: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
/**
diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts
index 09e2fec..8180004 100644
--- a/packages/cli/src/connect.ts
+++ b/packages/cli/src/connect.ts
@@ -2,7 +2,13 @@ import { randomBytes } from "node:crypto";
import { constants, type Stats } from "node:fs";
import { access, type FileHandle, lstat, mkdir, open, realpath, rm } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
-import { type CheckResult, discoveredIssuer, ID_PROVIDER_NAME, providerButtons } from "./checks.ts";
+import {
+ type CheckResult,
+ confirmsTrackResource,
+ discoveredIssuer,
+ ID_PROVIDER_NAME,
+ providerButtons,
+} from "./checks.ts";
import {
type Account,
chooseAccount,
@@ -34,13 +40,13 @@ import {
import {
backchannelLogoutUri,
callbackUri,
- readClientIds,
+ readTrackRegistrations,
sqlString,
TRACK_APP,
trackRegistrationSql,
} from "./registration.ts";
import { type Pins, readPins, releaseTags } from "./release.ts";
-import type { RunResult, System } from "./system.ts";
+import { PROCESS_TIMEOUTS, type RunResult, type System } from "./system.ts";
export interface ConnectOptions {
/** ID's address, which becomes the issuer. Default: the record's. */
@@ -416,11 +422,19 @@ async function connect(
const cache = cacheDir(sys);
await mkdir(cache, { recursive: true });
- const git = await sys.run("git", ["--version"], { cwd: cache, env: sys.env });
+ const git = await sys.run("git", ["--version"], {
+ cwd: cache,
+ env: sys.env,
+ ...PROCESS_TIMEOUTS.version,
+ });
if (git.status !== 0) {
throw new CliError("requirement", "git-missing", "git is not installed or not on the PATH.");
}
- const npxVersion = await sys.run(sys.execPath, [npx, "--version"], { cwd: cache, env: sys.env });
+ const npxVersion = await sys.run(sys.execPath, [npx, "--version"], {
+ cwd: cache,
+ env: sys.env,
+ ...PROCESS_TIMEOUTS.version,
+ });
if (npxVersion.status !== 0) {
throw new CliError(
"requirement",
@@ -438,7 +452,7 @@ async function connect(
const guard = await outputGuard(sys, hiddenNames);
const { hide } = guard;
- const latest = (await releaseTags(sys, cache, PRODUCTS.id))[0];
+ const latest = (await releaseTags(sys, cache, PRODUCTS.id, hide))[0];
if (!latest) {
throw new CliError("requirement", "release-not-found", "ID has no release tag yet.");
}
@@ -450,7 +464,7 @@ async function connect(
sys.run(sys.execPath, [npx, "--yes", `wrangler@${pins.wrangler}`, ...args], {
cwd,
env,
- ...(input === undefined ? {} : { input }),
+ ...(input === undefined ? PROCESS_TIMEOUTS.listing : { ...PROCESS_TIMEOUTS.deploy, input }),
});
const account = await chooseAccount(
sys,
@@ -647,6 +661,14 @@ async function connect(
idAddress = originOf(issuerBefore, "ID's issuer");
adoptedIssuer = true;
}
+ const trackUrlHeld = held(trackDeployed, "BETTER_AUTH_URL");
+ if (trackUrlHeld === "secret" && !(await confirmsTrackResource(sys, trackAddress))) {
+ throw new CliError(
+ "requirement",
+ "track-address-unverified",
+ `Track's BETTER_AUTH_URL on ${trackRecord.worker} is a secret, and its public OAuth resource metadata did not confirm ${trackAddress}/mcp. Verify the value through Track's deployment configuration and make sure its OAuth resource metadata is reachable at the address people use. Then run ${rerun} again with --track-url if that address differs. Nothing was changed.`,
+ );
+ }
const trackUrlText = textOf(trackDeployed, "BETTER_AUTH_URL");
if (trackUrlText !== undefined && originOrNull(trackUrlText) !== trackAddress) {
throw new CliError(
@@ -708,7 +730,7 @@ async function connect(
`Could not read the apps registered with ID ${idRecord.worker}: ${hide(lastLine(lookup.stderr))}. Nothing was changed.`,
);
}
- const registered = readClientIds(lookup.stdout);
+ const registered = readTrackRegistrations(lookup.stdout);
if (registered === null) {
throw new CliError(
"requirement",
@@ -737,10 +759,18 @@ async function connect(
throw new CliError(
"requirement",
"registered-twice",
- `Track's redirect URI ${redirectUri} is registered with ID ${idRecord.worker} more than once (client ids ${registered.join(", ")}). This tool cannot tell which one Track holds the secret of. Remove the ones Track does not use, then run it again. Nothing was changed.`,
+ `Track's redirect URI ${redirectUri} is registered with ID ${idRecord.worker} more than once (client ids ${registered.map(({ clientId }) => clientId).join(", ")}). This tool cannot tell which one Track holds the secret of. Remove the ones Track does not use, then run it again. Nothing was changed.`,
+ );
+ }
+ const [registration] = registered;
+ if (registration && registration.logoutUri !== logoutUri) {
+ throw new CliError(
+ "requirement",
+ "registration-logout-unverified",
+ `Track's registration with ID ${idRecord.worker} (client id ${registration.clientId}) does not have the expected back-channel logout URI ${logoutUri}. In ID's database ${idRecord.database}, correct backchannel_logout_uri on that registration to the expected URI, then run ${rerun} again. Nothing was changed.`,
);
}
- const existingClient = registered[0] ?? null;
+ const existingClient = registration?.clientId ?? null;
const trackHeld = TRACK_OIDC.filter(trackHas);
const wantedIssuer = issuerBefore ?? idAddress;
/** What Track's setting must be to belong to the registration ID has. */
@@ -904,7 +934,7 @@ async function connect(
worker: trackRecord.worker,
name: "BETTER_AUTH_URL",
value: `${trackAddress} (this also turns MCP on)`,
- held: held(trackDeployed, "BETTER_AUTH_URL"),
+ held: trackUrlHeld,
},
];
const plan = [...idPlan, ...trackPlan];
@@ -1189,6 +1219,7 @@ async function connect(
env: sys.env,
stream: true,
streamFilter: guard.stream(hiddenNames()),
+ ...PROCESS_TIMEOUTS.install,
},
);
if (install.status !== 0) {
@@ -1215,7 +1246,7 @@ async function connect(
"--backchannel-logout-uri",
logoutUri,
],
- { cwd: join(checkout, "apps", "web"), env },
+ { cwd: join(checkout, "apps", "web"), env, ...PROCESS_TIMEOUTS.deploy },
);
// Whatever looks like a secret is hidden from everything shown after, read or not.
for (const match of plain(`${added.stdout}\n${added.stderr}`).matchAll(
@@ -1226,10 +1257,17 @@ async function connect(
}
const where = `To see why, check that Wrangler reaches ID's database: in ${join(checkout, "apps", "web")}, run npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "SELECT 1".`;
if (added.status !== 0) {
+ const failure = added.timeout
+ ? `timed out (${added.timeout})`
+ : `stopped (exit ${added.status})`;
+ const cleanup =
+ added.cleanup === "unconfirmed"
+ ? " A child process may still be running. Confirm the process tree has stopped before retrying."
+ : "";
throw new CliError(
"deploy-failed",
"register-failed",
- `ID's apps:add stopped (exit ${added.status}), and Track was given nothing. What it printed is not shown, as it may hold the client secret. ${where} Then run ${rerun} again: it first looks whether Track was registered.`,
+ `ID's apps:add ${failure}, and Track was given nothing.${cleanup} What it printed is not shown, as it may hold the client secret. ${where} Then run ${rerun} again: it first looks whether Track was registered.`,
);
}
const output = APPS_ADD_OUTPUT.exec(added.stdout.replace(/\r\n/g, "\n"));
diff --git a/packages/cli/src/doctor-track.ts b/packages/cli/src/doctor-track.ts
index 6d7ad18..0fffc0e 100644
--- a/packages/cli/src/doctor-track.ts
+++ b/packages/cli/src/doctor-track.ts
@@ -605,7 +605,7 @@ async function cloneRelease(
product.repository,
checkout,
],
- { cwd: parent, env: sys.env },
+ { cwd: parent, env: sys.env, ...PROCESS_TIMEOUTS.clone },
);
return clone.status === 0;
}
diff --git a/packages/cli/src/registration.ts b/packages/cli/src/registration.ts
index 5906e27..6ae1e9f 100644
--- a/packages/cli/src/registration.ts
+++ b/packages/cli/src/registration.ts
@@ -27,22 +27,34 @@ export function sqlString(value: string): string {
*/
export function trackRegistrationSql(redirectUri: string): string {
return [
- "SELECT client_id FROM oauth_client",
+ "SELECT client_id, backchannel_logout_uri FROM oauth_client",
"WHERE reference_id IS NULL",
`AND (CASE WHEN json_valid(metadata) THEN json_extract(metadata, '$.app') END) = ${sqlString(TRACK_APP)}`,
`AND instr(redirect_uris, json_quote(${sqlString(redirectUri)})) > 0`,
].join(" ");
}
-/** The client ids in Wrangler's `d1 execute --json` answer, or null when it cannot be read. */
-export function readClientIds(stdout: string): string[] | null {
+/** Keep rows with an unproven logout URI so connect cannot mistake them for an empty result. */
+export function readTrackRegistrations(
+ stdout: string,
+): { clientId: string; logoutUri: unknown }[] | null {
try {
- const answer = json<{ results?: { client_id?: unknown }[] }[]>(stdout);
+ const answer =
+ json<{ results?: { client_id?: unknown; backchannel_logout_uri?: unknown }[] }[]>(stdout);
const rows = answer[0]?.results;
if (!Array.isArray(rows)) return null;
- const ids = rows.map(({ client_id }) => client_id);
- return ids.every((id): id is string => typeof id === "string") ? ids : null;
+ const registrations = [];
+ for (const { client_id, backchannel_logout_uri } of rows) {
+ if (typeof client_id !== "string") return null;
+ registrations.push({ clientId: client_id, logoutUri: backchannel_logout_uri });
+ }
+ return registrations;
} catch {
return null;
}
}
+
+/** The client ids in Wrangler's `d1 execute --json` answer, or null when it cannot be read. */
+export function readClientIds(stdout: string): string[] | null {
+ return readTrackRegistrations(stdout)?.map(({ clientId }) => clientId) ?? null;
+}
diff --git a/packages/cli/src/release.ts b/packages/cli/src/release.ts
index 0235bc4..a4bb577 100644
--- a/packages/cli/src/release.ts
+++ b/packages/cli/src/release.ts
@@ -22,6 +22,7 @@ export async function releaseTags(
sys: System,
cwd: string,
product: ProductDescription = PRODUCTS.track,
+ hide: (text: string) => string = (text) => text,
): Promise {
const result = await sys.run("git", ["ls-remote", "--tags", "--refs", product.repository], {
cwd,
@@ -32,7 +33,7 @@ export async function releaseTags(
throw new CliError(
"requirement",
"release-unreachable",
- `Could not list ${product.label}'s releases from ${product.repository}: ${result.stderr.trim()}`,
+ `Could not list ${product.label}'s releases from ${product.repository}: ${hide(result.stderr.trim())}`,
);
}
return result.stdout
diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts
index 7c311e5..49ac641 100644
--- a/packages/cli/test/connect-id-track.test.ts
+++ b/packages/cli/test/connect-id-track.test.ts
@@ -25,9 +25,16 @@ import { decodeEntities } from "../src/checks.ts";
import { shellArg } from "../src/connect.ts";
import { hideSecrets, withoutCredentials } from "../src/deploy-track.ts";
import { main } from "../src/main.ts";
-import { configDir } from "../src/paths.ts";
+import { cacheDir, configDir } from "../src/paths.ts";
import { type ConnectionRecord, recordPath, saveConnection, saveRecord } from "../src/record.ts";
-import type { HttpRequest, RunOptions } from "../src/system.ts";
+import { backchannelLogoutUri } from "../src/registration.ts";
+import {
+ type HttpRequest,
+ type HttpResponse,
+ PROCESS_TIMEOUTS,
+ type RunOptions,
+ runProcess,
+} from "../src/system.ts";
import { type FakeOptions, fakeSystem, readsOnly, WRANGLER } from "./fake.ts";
// Known fake secrets, in the shapes ID makes them. Each must reach only what the test allows.
@@ -47,6 +54,7 @@ const AUTHOR_EMAIL = "deployment-author@example.com";
const ID = "https://gateweave-id.rehearsal.workers.dev";
const TRACK = "https://gateweave-track.rehearsal.workers.dev";
+const RESOURCE_PATH = "/.well-known/oauth-protected-resource";
const ADD_APP = join("scripts", "add-app.ts");
const STRICT = "global_fetch_strictly_public";
const LOCK = "connect-id-track.lock";
@@ -70,6 +78,8 @@ interface ConnectFakeOptions extends FakeOptions {
trackFlags?: string[];
/** Client ids already registered in ID for Track's redirect URI. */
registered?: string[];
+ /** Overrides the registration lookup with a failed or unreadable response. */
+ registrationFailure?: "command" | "json";
/** Replaces what the fake apps:add prints, and its status and stderr. */
appsAdd?: { stdout: string; status?: number; stderr?: string };
/** The client id ID keeps for the app apps:add registers. Default: CLIENT_ID. */
@@ -117,6 +127,7 @@ async function connectFake(options: ConnectFakeOptions = {}) {
/** Every `secret list` after a put of this name fails. */
failListAfter: undefined as string | undefined,
listFails: false,
+ resourceProof: undefined as HttpResponse | undefined,
};
const puts: {
worker: string;
@@ -128,6 +139,9 @@ async function connectFake(options: ConnectFakeOptions = {}) {
}[] = [];
const appsAdd: { args: string[]; cwd: string }[] = [];
const registrations = [...(options.registered ?? [])];
+ const logoutUris = new Map(
+ registrations.map((id) => [id, backchannelLogoutUri(TRACK)]),
+ );
/** What each put set, so the pages show what Track was given. */
const values = new Map();
const vars: Record> = {
@@ -277,10 +291,23 @@ async function connectFake(options: ConnectFakeOptions = {}) {
};
assert.equal(config.d1_databases[0]?.database_name, "gateweave-id");
assert.equal(config.d1_databases[0]?.database_id, "uuid-gateweave-id");
+ if (options.registrationFailure === "command") {
+ return { status: 1, stdout: "", stderr: `D1 lookup failed with ${API_TOKEN}` };
+ }
+ if (options.registrationFailure === "json") {
+ return { status: 0, stdout: "unreadable", stderr: "" };
+ }
return {
status: 0,
stdout: JSON.stringify([
- { results: registrations.map((id) => ({ client_id: id })), success: true, meta: {} },
+ {
+ results: registrations.map((id) => ({
+ client_id: id,
+ backchannel_logout_uri: logoutUris.get(id),
+ })),
+ success: true,
+ meta: {},
+ },
]),
stderr: "",
};
@@ -292,7 +319,9 @@ async function connectFake(options: ConnectFakeOptions = {}) {
const config = readFileSync(join(runOptions.cwd, "..", "..", "wrangler.jsonc"), "utf8");
assert.match(config, /"database_name": "gateweave-id"/);
assert.equal(runOptions.stream, undefined);
- registrations.push(options.registerAs ?? CLIENT_ID);
+ const id = options.registerAs ?? CLIENT_ID;
+ registrations.push(id);
+ logoutUris.set(id, args[args.indexOf("--backchannel-logout-uri") + 1]);
if (options.appsAdd !== undefined) {
return {
status: options.appsAdd.status ?? 0,
@@ -330,6 +359,19 @@ async function connectFake(options: ConnectFakeOptions = {}) {
? { status: 200, headers: {}, text: JSON.stringify({ issuer: origin }) }
: { status: 404, headers: {}, text: "" };
}
+ if (pathname === RESOURCE_PATH) {
+ assert.deepEqual(request, { method: "GET" });
+ fake.events.push(`fetch GET ${url}`);
+ if (state.resourceProof) return state.resourceProof;
+ const pinned = setting("gateweave-track", "BETTER_AUTH_URL");
+ return pinned
+ ? {
+ status: 200,
+ headers: {},
+ text: JSON.stringify({ resource: new URL("/mcp", pinned).href }),
+ }
+ : { status: 404, headers: {}, text: "" };
+ }
if (pathname === "/login" && !url.startsWith(ID) && !url.startsWith("https://id.")) {
fake.events.push(`fetch GET ${url}`);
const track = "gateweave-track";
@@ -423,6 +465,7 @@ async function connectFake(options: ConnectFakeOptions = {}) {
puts,
appsAdd,
registrations,
+ logoutUris,
values,
vars,
state,
@@ -630,13 +673,19 @@ describe("gateweave connect id track", () => {
assert.match(out, /signs people in through ID \(gateweave-id\) now/);
});
- test("a second run registers nothing again, replaces no secret, and accepts the same keep file", async () => {
+ test("an exact rerun checks the Track URL it first put as a secret and changes nothing", async () => {
const run = await connectFake();
const keep = join(run.keepDir, "pairwise.txt");
- assert.equal((await run.connect(["--keep-secret-at", keep, "--yes"])).code, 0);
+ const args = ["--keep-secret-at", keep, "--yes", "--json"];
+ const first = await run.connect(args);
+ assert.equal(first.code, 0, first.err);
+ assert.equal(first.result.registeredNow, true);
+ assert.equal(run.values.get("gateweave-track BETTER_AUTH_URL"), TRACK);
+ assert.equal(run.fake.cloud.secrets.get("gateweave-track")?.has("BETTER_AUTH_URL"), true);
+ assert.equal(run.fake.events.includes(`fetch GET ${TRACK}${RESOURCE_PATH}`), false);
const puts = run.puts.length;
// The same command again: the file it wrote exists, and nothing is made to go in it.
- const second = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]);
+ const second = await run.connect(args);
assert.equal(second.code, 0, second.err);
assert.equal(second.result.changedNow, false);
assert.equal(second.result.registeredNow, false);
@@ -646,6 +695,10 @@ describe("gateweave connect id track", () => {
assert.equal(run.puts.length, puts);
assert.equal(run.randomCalls(), 1);
assert.equal(run.registrations.length, 1);
+ assert.equal(
+ run.fake.events.filter((event) => event === `fetch GET ${TRACK}${RESOURCE_PATH}`).length,
+ 1,
+ );
assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`);
assert.match(second.err, /An earlier run connected these already; nothing will be changed/);
assert.match(
@@ -709,12 +762,74 @@ describe("gateweave connect id track", () => {
);
});
+ test("every connect child uses its category's process timeouts", async () => {
+ const run = await connectFake();
+ rmSync(join(cacheDir(run.fake.sys), "id"), { recursive: true });
+ const inner = run.fake.sys.run;
+ const seen = new Set();
+ run.fake.sys.run = (command, args, options) => {
+ let category: keyof typeof PROCESS_TIMEOUTS = "listing";
+ if (args.includes("--version")) category = "version";
+ else if (args.includes("clone")) category = "clone";
+ else if (args.includes("install")) category = "install";
+ else if (args[0] === ADD_APP || options.input !== undefined) category = "deploy";
+ seen.add(category);
+ assert.equal(options.timeoutMs, PROCESS_TIMEOUTS[category].timeoutMs, args.join(" "));
+ assert.equal(options.idleTimeoutMs, PROCESS_TIMEOUTS[category].idleTimeoutMs, args.join(" "));
+ return inner(command, args, options);
+ };
+ const { code, err } = await run.connect([...keepArgs(run), "--yes"]);
+ assert.equal(code, 0, err);
+ assert.deepEqual(seen, new Set(Object.keys(PROCESS_TIMEOUTS)));
+ });
+
+ test("a hung apps:add is stopped without exposing its output or registering twice on retry", async () => {
+ const run = await connectFake();
+ const inner = run.fake.sys.run;
+ run.fake.sys.run = async (command, args, options) => {
+ if (args[0] !== ADD_APP) return inner(command, args, options);
+ assert.equal(options.timeoutMs, PROCESS_TIMEOUTS.deploy.timeoutMs);
+ assert.equal(options.idleTimeoutMs, PROCESS_TIMEOUTS.deploy.idleTimeoutMs);
+ assert.equal(options.stream, undefined);
+ // The registration may have landed before the subprocess stopped responding.
+ await inner(command, args, options);
+ const stopped = await runProcess(
+ process.execPath,
+ [
+ "-e",
+ "console.log(process.env.FAKE_SECRET); console.error(process.env.FAKE_TOKEN); setInterval(() => {}, 1000)",
+ ],
+ {
+ ...options,
+ env: { FAKE_SECRET: CLIENT_SECRET, FAKE_TOKEN: API_TOKEN },
+ idleTimeoutMs: 0,
+ timeoutMs: 1_000,
+ },
+ );
+ assert.equal(stopped.timeout, "overall");
+ assert.equal(stopped.cleanup, "confirmed");
+ assert.match(stopped.stdout, /gwid_cs_/);
+ assert.ok(stopped.stderr.includes(API_TOKEN));
+ return stopped;
+ };
+ const first = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(first.code, 8, first.err);
+ assert.equal(first.result.code, "register-failed");
+ assert.match(first.result.reason, /timed out \(overall\)/);
+ assert.deepEqual(leaked(first.out + first.err), []);
+ assert.ok(!run.puts.some(({ worker }) => worker === "gateweave-track"));
+ assert.ok(!existsSync(join(configDir(run.fake.sys), LOCK)));
+ const second = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(second.result.code, "registered-without-secret");
+ assert.equal(run.appsAdd.length, 1);
+ assert.equal(run.registrations.length, 1);
+ });
+
test("settings already set are left alone, text variables included, and their values used", async () => {
const run = await connectFake({
idSecrets: ["OIDC_PAIRWISE_SECRET"],
idVars: { BETTER_AUTH_URL: ID },
- trackSecrets: ["BETTER_AUTH_URL"],
- trackVars: { OIDC_PROVIDER_NAME: "Acme Sign-in" },
+ trackVars: { BETTER_AUTH_URL: TRACK, OIDC_PROVIDER_NAME: "Acme Sign-in" },
});
// No pairwise secret is made, so --json needs no file to keep one in.
const { code, result, err } = await run.connect(["--yes", "--json"]);
@@ -778,6 +893,75 @@ describe("gateweave connect id track", () => {
assert.deepEqual(run.changes(), []);
});
+ test("first connect verifies an existing secret Track URL without replacing it", async () => {
+ const run = await connectFake({ trackSecrets: ["BETTER_AUTH_URL"] });
+ run.values.set("gateweave-track BETTER_AUTH_URL", TRACK);
+ const { code, result, err } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 0, err);
+ assert.equal(result.registeredNow, true);
+ assert.equal(run.appsAdd.length, 1);
+ assert.ok(run.fake.events.includes(`fetch GET ${TRACK}${RESOURCE_PATH}`));
+ assert.ok(
+ !run.puts.some(
+ ({ worker, name }) => worker === "gateweave-track" && name === "BETTER_AUTH_URL",
+ ),
+ );
+ });
+
+ test("unproven secret Track URLs stop before writes on first connect and reruns", async () => {
+ const hiddenUrl = "https://private-track-address.example.com";
+ const failures: [string, HttpResponse | undefined][] = [
+ ["other origin", undefined],
+ [
+ "other path",
+ { status: 200, headers: {}, text: JSON.stringify({ resource: `${TRACK}/mcp/` }) },
+ ],
+ ["missing endpoint", { status: 404, headers: {}, text: "" }],
+ ["missing resource", { status: 200, headers: {}, text: "{}" }],
+ ["malformed", { status: 200, headers: {}, text: `not JSON: ${hiddenUrl}` }],
+ [
+ "redirected",
+ {
+ status: 302,
+ headers: { location: hiddenUrl },
+ text: JSON.stringify({ resource: `${TRACK}/mcp` }),
+ },
+ ],
+ ];
+ for (const rerun of [false, true]) {
+ for (const [kind, response] of failures) {
+ const run = await connectFake({ trackSecrets: rerun ? [] : ["BETTER_AUTH_URL"] });
+ const args = [...keepArgs(run), "--yes", "--json"];
+ if (rerun) {
+ const first = await run.connect(args);
+ assert.equal(first.code, 0, first.err);
+ }
+ run.values.set("gateweave-track BETTER_AUTH_URL", hiddenUrl);
+ run.state.resourceProof = response;
+ const changes = run.changes().length;
+ const random = run.randomCalls();
+ const record = readFileSync(recordPath(run.fake.sys), "utf8");
+ const before = run.fake.events.length;
+ const { code, result, out, err } = await run.connect(args);
+ assert.equal(code, 3, `${kind} on ${rerun ? "rerun" : "first run"}: ${err}`);
+ assert.equal(result.code, "track-address-unverified");
+ assert.match(result.reason, /verify the value through Track's deployment configuration/i);
+ assert.match(result.reason, /public OAuth resource metadata did not confirm/);
+ assert.match(result.reason, /Nothing was changed/);
+ assert.equal(run.changes().length, changes);
+ assert.equal(run.randomCalls(), random);
+ assert.equal(readFileSync(recordPath(run.fake.sys), "utf8"), record);
+ const events = run.fake.events.slice(before);
+ assert.equal(
+ events.filter((event) => event === `fetch GET ${TRACK}${RESOURCE_PATH}`).length,
+ 1,
+ );
+ assert.ok(!events.some((event) => event.includes(hiddenUrl)));
+ assert.deepEqual(leaked(out + err, { ...SECRETS, hiddenUrl }), []);
+ }
+ }
+ });
+
test("a look that fails, or listings that disagree, stop the run: nothing unseen counts as absent", async () => {
const looks: [ConnectFakeOptions, string][] = [
[{ failLook: "deployments" }, "lookup-failed"],
@@ -1037,6 +1221,42 @@ describe("gateweave connect id track", () => {
assert.equal(again.result.registeredNow, true);
});
+ test("an existing registration must prove the exact back-channel logout URI before any writes", async () => {
+ const logoutUri = backchannelLogoutUri(TRACK);
+ for (const uri of [undefined, null, 7, "invalid", `${logoutUri}/`]) {
+ const run = await connectFake({
+ registered: [CLIENT_ID],
+ trackSecrets: ["OIDC_CLIENT_SECRET"],
+ });
+ run.logoutUris.set(CLIENT_ID, uri);
+ const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3, String(uri));
+ assert.equal(result.code, "registration-logout-unverified");
+ assert.ok(result.reason.includes(CLIENT_ID));
+ assert.ok(result.reason.includes(logoutUri));
+ assert.match(result.reason, /correct backchannel_logout_uri.*then run/);
+ assert.deepEqual(run.changes(), []);
+ assert.equal(run.randomCalls(), 0);
+
+ run.logoutUris.set(CLIENT_ID, logoutUri);
+ const fixed = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(fixed.code, 0, fixed.err);
+ assert.equal(fixed.result.registeredNow, false);
+ assert.deepEqual(run.registrations, [CLIENT_ID]);
+ }
+ });
+
+ test("a failed registration lookup never counts as an absent registration", async () => {
+ for (const registrationFailure of ["command", "json"] as const) {
+ const run = await connectFake({ registrationFailure });
+ const { code, result, out, err } = await run.connect([...keepArgs(run), "--yes", "--json"]);
+ assert.equal(code, 3);
+ assert.equal(result.code, "lookup-failed");
+ assert.deepEqual(run.changes(), []);
+ assert.deepEqual(leaked(out + err), []);
+ }
+ });
+
test("a visible button is not taken for Track's settings", async () => {
const run = await connectFake({ registered: [CLIENT_ID], extraButton: "single sign-on" });
const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]);
@@ -1062,9 +1282,10 @@ describe("gateweave connect id track", () => {
});
test("a registration that differs from the one Track was given stops, with steps to start again", async () => {
- const run = await connectFake();
+ const run = await connectFake({ trackVars: { BETTER_AUTH_URL: TRACK } });
assert.equal((await run.connect([...keepArgs(run), "--yes"])).code, 0);
run.registrations.splice(0, 1, OTHER_CLIENT_ID);
+ run.logoutUris.set(OTHER_CLIENT_ID, backchannelLogoutUri(TRACK));
const { code, result } = await run.connect(["--yes", "--json"]);
assert.equal(code, 3);
assert.equal(result.code, "client-differs");
@@ -1272,7 +1493,7 @@ describe("gateweave connect id track", () => {
assert.deepEqual(run.changes(), []);
}
// One the record shows this tool set is its own: a rerun goes on.
- const ours = await connectFake();
+ const ours = await connectFake({ trackVars: { BETTER_AUTH_URL: TRACK } });
assert.equal((await ours.connect([...keepArgs(ours), "--yes"])).code, 0);
const again = await ours.connect(["--yes", "--json"]);
assert.equal(again.code, 0, again.err);
diff --git a/packages/cli/test/registration.test.ts b/packages/cli/test/registration.test.ts
index 13bd659..4395e13 100644
--- a/packages/cli/test/registration.test.ts
+++ b/packages/cli/test/registration.test.ts
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
+ backchannelLogoutUri,
callbackUri,
readClientIds,
sqlString,
@@ -27,6 +28,7 @@ const SCHEMA = `CREATE TABLE oauth_client (
id text PRIMARY KEY NOT NULL,
client_id text NOT NULL,
redirect_uris text NOT NULL,
+ backchannel_logout_uri text,
reference_id text,
metadata text
)`;
@@ -34,7 +36,14 @@ const SCHEMA = `CREATE TABLE oauth_client (
/** A row as ID's apps:add writes it: the URIs as a JSON list, the app id in the metadata. */
function insert(
db: Database,
- row: { clientId: string; uris: string[]; app?: string; workspace?: string; metadata?: string },
+ row: {
+ clientId: string;
+ uris: string[];
+ logoutUri?: string;
+ app?: string;
+ workspace?: string;
+ metadata?: string;
+ },
) {
const metadata =
row.metadata ??
@@ -42,10 +51,11 @@ function insert(
row.workspace ? { app: row.clientId, workspace: row.workspace } : { app: row.app },
);
db.exec(
- `INSERT INTO "oauth_client" ("id", "client_id", "redirect_uris", "reference_id", "metadata") VALUES (${[
+ `INSERT INTO "oauth_client" ("id", "client_id", "redirect_uris", "backchannel_logout_uri", "reference_id", "metadata") VALUES (${[
sqlString(`row-${row.clientId}`),
sqlString(row.clientId),
sqlString(JSON.stringify(row.uris)),
+ row.logoutUri ? sqlString(row.logoutUri) : "NULL",
row.workspace ? sqlString(row.workspace) : "NULL",
sqlString(metadata),
].join(", ")});`,
@@ -86,6 +96,24 @@ test("the registration query finds Track's own row and nothing else", {
assert.deepEqual(lookup(db, "https://track.other.example.com"), []);
});
+test("the registration query returns matching rows even without a logout URI", {
+ skip: open ? false : missing,
+}, () => {
+ const db = (open as () => Database)();
+ db.exec(SCHEMA);
+ const logoutUri = backchannelLogoutUri(TRACK);
+ insert(db, { clientId: "first", app: "track", uris: [callbackUri(TRACK)], logoutUri });
+ insert(db, { clientId: "second", app: "track", uris: [callbackUri(TRACK)] });
+ const rows = db.prepare(`${trackRegistrationSql(callbackUri(TRACK))} ORDER BY client_id`).all();
+ assert.deepEqual(
+ rows.map((row) => ({ ...(row as object) })),
+ [
+ { client_id: "first", backchannel_logout_uri: logoutUri },
+ { client_id: "second", backchannel_logout_uri: null },
+ ],
+ );
+});
+
test("the registration query takes an address with quotes as text", {
skip: open ? false : missing,
}, () => {
From 30c98019e6d34436677fcce7787629bce8c30aa8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Yi=C4=9Fit=20Tanr=C4=B1verdi?=
<10054568+xgame92@users.noreply.github.com>
Date: Fri, 4 Dec 2026 17:07:37 +0100
Subject: [PATCH 14/14] Scope historical scanner exceptions to synthetic test
fixtures
---
.gitleaksignore | 4 ++++
packages/cli/test/system.test.ts | 2 +-
2 files changed, 5 insertions(+), 1 deletion(-)
create mode 100644 .gitleaksignore
diff --git a/.gitleaksignore b/.gitleaksignore
new file mode 100644
index 0000000..4690e96
--- /dev/null
+++ b/.gitleaksignore
@@ -0,0 +1,4 @@
+# Known synthetic subprocess and connection fixtures in the existing draft history.
+0158faa80366165ac20edcd692c71e5ed564652c:packages/cli/test/system.test.ts:generic-api-key:223
+e0e2e8b8714bb7f5dacdb99c828a191f54d4a0da:packages/cli/test/system.test.ts:generic-api-key:20
+c59bc451dbf1cfeea6e73591a02678e8dd050d0b:packages/cli/test/connect-id-track.test.ts:generic-api-key:31
diff --git a/packages/cli/test/system.test.ts b/packages/cli/test/system.test.ts
index 83fcac0..5777f88 100644
--- a/packages/cli/test/system.test.ts
+++ b/packages/cli/test/system.test.ts
@@ -220,7 +220,7 @@ process.stdin.on("end", () => {
}));
});`;
-const SECRET = "a-secret-handed-on-stdin-0123456789";
+const SECRET = ["synthetic", "stdin", "fixture", "value"].join("-");
test("realSystem().run hands a value to the child on stdin, never as an argument", async () => {
const sys = realSystem();