Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/canonical-awaiting-input.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@onkernel/managed-auth-react": minor
---

Prefer canonical managed-auth fields and choices when present, bind submissions to their interaction IDs, refresh stale interactions, and retain legacy rendering and submission fallbacks during the deprecation window.
3 changes: 3 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ jobs:
- name: Typecheck
run: bun run typecheck

- name: Test
run: bun run test

# Dry-run npm pack so we catch missing files / bad exports BEFORE a
# tagged release tries to publish. Exits non-zero if e.g. dist/ is
# missing from `files` or an export points at a non-existent path.
Expand Down
5 changes: 5 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"build": "bun run --filter '*' build",
"dev": "bun run --filter '*' dev",
"typecheck": "bun run --filter '*' typecheck",
"test": "bun test",
"lint": "bun run --filter '*' lint",
"format": "prettier --write \"**/*.{ts,tsx,js,json,md,css}\"",
"format:check": "prettier --check \"**/*.{ts,tsx,js,json,md,css}\"",
Expand All @@ -18,6 +19,7 @@
"devDependencies": {
"@changesets/changelog-github": "0.7.0",
"@changesets/cli": "^2.27.0",
"@types/bun": "1.2.21",
"@types/node": "^20",
"prettier": "^3.3.0",
"typescript": "^5.6.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function getMFAIcon(type: MFAType) {
interface ExternalActionWaitingProps {
message?: string | null;
mfaOptions?: MFAOption[];
onMFASelect?: (mfaType: MFAType) => void;
onMFASelect?: (mfaType: MFAType, choiceId?: string) => void;
isLoading?: boolean;
}

Expand Down Expand Up @@ -91,11 +91,11 @@ export function ExternalActionWaiting({
<div className="kma-external-action__alternatives">
{mfaOptions.map((option, idx) => (
<Button
key={idx}
key={option.id ?? `${option.type}:${idx}`}
variant="secondary"
slotKey="mfaOption"
className="kma-option"
onClick={() => onMFASelect(option.type)}
onClick={() => onMFASelect(option.type, option.id)}
disabled={isLoading}
>
<span
Expand Down
16 changes: 16 additions & 0 deletions packages/managed-auth-react/src/components/UnifiedAuthForm.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, test } from "bun:test";
import { getAutocomplete } from "./UnifiedAuthForm";

describe("getAutocomplete", () => {
test("uses the canonical field ref for username autocomplete", () => {
expect(
getAutocomplete({
id: "field_opaque",
ref: "username",
name: "field_opaque",
label: "Username",
type: "text",
}),
).toBe("username");
});
});
19 changes: 12 additions & 7 deletions packages/managed-auth-react/src/components/UnifiedAuthForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ interface UnifiedAuthFormProps {
signInOptions?: SignInOption[];
onSubmitFields: (credentials: Record<string, string>) => void;
onSSOClick: (ssoButton: SSOButton) => void;
onMFASelect: (mfaType: MFAType) => void;
onMFASelect: (mfaType: MFAType, choiceId?: string) => void;
onSignInOptionSelect: (optionId: string) => void;
isLoading?: boolean;
errorMessage?: string | null;
Expand Down Expand Up @@ -76,8 +76,8 @@ function getInputType(field: DiscoveredField): string {
}
}

function getAutocomplete(field: DiscoveredField): string | undefined {
const name = field.name.toLowerCase();
export function getAutocomplete(field: DiscoveredField): string | undefined {
const identity = (field.ref ?? field.name).toLowerCase();
switch (field.type) {
case "email":
return "email";
Expand All @@ -89,7 +89,7 @@ function getAutocomplete(field: DiscoveredField): string | undefined {
case "totp":
return "one-time-code";
default:
if (name.includes("user") || name.includes("identifier"))
if (identity.includes("user") || identity.includes("identifier"))
return "username";
return undefined;
}
Expand Down Expand Up @@ -124,12 +124,17 @@ export function UnifiedAuthForm({
const hasSignIn = signInOptions.length > 0;

const onlySignIn = hasSignIn && !hasMFA && !hasFields && !hasSSO;
const onlyAccounts =
onlySignIn && signInOptions.every((option) => option.type === "account");
const onlyMFA = hasMFA && !hasSignIn && !hasFields && !hasSSO;

let title: ReactNode;
let subtitle: string | undefined;

if (onlySignIn) {
if (onlyAccounts) {
title = l.accountSelectTitle;
subtitle = l.accountSelectSubtitle;
} else if (onlySignIn) {
title = l.signInSelectTitle;
subtitle = l.signInSelectSubtitle;
} else if (onlyMFA) {
Expand Down Expand Up @@ -196,11 +201,11 @@ export function UnifiedAuthForm({
<div className="kma-options">
{sortedMFAOptions.map((option, idx) => (
<Button
key={idx}
key={option.id ?? `${option.type}:${idx}`}
variant="secondary"
slotKey="mfaOption"
className="kma-option"
onClick={() => onMFASelect(option.type)}
onClick={() => onMFASelect(option.type, option.id)}
disabled={isLoading}
>
<span
Expand Down
3 changes: 3 additions & 0 deletions packages/managed-auth-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ export type {
SignInOption,
FlowStatus,
FlowStep,
ManagedAuthChoice,
ManagedAuthChoiceType,
ManagedAuthField,
ManagedAuthResponse,
UIState,
} from "./lib/types";
Expand Down
34 changes: 34 additions & 0 deletions packages/managed-auth-react/src/lib/api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, expect, test } from "bun:test";
import { ManagedAuthApiError, submitManagedAuth } from "./api";

describe("submitManagedAuth", () => {
test("preserves structured API error codes", async () => {
const fetch = async () =>
new Response(
JSON.stringify({
code: "stale_interaction",
message: "Refresh the flow state and try again.",
}),
{ status: 400, headers: { "Content-Type": "application/json" } },
);

try {
await submitManagedAuth(
"connection-id",
"jwt",
{
interaction_id: "mai_previous",
field_values: { field_password: "secret" },
},
{ fetch: fetch as unknown as typeof globalThis.fetch },
);
throw new Error("expected submitManagedAuth to reject");
} catch (error) {
expect(error).toBeInstanceOf(ManagedAuthApiError);
expect((error as ManagedAuthApiError).code).toBe("stale_interaction");
expect((error as ManagedAuthApiError).message).toBe(
"Refresh the flow state and try again.",
);
}
});
});
117 changes: 52 additions & 65 deletions packages/managed-auth-react/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,20 @@ export class ManagedAuthApiError extends Error {
public readonly status: number;
public readonly body: string;
public readonly fatal: boolean;
constructor(message: string, status: number, body: string, fatal = false) {
public readonly code?: string;
constructor(
message: string,
status: number,
body: string,
fatal = false,
code?: string,
) {
super(message);
this.name = "ManagedAuthApiError";
this.status = status;
this.body = body;
this.fatal = fatal;
this.code = code;
}
}

Expand All @@ -34,15 +42,40 @@ function getBaseUrl(options?: ApiClientOptions): string {
return (options?.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
}

async function parseError(response: Response): Promise<string> {
const text = await response.text();
interface ParsedApiError {
message: string;
code?: string;
}

async function parseError(response: Response): Promise<ParsedApiError> {
const body = await response.text();
try {
const parsed = JSON.parse(text);
if (parsed && typeof parsed.message === "string") return parsed.message;
const parsed = JSON.parse(body) as unknown;
if (parsed && typeof parsed === "object") {
const error = parsed as { message?: unknown; code?: unknown };
return {
message:
typeof error.message === "string"
? error.message
: body || response.statusText,
code: typeof error.code === "string" ? error.code : undefined,
};
}
return { message: body || response.statusText };
} catch {
/* fall through */
return { message: body || response.statusText };
}
return text || response.statusText;
}

async function responseError(response: Response): Promise<ManagedAuthApiError> {
const error = await parseError(response);
return new ManagedAuthApiError(
error.message,
response.status,
error.message,
false,
error.code,
);
}

export async function exchangeHandoffCode(
Expand All @@ -60,8 +93,7 @@ export async function exchangeHandoffCode(
},
);
if (!res.ok) {
const msg = await parseError(res);
throw new ManagedAuthApiError(msg, res.status, msg);
throw await responseError(res);
}
const data = (await res.json()) as { jwt?: string };
if (!data.jwt) {
Expand All @@ -85,23 +117,26 @@ export async function retrieveManagedAuth(
headers: { Authorization: `Bearer ${jwt}` },
});
if (!res.ok) {
const msg = await parseError(res);
throw new ManagedAuthApiError(msg, res.status, msg);
throw await responseError(res);
}
return (await res.json()) as ManagedAuthResponse;
}

interface SubmitBody {
fields: Record<string, string>;
export interface ManagedAuthSubmitBody {
interaction_id?: string;
field_values?: Record<string, string>;
selected_choice_id?: string;
fields?: Record<string, string>;
sso_button_selector?: string;
sso_provider?: string;
mfa_option_id?: MFAType;
sign_in_option_id?: string;
}

async function submit(
export async function submitManagedAuth(
id: string,
jwt: string,
body: SubmitBody,
body: ManagedAuthSubmitBody,
options?: ApiClientOptions,
): Promise<void> {
const f = getFetch(options);
Expand All @@ -114,57 +149,10 @@ async function submit(
body: JSON.stringify(body),
});
if (!res.ok) {
const msg = await parseError(res);
throw new ManagedAuthApiError(msg, res.status, msg);
throw await responseError(res);
}
}

export function submitFieldValues(
id: string,
jwt: string,
fields: Record<string, string>,
options?: ApiClientOptions,
): Promise<void> {
return submit(id, jwt, { fields }, options);
}

export function submitSSOButton(
id: string,
jwt: string,
selector: string,
options?: ApiClientOptions,
): Promise<void> {
return submit(
id,
jwt,
{ fields: {}, sso_button_selector: selector },
options,
);
}

export function submitMFASelection(
id: string,
jwt: string,
mfaType: MFAType,
options?: ApiClientOptions,
): Promise<void> {
return submit(id, jwt, { fields: {}, mfa_option_id: mfaType }, options);
}

export function submitSignInOption(
id: string,
jwt: string,
signInOptionId: string,
options?: ApiClientOptions,
): Promise<void> {
return submit(
id,
jwt,
{ fields: {}, sign_in_option_id: signInOptionId },
options,
);
}

/** Callbacks for the SSE event stream. */
export interface ManagedAuthStreamHandlers {
onState: (data: ManagedAuthStateEventData) => void;
Expand Down Expand Up @@ -202,8 +190,7 @@ export function streamManagedAuthEvents(
});

if (!res.ok) {
const msg = await parseError(res);
handlers.onError(new ManagedAuthApiError(msg, res.status, msg));
handlers.onError(await responseError(res));
return;
}

Expand Down
Loading
Loading