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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/lib/identity-errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { IDENTITY_CONFLICT_MESSAGES, identityConflictMessage } from "./identity-errors";

describe("identityConflictMessage", () => {
it("resolves the deprecated alias to the exact same text as orcid_in_use", () => {
expect(identityConflictMessage("orcid_already_linked")).toBe(
identityConflictMessage("orcid_in_use"),
);
expect(IDENTITY_CONFLICT_MESSAGES.orcid_already_linked).toBe(
IDENTITY_CONFLICT_MESSAGES.orcid_in_use,
);
});

it("keeps orcid_linked_other a distinct message from orcid_in_use", () => {
expect(IDENTITY_CONFLICT_MESSAGES.orcid_linked_other).not.toBe(
IDENTITY_CONFLICT_MESSAGES.orcid_in_use,
);
});

it("covers email_in_use and github_in_use with their own sentences", () => {
expect(identityConflictMessage("email_in_use")).toMatch(/email address/i);
expect(identityConflictMessage("github_in_use")).toMatch(/GitHub/);
expect(IDENTITY_CONFLICT_MESSAGES.email_in_use).not.toBe(
IDENTITY_CONFLICT_MESSAGES.github_in_use,
);
});

it("every message names the self-service fix in Settings", () => {
for (const message of Object.values(IDENTITY_CONFLICT_MESSAGES)) {
expect(message).toMatch(/settings|sign in/i);
}
});

it("degrades to undefined for an unknown code", () => {
expect(identityConflictMessage("something_else")).toBeUndefined();
expect(identityConflictMessage(null)).toBeUndefined();
expect(identityConflictMessage(undefined)).toBeUndefined();
expect(identityConflictMessage("")).toBeUndefined();
});

it("is prototype-safe: a prototype-polluting key never resolves", () => {
expect(identityConflictMessage("constructor")).toBeUndefined();
expect(identityConflictMessage("toString")).toBeUndefined();
expect(identityConflictMessage("__proto__")).toBeUndefined();
expect(identityConflictMessage("hasOwnProperty")).toBeUndefined();
});
});
67 changes: 67 additions & 0 deletions src/lib/identity-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* User-facing copy for identity-uniqueness refusals (nemar-cli #1254, epic
* #1250, ADR 0043; website#305). Mirrors the wording of
* `shared/contract/identity.ts`'s `IDENTITY_CONFLICT_MESSAGES` on the
* backend -- this repo does not depend on nemar-cli, so the two are kept in
* sync by hand, not by import.
*
* `orcid_already_linked` is a DEPRECATED ALIAS of `orcid_in_use`: both mean
* "this ORCID iD already backs a live NEMAR account", and the only
* difference is which D1 constraint noticed it (`users.orcid` vs. an
* `oauth_identities` row) -- not a distinction a person reading the message
* can act on. It survives only because `POST /auth/orcid/finalize` has
* always returned it and the site used to switch on it directly. Folding it
* into `orcid_in_use` here is what closes website#305; once nemar-cli stops
* emitting the alias, delete this key.
*
* `orcid_linked_other` is a DIFFERENT refusal -- the finished iD belongs to
* a different, already-linked account than the one attempting to link or
* relink -- and keeps its own message. Do not fold it in here.
*/

/** Every wire code this module renders. Keep in sync with the subset of
* `IdentityConflictCode` (shared/contract/identity.ts on nemar-cli) that
* the website actually surfaces; `identity_conflict_remains` is admin-only
* and has no website rendering, so it is intentionally not included. */
export type IdentityConflictCode =
| "orcid_in_use"
| "orcid_already_linked"
| "orcid_linked_other"
| "email_in_use"
| "github_in_use";

const ORCID_IN_USE_MESSAGE =
"That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first in Settings.";

/**
* One sentence per code, each naming the self-service fix on the account
* that already exists (sign in to it, or change/unlink the colliding
* identifier from Settings) -- the same remedy the backend's contract
* documents, never a different one invented here.
*/
export const IDENTITY_CONFLICT_MESSAGES: Readonly<Record<IdentityConflictCode, string>> =
Object.freeze({
orcid_in_use: ORCID_IN_USE_MESSAGE,
// Deprecated alias -- same case, same message. See module comment.
orcid_already_linked: ORCID_IN_USE_MESSAGE,
orcid_linked_other:
"That ORCID iD is linked to a different NEMAR account. Unlink it there first in Settings, then link it here.",
email_in_use:
"That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first in Settings.",
github_in_use:
"That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first in Settings.",
});

/**
* Look up an identity-conflict message by wire code, or `undefined` when the
* code is not one of ours (the caller degrades to its own generic message).
* `Object.hasOwn` guards against prototype keys (`?error=constructor` etc.
* resolving to a function rather than `undefined`) -- the same guard
* login.astro's and settings.astro's own ORCID error maps apply inline
* before indexing. Prefer this helper (or that same guard) over indexing
* `IDENTITY_CONFLICT_MESSAGES` directly with a server-supplied key.
*/
export function identityConflictMessage(code: string | null | undefined): string | undefined {
if (!code || !Object.hasOwn(IDENTITY_CONFLICT_MESSAGES, code)) return undefined;
return IDENTITY_CONFLICT_MESSAGES[code as IdentityConflictCode];
}
31 changes: 21 additions & 10 deletions src/pages/auth/orcid/complete.astro
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ if (!Astro.cookies.has("nemar_orcid_pending")) {
</style>

<script>
import { identityConflictMessage } from "../../../lib/identity-errors";

const form = document.querySelector<HTMLFormElement>("[data-finish-form]");
const emailEl = document.querySelector<HTMLInputElement>("[data-finish-email]");
const cityEl = document.querySelector<HTMLInputElement>("[data-finish-city]");
Expand All @@ -244,19 +246,29 @@ if (!Astro.cookies.has("nemar_orcid_pending")) {
const submitEl = document.querySelector<HTMLButtonElement>("[data-finish-submit]");
const errorEl = document.querySelector<HTMLElement>("[data-finish-error]");

// Values are trusted static strings rendered via innerHTML (one carries an
// <a>). The lookup key `code` is never interpolated into them. Keep every
// value a compile-time constant -- never build one from a server value, or
// this becomes an XSS sink.
const MESSAGES: Record<string, string> = {
email_in_use:
"That email already has a NEMAR account. Sign in with it first, then link ORCID from settings.",
// Codes this page renders that aren't an identity-uniqueness conflict
// (those go through identityConflictMessage below). Values are trusted
// static strings rendered via innerHTML (one carries an <a>); the lookup
// key `code` is never interpolated into them. Keep every value a
// compile-time constant -- never build one from a server value, or this
// becomes an XSS sink. Object.hasOwn guards the lookup below against a
// prototype key (`constructor`, `toString`, ...) resolving to a function
// instead of `undefined` -- the same guard login.astro and settings.astro
// apply to their own ORCID error maps.
const EXTRA_MESSAGES: Record<string, string> = {
orcid_pending_expired:
'Your ORCID session expired. <a href="/auth/orcid/start">Sign in with ORCID</a> again to retry.',
orcid_already_linked: "This ORCID iD is already linked to an account. Try signing in instead.",
invalid_email: "That doesn't look like an email address.",
};

function messageForCode(code: string): string {
return (
identityConflictMessage(code) ??
(Object.hasOwn(EXTRA_MESSAGES, code) ? EXTRA_MESSAGES[code] : undefined) ??
"We couldn't finish creating your account. Try again in a moment."
);
}

if (form && emailEl && cityEl && countryEl && submitEl && errorEl) {
form.addEventListener("submit", async (e) => {
e.preventDefault();
Expand Down Expand Up @@ -290,8 +302,7 @@ if (!Astro.cookies.has("nemar_orcid_pending")) {
} catch {
/* keep "unknown" */
}
errorEl.innerHTML =
MESSAGES[code] ?? "We couldn't finish creating your account. Try again in a moment.";
errorEl.innerHTML = messageForCode(code);
errorEl.hidden = false;
submitEl.disabled = false;
} catch (err) {
Expand Down
6 changes: 5 additions & 1 deletion src/pages/login.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import Base from "../layouts/Base.astro";
import { safeRedirectPath } from "../lib/auth";
import { ORCID_SIGNIN_ENABLED, WEB_SIGNIN_ETA, webSigninEnabled } from "../lib/flags";
import { IDENTITY_CONFLICT_MESSAGES } from "../lib/identity-errors";

const url = new URL(Astro.request.url);
const next = safeRedirectPath(url.searchParams.get("next"));
Expand All @@ -15,7 +16,10 @@ const ERROR_MESSAGES: Record<string, string> = {
orcid_exchange: "We couldn't complete ORCID sign-in. Please try again.",
orcid_error: "Something went wrong during ORCID sign-in. Please try again.",
orcid_unavailable: "ORCID sign-in is temporarily unavailable. Please try again shortly.",
orcid_linked_other: "That ORCID iD is already linked to a different NEMAR account.",
// orcid_in_use / its deprecated alias orcid_already_linked, plus
// email_in_use and github_in_use, share one sentence regardless of which
// backend constraint noticed the collision (website#305).
...IDENTITY_CONFLICT_MESSAGES,
orcid_already_have: "Your account already has a different ORCID iD linked.",
orcid_account: "We couldn't find an active account for that ORCID iD.",
orcid_pending_expired: "Your ORCID sign-in session expired. Please sign in with ORCID again.",
Expand Down
6 changes: 5 additions & 1 deletion src/pages/settings.astro
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
resolveDocsBase,
} from "../lib/docs-base";
import { formatDate } from "../lib/format";
import { IDENTITY_CONFLICT_MESSAGES } from "../lib/identity-errors";

const session = getSession(Astro.locals);
if (!session) {
Expand All @@ -25,7 +26,10 @@ if (!session) {
// carries state.next=/settings). Only known ORCID codes render; anything else
// is ignored rather than shown as a generic scare banner.
const ORCID_ERROR_MESSAGES: Record<string, string> = {
orcid_linked_other: "That ORCID iD is already linked to a different NEMAR account.",
// orcid_in_use / its deprecated alias orcid_already_linked, orcid_linked_other,
// email_in_use, and github_in_use share one sentence regardless of which
// backend constraint noticed the collision (website#305).
...IDENTITY_CONFLICT_MESSAGES,
orcid_already_have:
"Your account already has a different ORCID iD linked. Use Change / re-link to replace it.",
orcid_denied: "The ORCID sign-in was cancelled. Nothing was changed.",
Expand Down
88 changes: 88 additions & 0 deletions test/identity-conflict-pages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* Source-level guards for website#305: every page that can render an
* identity-uniqueness refusal must go through the shared
* `src/lib/identity-errors.ts` mapping, and none of them may branch on the
* deprecated `orcid_already_linked` code as a case distinct from
* `orcid_in_use`.
*
* Astro files have no rendering harness in this repo (page-level checks run
* against a live server via `/browse`, see AGENTS.md), so reading the source
* is the honest cheap check -- same pattern as `test/signin-notice.test.ts`.
*/

import { describe, expect, it } from "vitest";
import COMPLETE_PAGE from "../src/pages/auth/orcid/complete.astro?raw";
import LOGIN_PAGE from "../src/pages/login.astro?raw";
import SETTINGS_PAGE from "../src/pages/settings.astro?raw";

const ALL_PAGES = [
{ name: "login.astro", source: LOGIN_PAGE },
{ name: "settings.astro", source: SETTINGS_PAGE },
{ name: "auth/orcid/complete.astro", source: COMPLETE_PAGE },
];

// login.astro and settings.astro build their whole error-message record at
// module-evaluation time (an Astro frontmatter, not a browser script) and
// already guard every lookup into it with Object.hasOwn before indexing, so
// spreading the shared map straight into that record is safe there.
const SPREAD_PAGES = [
{ name: "login.astro", source: LOGIN_PAGE, importPath: "../lib/identity-errors" },
{ name: "settings.astro", source: SETTINGS_PAGE, importPath: "../lib/identity-errors" },
];

describe("shared identity-conflict mapping is used, not reimplemented", () => {
for (const { name, source, importPath } of SPREAD_PAGES) {
it(`${name} imports IDENTITY_CONFLICT_MESSAGES from the shared module`, () => {
expect(source).toContain(`import { IDENTITY_CONFLICT_MESSAGES } from "${importPath}"`);
});

it(`${name} spreads the shared mapping into its local error-message record`, () => {
expect(source).toMatch(/\.\.\.IDENTITY_CONFLICT_MESSAGES/);
});
}

// complete.astro is a browser <script>: it looks up a code straight from a
// fetch() JSON response, so a plain-object spread indexed without a guard
// (`MESSAGES[code]`) would resolve a prototype key ("constructor",
// "toString", ...) to a function instead of undefined. It must go through
// the exported identityConflictMessage() helper, which applies the
// Object.hasOwn guard internally, rather than reimplementing the guard or
// (worse) indexing the shared map directly.
it("complete.astro imports identityConflictMessage from the shared module", () => {
expect(COMPLETE_PAGE).toContain(
'import { identityConflictMessage } from "../../../lib/identity-errors"',
);
});

it("complete.astro calls identityConflictMessage rather than indexing the map directly", () => {
expect(COMPLETE_PAGE).toMatch(/identityConflictMessage\(/);
expect(COMPLETE_PAGE).not.toMatch(/\.\.\.IDENTITY_CONFLICT_MESSAGES/);
expect(COMPLETE_PAGE).not.toContain("IDENTITY_CONFLICT_MESSAGES[");
});

for (const { name, source } of ALL_PAGES) {
it(`${name} does not branch on the deprecated orcid_already_linked code`, () => {
// The only allowed appearance is inside a comment explaining the fold;
// it must never be used as an object key (`orcid_already_linked:`) or
// a switch/case/equality target, which would reintroduce a second
// branch for what is now one case.
expect(source).not.toMatch(/orcid_already_linked\s*:/);
expect(source).not.toMatch(/["'`]orcid_already_linked["'`]\s*(===|==)/);
expect(source).not.toMatch(/case\s+["'`]orcid_already_linked["'`]/);
});
}

it("login.astro no longer hardcodes its own orcid_linked_other sentence", () => {
// It still renders the code, but the text now comes from the shared map,
// not a locally duplicated string literal.
expect(LOGIN_PAGE).not.toMatch(/orcid_linked_other:\s*"/);
});

it("settings.astro no longer hardcodes its own orcid_linked_other sentence", () => {
expect(SETTINGS_PAGE).not.toMatch(/orcid_linked_other:\s*"/);
});

it("complete.astro no longer hardcodes its own email_in_use sentence", () => {
expect(COMPLETE_PAGE).not.toMatch(/email_in_use:\s*"/);
});
});
Loading