Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,50 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tenantHasModule: vi.fn(),
webConfig: { kwp: { hiveGridTenantId: "tenant-1" } },
}));
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: mocks.tenantHasModule }));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: () => mocks.webConfig }));
import { hasKwpIntegrationModule, KWP_INTEGRATION_MODULE_KEY, requireKwpIntegrationModule } from "./kwpAccess.server";
const CONTEXT = {
tenantId: "tenant-1",
userId: "user-1",
permissions: ["integrations.read", "integrations.connect"],
hasModule: true,
} as const;
beforeEach(() => {
vi.clearAllMocks();
mocks.webConfig.kwp.hiveGridTenantId = "tenant-1";
mocks.tenantHasModule.mockResolvedValue(true);
});
describe("KWP integration access", () => {
it("uses the dedicated subscription-gated kwp_integration feature", async () => {
expect(KWP_INTEGRATION_MODULE_KEY).toBe("kwp_integration");
await expect(hasKwpIntegrationModule(CONTEXT)).resolves.toBe(true);
expect(mocks.tenantHasModule).toHaveBeenCalledWith({
tenantId: "tenant-1",
userId: "user-1",
moduleKey: "kwp_integration",
});
});
it("returns a not-found domain error when the tenant lacks the add-on", async () => {
mocks.tenantHasModule.mockResolvedValueOnce(false);
await expect(requireKwpIntegrationModule(CONTEXT)).rejects.toMatchObject({ status: 404 });
});
it("fails closed before entitlement lookup when the process credentials belong to another tenant", async () => {
mocks.webConfig.kwp.hiveGridTenantId = "tenant-other";
await expect(hasKwpIntegrationModule(CONTEXT)).resolves.toBe(false);
await expect(requireKwpIntegrationModule(CONTEXT)).rejects.toMatchObject({ status: 404 });
expect(mocks.tenantHasModule).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,28 @@
import { featureKeys } from "@hivegrid/entitlements";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import type { IntegrationsRouteContext } from "~/utils/integrations/integrationsAccess.server";
export const KWP_INTEGRATION_MODULE_KEY = featureKeys.kwpIntegration;
export async function hasKwpIntegrationModule(context: IntegrationsRouteContext): Promise<boolean> {
const configuredTenantId = loadRequiredWebConfig().kwp?.hiveGridTenantId?.trim();
if (!configuredTenantId || configuredTenantId !== context.tenantId) return false;
return tenantHasModule({
tenantId: context.tenantId,
userId: context.userId,
moduleKey: KWP_INTEGRATION_MODULE_KEY,
});
}
/** Fail closed with the platform's 404 permission semantics. */
export async function requireKwpIntegrationModule(
context: IntegrationsRouteContext,
): Promise<IntegrationsRouteContext> {
if (!(await hasKwpIntegrationModule(context))) {
throw new CatalogError(foundationErrors.notFound, { module: KWP_INTEGRATION_MODULE_KEY });
}
return context;
}
@@ -0,0 +1,832 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
const mocks = vi.hoisted(() => ({
AppsEngineServiceError: class AppsEngineServiceError extends Error {
readonly messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.name = "AppsEngineServiceError";
this.messageKey = messageKey;
}
},
KwpOidcClientError: class KwpOidcClientError extends Error {
readonly code: string;
readonly diagnosticCode?: string;
constructor(code: string, options?: { diagnosticCode?: string }) {
super(code);
this.name = "KwpOidcClientError";
this.code = code;
this.diagnosticCode = options?.diagnosticCode;
}
},
KwpError: class KwpError extends Error {
readonly code: string;
readonly httpStatus?: number;
constructor(code: string, httpStatus?: number) {
super(code);
this.name = "KwpError";
this.code = code;
this.httpStatus = httpStatus;
}
},
context: { tenantId: "tenant-1", userId: "user-1" } as { tenantId?: string; userId?: string },
executeRaw: vi.fn(async () => 1),
findMany: vi.fn(),
findFirst: vi.fn(),
create: vi.fn(),
updateMany: vi.fn(),
createAuditEvent: vi.fn(async () => undefined),
activateOAuthConnection: vi.fn(async () => undefined),
encryptTenantField: vi.fn(),
decryptTenantField: vi.fn(),
discoverKwpMandants: vi.fn(),
readConfig: vi.fn(),
buildAuthorizationUrl: vi.fn(),
exchangeAuthorizationCode: vi.fn(),
createChallenge: vi.fn(),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: () => mocks.context }));
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.createAuditEvent }));
vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({
encryptTenantField: mocks.encryptTenantField,
decryptTenantField: mocks.decryptTenantField,
}));
vi.mock("@hivegrid/integrations", async (importOriginal) => ({
...(await importOriginal<typeof import("@hivegrid/integrations")>()),
KwpError: mocks.KwpError,
discoverKwpMandants: mocks.discoverKwpMandants,
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (_tenantId: string, callback: (tx: unknown) => Promise<unknown>) =>
callback({
$executeRaw: mocks.executeRaw,
dataConnection: {
findMany: mocks.findMany,
findFirst: mocks.findFirst,
create: mocks.create,
updateMany: mocks.updateMany,
},
}),
}));
vi.mock("~/utils/integrations/appsEngineService.server", () => ({
AppsEngineServiceError: mocks.AppsEngineServiceError,
activateOAuthConnection: mocks.activateOAuthConnection,
}));
vi.mock("./kwpOidcClient.server", () => ({
KwpOidcClientError: mocks.KwpOidcClientError,
readKwpOidcRuntimeConfig: mocks.readConfig,
buildKwpAuthorizationUrl: mocks.buildAuthorizationUrl,
exchangeKwpAuthorizationCode: mocks.exchangeAuthorizationCode,
}));
vi.mock("./kwpOAuthChallenge.server", () => ({
KWP_OAUTH_CHALLENGE_TTL_MS: 10 * 60_000,
createKwpOAuthChallenge: mocks.createChallenge,
}));
import {
beginKwpOAuthConnection,
cancelKwpOAuthConnectionAttempt,
completeKwpOAuthConnection,
finalizeKwpOAuthConnection,
KwpConnectError,
loadKwpMandantSelection,
} from "./KwpConnectionService.server";
const ACCESS_TOKEN = "access-token-sensitive";
const REFRESH_TOKEN = "refresh-token-sensitive";
const CLIENT_SECRET = "client-secret-sensitive";
const TOKEN_EXPIRES_AT = new Date("2099-07-20T13:05:00.000Z");
const PENDING_VERSION = new Date("2026-07-20T12:01:00.000Z");
const PENDING_CIPHERTEXT = "sealed-pending-bundle";
const PREVIOUS_CIPHERTEXT = "sealed-working-credentials";
const RESERVATION_EXPIRES_AT = new Date("2099-07-20T13:10:00.000Z");
const OAUTH_CREDENTIALS = {
accessToken: ACCESS_TOKEN,
refreshToken: REFRESH_TOKEN,
expiresAt: TOKEN_EXPIRES_AT.toISOString(),
issuer: "https://id.kwp-online.de/realms/kwp-federated",
clientId: "_extern-geerkens2",
clientSecret: CLIENT_SECRET,
customerCode: "geerkens2",
scopes: ["openid", "adresse-extern", "archiv-extern", "termin-extern", "vorgang-extern", "aktivitaet-extern", "offline_access"],
} as const;
const AVAILABLE_BUNDLE = {
kind: "kwp_mandant_selection_v2",
previous: null,
oauth: OAUTH_CREDENTIALS,
discovery: {
kind: "available",
options: [
{ id: 1, code: "001", label: "Geerkens GmbH" },
{ id: 2, code: "002", label: "Geerkens Service GmbH" },
],
},
issuedAt: "2026-07-20T12:00:30.000Z",
} as const;
const PREVIOUS_CONNECTION = {
credentialsCiphertext: PREVIOUS_CIPHERTEXT,
connectionStatus: "active",
tokenExpiresAt: "2099-07-20T13:00:00.000Z",
healthMessageKey: "integrations.kwp.health.active",
lastHealthCheck: "2026-07-20T11:59:00.000Z",
createdByUserId: "original-owner",
} as const;
const RESERVATION_BUNDLE = {
kind: "kwp_oauth_reservation_v1",
customerCode: "geerkens2",
previous: PREVIOUS_CONNECTION,
issuedAt: "2099-07-20T13:00:00.000Z",
expiresAt: RESERVATION_EXPIRES_AT.toISOString(),
} as const;
const MANUAL_BUNDLE = {
...AVAILABLE_BUNDLE,
discovery: { kind: "manual" },
} as const;
const RECONNECT_SELECTION_BUNDLE = {
...AVAILABLE_BUNDLE,
previous: PREVIOUS_CONNECTION,
} as const;
const EMPTY_AVAILABLE_BUNDLE = {
...AVAILABLE_BUNDLE,
discovery: { kind: "available", options: [] },
} as const;
const CHALLENGE = {
tenantId: "tenant-1",
tenantSlug: "acme",
userId: "user-1",
connectionId: "connection-1",
connectionVersion: "2026-07-20T12:00:00.000Z",
customerCode: "geerkens2",
state: "a".repeat(64),
nonce: "b".repeat(64),
codeVerifier: "v".repeat(64),
codeChallenge: "c".repeat(43),
createdAt: 1_725_000_000_000,
} as const;
function pendingRow(overrides: Record<string, unknown> = {}) {
return {
id: "connection-1",
updatedAt: PENDING_VERSION,
credentialsCiphertext: PENDING_CIPHERTEXT,
tokenExpiresAt: TOKEN_EXPIRES_AT,
healthMessageKey: "integrations.kwp.health.mandantSelectionRequired",
...overrides,
};
}
function reservationRow(overrides: Record<string, unknown> = {}) {
return pendingRow({
updatedAt: new Date(CHALLENGE.connectionVersion),
tokenExpiresAt: RESERVATION_EXPIRES_AT,
healthMessageKey: "integrations.kwp.health.oauthPending",
...overrides,
});
}
function mockPendingBundle(bundle: unknown = AVAILABLE_BUNDLE): void {
mocks.findFirst.mockResolvedValue(pendingRow());
mocks.decryptTenantField.mockResolvedValue(JSON.stringify(bundle));
}
beforeEach(() => {
vi.clearAllMocks();
mocks.context = { tenantId: "tenant-1", userId: "user-1" };
mocks.findMany.mockResolvedValue([]);
mocks.findFirst.mockResolvedValue(reservationRow());
mocks.create.mockResolvedValue({ id: "connection-1", updatedAt: new Date(CHALLENGE.connectionVersion) });
mocks.updateMany.mockResolvedValue({ count: 1 });
mocks.encryptTenantField.mockResolvedValue(PENDING_CIPHERTEXT);
mocks.decryptTenantField.mockResolvedValue(JSON.stringify(RESERVATION_BUNDLE));
mocks.discoverKwpMandants.mockResolvedValue(AVAILABLE_BUNDLE.discovery.options);
mocks.readConfig.mockReturnValue({ customerCode: "geerkens2", hiveGridTenantId: "tenant-1" });
mocks.buildAuthorizationUrl.mockResolvedValue("https://id.kwp-online.de/auth?state=state");
mocks.createChallenge.mockReturnValue({ payload: CHALLENGE, cookie: "__Host-kwp=challenge; Secure; HttpOnly" });
mocks.exchangeAuthorizationCode.mockResolvedValue({ credentials: OAUTH_CREDENTIALS, tokenExpiresAt: TOKEN_EXPIRES_AT });
});
describe("beginKwpOAuthConnection", () => {
it("requires the entered customer code to match the tenant's provisioned pilot code", async () => {
await expect(beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "other" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "not_configured" })
);
await expect(beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "bad/code" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "not_configured" })
);
expect(mocks.findMany).not.toHaveBeenCalled();
expect(mocks.create).not.toHaveBeenCalled();
});
it("serializes and reserves one pending slot before creating the bound challenge", async () => {
await expect(beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" })).resolves.toEqual({
authorizationUrl: "https://id.kwp-online.de/auth?state=state",
setCookie: "__Host-kwp=challenge; Secure; HttpOnly",
});
expect(mocks.executeRaw).toHaveBeenCalledTimes(1);
expect(mocks.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant-1",
appId: "kwp",
credentialsCiphertext: PENDING_CIPHERTEXT,
connectionStatus: "pending",
healthMessageKey: "integrations.kwp.health.oauthPending",
tokenExpiresAt: expect.any(Date),
createdByUserId: "user-1",
}),
select: { id: true, updatedAt: true },
});
expect(JSON.parse(mocks.encryptTenantField.mock.calls[0]?.[1] as string)).toEqual(
expect.objectContaining({ kind: "kwp_oauth_reservation_v1", customerCode: "geerkens2", previous: null })
);
expect(mocks.createChallenge).toHaveBeenCalledWith(expect.objectContaining({ customerCode: "geerkens2", connectionId: "connection-1" }));
expect(mocks.buildAuthorizationUrl).toHaveBeenCalledWith(expect.objectContaining({ customerCode: "geerkens2" }));
expect(mocks.createAuditEvent).toHaveBeenCalledWith(expect.objectContaining({ action: "INTEGRATION_OAUTH_RESERVE" }));
});
it("invalidates an old pending attempt with an exact new generation before starting another", async () => {
const previousVersion = PENDING_VERSION;
mocks.findMany.mockResolvedValueOnce([{ id: "connection-1", updatedAt: previousVersion, connectionStatus: "pending" }]);
await beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" });
expect(mocks.create).not.toHaveBeenCalled();
const invalidation = mocks.updateMany.mock.calls[0]?.[0];
expect(invalidation).toEqual({
where: expect.objectContaining({
id: "connection-1",
tenantId: "tenant-1",
appId: "kwp",
archivedAt: null,
connectionStatus: "pending",
updatedAt: previousVersion,
}),
data: expect.objectContaining({
credentialsCiphertext: PENDING_CIPHERTEXT,
tokenExpiresAt: expect.any(Date),
connectionStatus: "pending",
healthMessageKey: "integrations.kwp.health.oauthPending",
createdByUserId: "user-1",
updatedAt: expect.any(Date),
}),
});
const nextVersion = invalidation?.data.updatedAt as Date;
expect(nextVersion.getTime()).toBeGreaterThan(previousVersion.getTime());
expect(mocks.createChallenge).toHaveBeenCalledWith(expect.objectContaining({ connectionVersion: nextVersion.toISOString() }));
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({ action: "INTEGRATION_OAUTH_RESERVE", metadata: { appId: "kwp", created: false } })
);
mocks.findFirst.mockResolvedValueOnce(null);
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: previousVersion.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" }));
expect(mocks.activateOAuthConnection).not.toHaveBeenCalled();
});
it("reserves an active slot while preserving its full working snapshot", async () => {
mocks.findMany.mockResolvedValueOnce([{
id: "connection-1",
updatedAt: PENDING_VERSION,
connectionStatus: "active",
credentialsCiphertext: PREVIOUS_CIPHERTEXT,
tokenExpiresAt: new Date(PREVIOUS_CONNECTION.tokenExpiresAt),
healthMessageKey: PREVIOUS_CONNECTION.healthMessageKey,
lastHealthCheck: new Date(PREVIOUS_CONNECTION.lastHealthCheck),
createdByUserId: PREVIOUS_CONNECTION.createdByUserId,
}]);
await beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" });
expect(mocks.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({ connectionStatus: "active", updatedAt: PENDING_VERSION }),
data: expect.objectContaining({
credentialsCiphertext: PENDING_CIPHERTEXT,
connectionStatus: "pending",
healthMessageKey: "integrations.kwp.health.oauthPending",
updatedAt: expect.any(Date),
}),
});
expect(JSON.parse(mocks.encryptTenantField.mock.calls[0]?.[1] as string).previous).toEqual(PREVIOUS_CONNECTION);
});
it("restores the working connection immediately when authorization cannot start", async () => {
mocks.findMany.mockResolvedValueOnce([{
id: "connection-1",
updatedAt: PENDING_VERSION,
connectionStatus: "active",
credentialsCiphertext: PREVIOUS_CIPHERTEXT,
tokenExpiresAt: new Date(PREVIOUS_CONNECTION.tokenExpiresAt),
healthMessageKey: PREVIOUS_CONNECTION.healthMessageKey,
lastHealthCheck: new Date(PREVIOUS_CONNECTION.lastHealthCheck),
createdByUserId: PREVIOUS_CONNECTION.createdByUserId,
}]);
mocks.buildAuthorizationUrl.mockRejectedValueOnce(new Error("provider unavailable"));
await expect(
beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" })
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "authorization_failed" }));
expect(mocks.updateMany).toHaveBeenCalledTimes(2);
expect(mocks.updateMany.mock.calls[1]?.[0]).toEqual(
expect.objectContaining({
data: expect.objectContaining({
credentialsCiphertext: PREVIOUS_CIPHERTEXT,
connectionStatus: "active",
createdByUserId: "original-owner",
}),
})
);
});
it("carries the original active snapshot into a replacement browser attempt", async () => {
mocks.findMany.mockResolvedValueOnce([{
id: "connection-1",
updatedAt: PENDING_VERSION,
connectionStatus: "pending",
credentialsCiphertext: PENDING_CIPHERTEXT,
tokenExpiresAt: RESERVATION_EXPIRES_AT,
healthMessageKey: "integrations.kwp.health.oauthPending",
lastHealthCheck: null,
createdByUserId: "user-1",
}]);
await beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" });
expect(JSON.parse(mocks.encryptTenantField.mock.calls[0]?.[1] as string).previous).toEqual(PREVIOUS_CONNECTION);
});
it("rejects ambiguous rows and a lost attempt-generation CAS", async () => {
mocks.findMany.mockResolvedValueOnce([
{ id: "one", updatedAt: new Date(CHALLENGE.connectionVersion), connectionStatus: "pending" },
{ id: "two", updatedAt: new Date(CHALLENGE.connectionVersion), connectionStatus: "pending" },
]);
await expect(beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "slot_conflict" })
);
mocks.findMany.mockResolvedValueOnce([{ id: "one", updatedAt: PENDING_VERSION, connectionStatus: "pending" }]);
mocks.updateMany.mockResolvedValueOnce({ count: 0 });
await expect(beginKwpOAuthConnection({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", customerCode: "geerkens2" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "slot_conflict" })
);
});
});
describe("completeKwpOAuthConnection", () => {
it("discovers immediately and CAS-stages an encrypted pending bundle without activating", async () => {
await expect(completeKwpOAuthConnection({ callbackParameters: { code: "one-time-code", state: CHALLENGE.state }, challenge: CHALLENGE })).resolves.toEqual({
tenantId: "tenant-1",
tenantSlug: "acme",
connectionId: "connection-1",
});
expect(mocks.discoverKwpMandants).toHaveBeenCalledWith(expect.objectContaining({ accessToken: ACCESS_TOKEN, customerCode: "geerkens2" }));
const plaintext = mocks.encryptTenantField.mock.calls[0]?.[1] as string;
expect(JSON.parse(plaintext)).toEqual(
expect.objectContaining({
kind: "kwp_mandant_selection_v2",
previous: PREVIOUS_CONNECTION,
oauth: expect.objectContaining({ accessToken: ACCESS_TOKEN, refreshToken: REFRESH_TOKEN, clientSecret: CLIENT_SECRET }),
discovery: AVAILABLE_BUNDLE.discovery,
})
);
expect(JSON.parse(plaintext).oauth).not.toHaveProperty("mandantBinding");
expect(mocks.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
id: "connection-1",
tenantId: "tenant-1",
appId: "kwp",
archivedAt: null,
updatedAt: new Date(CHALLENGE.connectionVersion),
credentialsCiphertext: PENDING_CIPHERTEXT,
tokenExpiresAt: RESERVATION_EXPIRES_AT,
healthMessageKey: "integrations.kwp.health.oauthPending",
}),
data: expect.objectContaining({
credentialsCiphertext: PENDING_CIPHERTEXT,
tokenExpiresAt: TOKEN_EXPIRES_AT,
connectionStatus: "pending",
createdByUserId: "user-1",
}),
});
expect(mocks.activateOAuthConnection).not.toHaveBeenCalled();
const persistedAndAudited = JSON.stringify([mocks.updateMany.mock.calls, mocks.createAuditEvent.mock.calls]);
expect(persistedAndAudited).not.toContain(ACCESS_TOKEN);
expect(persistedAndAudited).not.toContain(REFRESH_TOKEN);
expect(persistedAndAudited).not.toContain(CLIENT_SECRET);
});
it.each([
["403", new mocks.KwpError("mandant_discovery_unavailable", 403)],
["404", new mocks.KwpError("mandant_discovery_unavailable", 404)],
["invalid response", new mocks.KwpError("invalid_response", 200)],
["provider outage", new mocks.KwpError("provider_outage", 503)],
["rate limit", new mocks.KwpError("rate_limit_exceeded", 429)],
])("stages manual selection on the documented %s discovery fallback", async (_label, error) => {
mocks.discoverKwpMandants.mockRejectedValueOnce(error);
await completeKwpOAuthConnection({ callbackParameters: { code: "code", state: CHALLENGE.state }, challenge: CHALLENGE });
const plaintext = JSON.parse(mocks.encryptTenantField.mock.calls[0]?.[1] as string);
expect(plaintext.discovery).toEqual({ kind: "manual" });
expect(mocks.createAuditEvent).toHaveBeenCalledWith(expect.objectContaining({ metadata: { appId: "kwp", discovery: "manual", optionCount: 0 } }));
});
it.each([
["401", new mocks.KwpError("auth_token_invalid", 401), "discovery_auth_token_invalid"],
["invalid credentials", new mocks.KwpError("invalid_credentials", 400), "discovery_invalid_credentials"],
["invalid relay host", new mocks.KwpError("relay_host_invalid"), "discovery_relay_host_invalid"],
["unconfirmed binding", new mocks.KwpError("mandant_unconfirmed"), "discovery_mandant_unconfirmed"],
])("fails closed on %s discovery errors and restores the previous connection", async (_label, error, diagnosticCode) => {
mocks.discoverKwpMandants.mockRejectedValueOnce(error);
await expect(completeKwpOAuthConnection({ callbackParameters: { code: "code", state: CHALLENGE.state }, challenge: CHALLENGE })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "connection_failed", diagnosticCode })
);
expect(mocks.encryptTenantField).not.toHaveBeenCalled();
expect(mocks.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
credentialsCiphertext: PREVIOUS_CIPHERTEXT,
connectionStatus: "active",
createdByUserId: "original-owner",
}),
})
);
});
it("normalizes a missing provider label and falls back manually on an invalid discovered option", async () => {
mocks.discoverKwpMandants.mockResolvedValueOnce([{ id: 7, code: "007" }]);
await completeKwpOAuthConnection({ callbackParameters: { code: "code", state: CHALLENGE.state }, challenge: CHALLENGE });
expect(JSON.parse(mocks.encryptTenantField.mock.calls[0]?.[1] as string).discovery).toEqual({
kind: "available",
options: [{ id: 7, code: "007", label: "007" }],
});
mocks.encryptTenantField.mockClear();
mocks.discoverKwpMandants.mockResolvedValueOnce([{ id: 7, code: "bad/code", label: "Invalid" }]);
await completeKwpOAuthConnection({ callbackParameters: { code: "code", state: CHALLENGE.state }, challenge: CHALLENGE });
expect(JSON.parse(mocks.encryptTenantField.mock.calls[0]?.[1] as string).discovery).toEqual({ kind: "manual" });
});
it("rejects a callback CAS race and preserves stable token-exchange diagnostics", async () => {
mocks.updateMany.mockResolvedValueOnce({ count: 0 });
await expect(completeKwpOAuthConnection({ callbackParameters: { code: "code", state: CHALLENGE.state }, challenge: CHALLENGE })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" })
);
mocks.exchangeAuthorizationCode.mockRejectedValueOnce(new mocks.KwpOidcClientError("invalid-token-response", { diagnosticCode: "missing_refresh_token" }));
await expect(completeKwpOAuthConnection({ callbackParameters: { code: "code", state: CHALLENGE.state }, challenge: CHALLENGE })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "exchange_failed", diagnosticCode: "missing_refresh_token" })
);
expect(mocks.updateMany).toHaveBeenLastCalledWith(
expect.objectContaining({ data: expect.objectContaining({ credentialsCiphertext: PREVIOUS_CIPHERTEXT, connectionStatus: "active" }) })
);
});
});
describe("cancelKwpOAuthConnectionAttempt", () => {
it("restores the exact pre-reconnect credentials, health and owner", async () => {
mockPendingBundle(RECONNECT_SELECTION_BUNDLE);
await cancelKwpOAuthConnectionAttempt({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
});
expect(mocks.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
updatedAt: PENDING_VERSION,
credentialsCiphertext: PENDING_CIPHERTEXT,
healthMessageKey: "integrations.kwp.health.mandantSelectionRequired",
}),
data: expect.objectContaining({
credentialsCiphertext: PREVIOUS_CIPHERTEXT,
connectionStatus: "active",
tokenExpiresAt: new Date(PREVIOUS_CONNECTION.tokenExpiresAt),
healthMessageKey: PREVIOUS_CONNECTION.healthMessageKey,
lastHealthCheck: new Date(PREVIOUS_CONNECTION.lastHealthCheck),
createdByUserId: PREVIOUS_CONNECTION.createdByUserId,
updatedAt: expect.any(Date),
}),
})
);
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({ action: "INTEGRATION_OAUTH_CANCEL", metadata: { appId: "kwp", restored: true } })
);
});
});
describe("loadKwpMandantSelection", () => {
it("returns only the safe projection from the tenant/user-bound pending row", async () => {
mockPendingBundle();
const view = await loadKwpMandantSelection({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1" });
expect(view).toEqual({
connectionId: "connection-1",
customerCode: "geerkens2",
version: PENDING_VERSION.toISOString(),
mode: "available",
options: AVAILABLE_BUNDLE.discovery.options,
});
expect(JSON.stringify(view)).not.toContain(ACCESS_TOKEN);
expect(JSON.stringify(view)).not.toContain(REFRESH_TOKEN);
expect(JSON.stringify(view)).not.toContain(CLIENT_SECRET);
expect(mocks.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ tenantId: "tenant-1", connectionStatus: "pending", createdByUserId: "user-1" }),
})
);
});
it("clears an expired attempt with its exact ciphertext/version CAS", async () => {
const expired = { ...AVAILABLE_BUNDLE, oauth: { ...OAUTH_CREDENTIALS, expiresAt: "2020-01-01T00:00:00.000Z" } };
mocks.findFirst.mockResolvedValue(pendingRow({ tokenExpiresAt: new Date(expired.oauth.expiresAt) }));
mocks.decryptTenantField.mockResolvedValue(JSON.stringify(expired));
await expect(loadKwpMandantSelection({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "selection_expired" })
);
expect(mocks.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
connectionStatus: "pending",
createdByUserId: "user-1",
updatedAt: PENDING_VERSION,
credentialsCiphertext: PENDING_CIPHERTEXT,
}),
data: expect.objectContaining({ credentialsCiphertext: null, tokenExpiresAt: null, connectionStatus: "pending" }),
});
});
it("rejects an expired-attempt clear when its exact CAS generation was already replaced", async () => {
const expired = { ...AVAILABLE_BUNDLE, oauth: { ...OAUTH_CREDENTIALS, expiresAt: "2020-01-01T00:00:00.000Z" } };
mocks.findFirst.mockResolvedValue(pendingRow({ tokenExpiresAt: new Date(expired.oauth.expiresAt) }));
mocks.decryptTenantField.mockResolvedValue(JSON.stringify(expired));
mocks.updateMany.mockResolvedValueOnce({ count: 0 });
await expect(loadKwpMandantSelection({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" })
);
});
it("rejects another identity and malformed encrypted state", async () => {
mocks.context = { tenantId: "tenant-1", userId: "other-user" };
await expect(loadKwpMandantSelection({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" })
);
expect(mocks.findFirst).not.toHaveBeenCalled();
mocks.context = { tenantId: "tenant-1", userId: "user-1" };
mockPendingBundle({ kind: "unexpected" });
await expect(loadKwpMandantSelection({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" })
);
mockPendingBundle({
...AVAILABLE_BUNDLE,
discovery: { kind: "available", options: [{ id: 1, code: "bad/code", label: "Invalid" }] },
});
await expect(loadKwpMandantSelection({ tenantId: "tenant-1", userId: "user-1", connectionId: "connection-1" })).rejects.toEqual(
expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" })
);
});
});
describe("finalizeKwpOAuthConnection", () => {
it("accepts only a discovered option, canonicalizes its label, and activates with the exact version fence", async () => {
mockPendingBundle();
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "selected", code: "002", label: "tampered browser label" },
})
).resolves.toEqual({ connectionId: "connection-1" });
expect(mocks.activateOAuthConnection).toHaveBeenCalledWith({
tenantId: "tenant-1",
connectionId: "connection-1",
appId: "kwp",
credentials: expect.objectContaining({
accessToken: ACCESS_TOKEN,
mandantBinding: { kind: "selected", code: "002", label: "Geerkens Service GmbH" },
}),
tokenExpiresAt: TOKEN_EXPIRES_AT,
actorUserId: "user-1",
expectedUpdatedAt: PENDING_VERSION,
});
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "INTEGRATION_KWP_MANDANT_BIND",
metadata: { appId: "kwp", binding: "selected", source: "available" },
})
);
expect(JSON.stringify(mocks.createAuditEvent.mock.calls)).not.toContain("002");
});
it.each([{ kind: "none" } as const, { kind: "selected", code: "999" } as const])(
"rejects a non-listed binding when discovery returned options",
async (mandantBinding) => {
mockPendingBundle();
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding,
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_selection" }));
expect(mocks.activateOAuthConnection).not.toHaveBeenCalled();
}
);
it("allows an explicit none or validated manual code only in manual/empty mode", async () => {
mockPendingBundle(MANUAL_BUNDLE);
await finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
});
expect(mocks.activateOAuthConnection).toHaveBeenLastCalledWith(
expect.objectContaining({
credentials: expect.objectContaining({ mandantBinding: { kind: "none" } }),
})
);
mocks.activateOAuthConnection.mockClear();
mockPendingBundle(MANUAL_BUNDLE);
await finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "selected", code: "007", label: "ignored" },
});
expect(mocks.activateOAuthConnection).toHaveBeenLastCalledWith(
expect.objectContaining({
credentials: expect.objectContaining({ mandantBinding: { kind: "selected", code: "007" } }),
})
);
mocks.activateOAuthConnection.mockClear();
mockPendingBundle(EMPTY_AVAILABLE_BUNDLE);
await finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
});
expect(mocks.activateOAuthConnection).toHaveBeenLastCalledWith(
expect.objectContaining({ credentials: expect.objectContaining({ mandantBinding: { kind: "none" } }) })
);
mocks.activateOAuthConnection.mockClear();
mockPendingBundle(EMPTY_AVAILABLE_BUNDLE);
await finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "selected", code: "008" },
});
expect(mocks.activateOAuthConnection).toHaveBeenLastCalledWith(
expect.objectContaining({ credentials: expect.objectContaining({ mandantBinding: { kind: "selected", code: "008" } }) })
);
});
it("rejects malformed manual codes and stale versions before provider I/O", async () => {
mockPendingBundle(MANUAL_BUNDLE);
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "selected", code: "bad/code" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_selection" }));
mocks.findFirst.mockResolvedValueOnce(null);
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" }));
expect(mocks.activateOAuthConnection).not.toHaveBeenCalled();
});
it("clears the exact pending attempt and reports selection_expired after a Health 401", async () => {
mockPendingBundle(MANUAL_BUNDLE);
mocks.activateOAuthConnection.mockRejectedValueOnce(new mocks.AppsEngineServiceError("integrations.kwp.health.tokenInvalid"));
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "selection_expired" }));
expect(mocks.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ updatedAt: PENDING_VERSION, credentialsCiphertext: PENDING_CIPHERTEXT }),
data: expect.objectContaining({ credentialsCiphertext: null, tokenExpiresAt: null, connectionStatus: "pending" }),
})
);
});
it("rejects a Health-401 clear when another attempt already won the CAS", async () => {
mockPendingBundle(MANUAL_BUNDLE);
mocks.activateOAuthConnection.mockRejectedValueOnce(new mocks.AppsEngineServiceError("integrations.kwp.health.tokenInvalid"));
mocks.updateMany.mockResolvedValueOnce({ count: 0 });
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" }));
});
it("maps a lost activation CAS after the Health probe to invalid_state", async () => {
mockPendingBundle(MANUAL_BUNDLE);
mocks.activateOAuthConnection.mockRejectedValueOnce(new CatalogError(foundationErrors.notFound, { connectionId: "connection-1" }));
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "invalid_state" }));
expect(mocks.updateMany).not.toHaveBeenCalled();
});
it("keeps the pending attempt on non-401 provider rejection", async () => {
mockPendingBundle(MANUAL_BUNDLE);
mocks.activateOAuthConnection.mockRejectedValueOnce(new mocks.AppsEngineServiceError("integrations.kwp.health.scopeMissing"));
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "connection_failed", diagnosticCode: "health_scope_missing" }));
expect(mocks.updateMany).not.toHaveBeenCalled();
});
it("keeps an unexpectedly unconfirmed Health result pending with a stable diagnostic", async () => {
mockPendingBundle(MANUAL_BUNDLE);
mocks.activateOAuthConnection.mockRejectedValueOnce(new mocks.AppsEngineServiceError("integrations.kwp.health.mandantUnconfirmed"));
await expect(
finalizeKwpOAuthConnection({
tenantId: "tenant-1",
userId: "user-1",
connectionId: "connection-1",
version: PENDING_VERSION.toISOString(),
mandantBinding: { kind: "none" },
})
).rejects.toEqual(expect.objectContaining<Partial<KwpConnectError>>({ code: "connection_failed", diagnosticCode: "health_mandant_unconfirmed" }));
expect(mocks.updateMany).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,924 @@
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { decryptTenantField, encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import {
discoverKwpMandants,
isValidKwpContextCode,
KWP_APP_ID,
KWP_LEGACY_MANDANT_SELECTION_KIND,
KWP_MANDANT_SELECTION_HEALTH_KEY,
KWP_MANDANT_SELECTION_KIND,
KWP_OAUTH_PENDING_HEALTH_KEY,
KWP_OAUTH_RESERVATION_KIND,
KwpError,
parseKwpOAuthReservationBundle,
parseKwpPendingAttemptLifecycle,
type KwpCredentials,
type KwpMandantBinding,
type KwpOAuthReservationBundle,
type KwpRestorableConnectionSnapshot,
type KwpRestorableConnectionStatus,
} from "@hivegrid/integrations";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { activateOAuthConnection, AppsEngineServiceError } from "~/utils/integrations/appsEngineService.server";
import { buildKwpAuthorizationUrl, exchangeKwpAuthorizationCode, KwpOidcClientError, readKwpOidcRuntimeConfig } from "./kwpOidcClient.server";
import {
createKwpOAuthChallenge,
KWP_OAUTH_CHALLENGE_TTL_MS,
type KwpOAuthChallengePayload,
} from "./kwpOAuthChallenge.server";
const KWP_CONNECTION_LABEL = "KWP";
const KWP_SLOT_LOCK_SALT = 32_001;
const KWP_NOT_CONNECTED_HEALTH_KEY = "integrations.health.notConnected";
const MAX_DISCOVERED_MANDANTS = 100;
const MAX_MANDANT_LABEL_LENGTH = 256;
type KwpUnconfirmedCredentials = Omit<KwpCredentials, "mandantBinding"> & { readonly mandantBinding?: never };
type KwpMandantOption = {
readonly id: number;
readonly code: string;
readonly label: string;
};
type KwpMandantSelectionBundle = {
readonly kind: typeof KWP_MANDANT_SELECTION_KIND;
readonly previous: KwpRestorableConnectionSnapshot | null;
readonly oauth: KwpUnconfirmedCredentials;
readonly discovery: { readonly kind: "available"; readonly options: readonly KwpMandantOption[] } | { readonly kind: "manual" };
readonly issuedAt: string;
};
type PendingKwpMandantSelection = {
readonly connectionId: string;
readonly version: string;
readonly credentialsCiphertext: string;
readonly tokenExpiresAt: Date;
readonly bundle: KwpMandantSelectionBundle;
};
type PendingKwpOAuthReservation = {
readonly connectionId: string;
readonly version: string;
readonly credentialsCiphertext: string;
readonly tokenExpiresAt: Date;
readonly bundle: KwpOAuthReservationBundle;
};
type RestorablePendingKwpAttempt = {
readonly connectionId: string;
readonly version: string;
readonly credentialsCiphertext: string;
readonly tokenExpiresAt: Date;
readonly healthMessageKey: typeof KWP_OAUTH_PENDING_HEALTH_KEY | typeof KWP_MANDANT_SELECTION_HEALTH_KEY;
readonly previous: KwpRestorableConnectionSnapshot | null;
};
export class KwpConnectError extends Error {
readonly code:
| "not_configured"
| "invalid_state"
| "slot_conflict"
| "authorization_failed"
| "exchange_failed"
| "connection_failed"
| "persistence_failed"
| "invalid_selection"
| "selection_expired";
readonly diagnosticCode?: string;
constructor(code: KwpConnectError["code"], options?: { readonly diagnosticCode?: string }) {
super(code);
this.name = "KwpConnectError";
this.code = code;
this.diagnosticCode = options?.diagnosticCode;
}
}
export type BeginKwpOAuthConnectionResult = {
readonly authorizationUrl: string;
readonly setCookie: string;
};
export type CompleteKwpOAuthConnectionResult = {
readonly tenantId: string;
readonly tenantSlug: string;
readonly connectionId: string;
};
export type KwpMandantSelectionView = {
readonly connectionId: string;
readonly customerCode: string;
/** Exact DataConnection.updatedAt CAS fence for the selection submission. */
readonly version: string;
readonly mode: "available" | "manual";
readonly options: readonly KwpMandantOption[];
};
/** Reserve/reuse the tenant's one KWP slot and create a one-time OIDC challenge. */
export async function beginKwpOAuthConnection(input: {
readonly tenantId: string;
readonly tenantSlug: string;
readonly userId: string;
readonly customerCode: string;
}): Promise<BeginKwpOAuthConnectionResult> {
assertBoundIdentity(input.tenantId, input.userId);
let runtimeConfig: ReturnType<typeof readKwpOidcRuntimeConfig>;
try {
runtimeConfig = readKwpOidcRuntimeConfig();
} catch {
throw new KwpConnectError("not_configured");
}
if (runtimeConfig.hiveGridTenantId !== input.tenantId || !isValidKwpContextCode(input.customerCode) || input.customerCode !== runtimeConfig.customerCode) {
throw new KwpConnectError("not_configured");
}
const reservation = await ensureKwpConnectionSlot(input.tenantId, input.userId, input.customerCode);
try {
const challenge = createKwpOAuthChallenge({
tenantId: input.tenantId,
tenantSlug: input.tenantSlug,
userId: input.userId,
connectionId: reservation.connectionId,
connectionVersion: reservation.version,
customerCode: input.customerCode,
});
const authorizationUrl = await buildKwpAuthorizationUrl({
state: challenge.payload.state,
nonce: challenge.payload.nonce,
codeChallenge: challenge.payload.codeChallenge,
customerCode: input.customerCode,
});
return { authorizationUrl, setCookie: challenge.cookie };
} catch {
await restorePendingKwpAttempt({ ...input, connectionId: reservation.connectionId }, reservation).catch(() => undefined);
throw new KwpConnectError("authorization_failed");
}
}
/**
* Exchange the one-time authorization code and discover the user's allowed KWP
* mandates immediately while the five-minute access token is fresh. The OAuth
* material is persisted only as an inert, envelope-encrypted pending bundle;
* no connection becomes active before an explicit mandate binding is confirmed.
*/
export async function completeKwpOAuthConnection(input: {
readonly callbackParameters: { readonly code: string; readonly state: string; readonly iss?: string };
readonly challenge: KwpOAuthChallengePayload;
}): Promise<CompleteKwpOAuthConnectionResult> {
const { challenge } = input;
assertBoundIdentity(challenge.tenantId, challenge.userId);
const reservation = await loadPendingOAuthReservation({
tenantId: challenge.tenantId,
userId: challenge.userId,
connectionId: challenge.connectionId,
expectedVersion: parseConnectionVersion(challenge.connectionVersion),
});
if (isExpired(reservation)) {
await restorePendingKwpAttempt(challenge, reservation);
throw new KwpConnectError("invalid_state");
}
let runtimeConfig: ReturnType<typeof readKwpOidcRuntimeConfig>;
try {
runtimeConfig = readKwpOidcRuntimeConfig();
} catch {
await restorePendingKwpAttempt(challenge, reservation).catch(() => undefined);
throw new KwpConnectError("not_configured");
}
if (
runtimeConfig.hiveGridTenantId !== challenge.tenantId ||
runtimeConfig.customerCode !== challenge.customerCode ||
input.callbackParameters.state !== challenge.state ||
reservation.bundle.customerCode !== challenge.customerCode
) {
await restorePendingKwpAttempt(challenge, reservation).catch(() => undefined);
throw new KwpConnectError("invalid_state");
}
let exchanged: { readonly credentials: KwpCredentials; readonly tokenExpiresAt: Date };
try {
exchanged = await exchangeKwpAuthorizationCode(input.callbackParameters, {
state: challenge.state,
nonce: challenge.nonce,
codeVerifier: challenge.codeVerifier,
customerCode: challenge.customerCode,
});
} catch (error) {
await restorePendingKwpAttempt(challenge, reservation).catch(() => undefined);
throw new KwpConnectError("exchange_failed", {
diagnosticCode: error instanceof KwpOidcClientError ? (error.diagnosticCode ?? `oidc_${error.code.replaceAll("-", "_")}`) : "exchange_unexpected",
});
}
if (!Number.isFinite(exchanged.tokenExpiresAt.getTime())) {
await restorePendingKwpAttempt(challenge, reservation).catch(() => undefined);
throw new KwpConnectError("exchange_failed");
}
const oauth = toUnconfirmedCredentials(exchanged.credentials);
let discovery: KwpMandantSelectionBundle["discovery"];
try {
discovery = await discoverMandantsOrManualFallback(oauth);
} catch (error) {
await restorePendingKwpAttempt(challenge, reservation).catch(() => undefined);
throw error;
}
const bundle: KwpMandantSelectionBundle = {
kind: KWP_MANDANT_SELECTION_KIND,
previous: reservation.bundle.previous,
oauth,
discovery,
issuedAt: new Date().toISOString(),
};
try {
const updated = await withTenantRLS(challenge.tenantId, async (tx) => {
const credentialsCiphertext = await encryptTenantField(challenge.tenantId, JSON.stringify(bundle), { client: tx as never });
return tx.dataConnection.updateMany({
where: {
id: challenge.connectionId,
tenantId: challenge.tenantId,
appId: KWP_APP_ID,
archivedAt: null,
connectionStatus: "pending",
createdByUserId: challenge.userId,
updatedAt: new Date(challenge.connectionVersion),
credentialsCiphertext: reservation.credentialsCiphertext,
tokenExpiresAt: reservation.tokenExpiresAt,
healthMessageKey: KWP_OAUTH_PENDING_HEALTH_KEY,
},
data: {
credentialsCiphertext,
tokenExpiresAt: exchanged.tokenExpiresAt,
connectionStatus: "pending",
healthMessageKey: KWP_MANDANT_SELECTION_HEALTH_KEY,
lastHealthCheck: null,
createdByUserId: challenge.userId,
},
});
});
if (updated.count !== 1) throw new KwpConnectError("invalid_state");
} catch (error) {
if (error instanceof KwpConnectError) throw error;
await restorePendingKwpAttempt(challenge, reservation).catch(() => undefined);
throw new KwpConnectError("persistence_failed");
}
await auditKwpConnection(challenge.tenantId, challenge.userId, "INTEGRATION_OAUTH_MANDANT_SELECTION_PENDING", challenge.connectionId, {
discovery: discovery.kind,
optionCount: discovery.kind === "available" ? discovery.options.length : 0,
});
return {
tenantId: challenge.tenantId,
tenantSlug: challenge.tenantSlug,
connectionId: challenge.connectionId,
};
}
/** Return only the safe selection projection; OAuth material never leaves this service. */
export async function loadKwpMandantSelection(input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
}): Promise<KwpMandantSelectionView> {
assertBoundIdentity(input.tenantId, input.userId);
const pending = await loadPendingMandantSelection(input);
if (isExpired(pending)) {
await restorePendingKwpAttempt(input, pending);
throw new KwpConnectError("selection_expired");
}
return {
connectionId: pending.connectionId,
customerCode: pending.bundle.oauth.customerCode,
version: pending.version,
mode: pending.bundle.discovery.kind,
options: pending.bundle.discovery.kind === "available" ? pending.bundle.discovery.options.map((option) => ({ ...option })) : [],
};
}
/** Validate one explicit binding, prove it against KWP, then atomically activate. */
export async function finalizeKwpOAuthConnection(input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly version: string;
readonly mandantBinding: KwpMandantBinding;
}): Promise<{ readonly connectionId: string }> {
assertBoundIdentity(input.tenantId, input.userId);
const expectedVersion = parseConnectionVersion(input.version);
const pending = await loadPendingMandantSelection({
tenantId: input.tenantId,
userId: input.userId,
connectionId: input.connectionId,
expectedVersion,
});
if (isExpired(pending)) {
await restorePendingKwpAttempt(input, pending);
throw new KwpConnectError("selection_expired");
}
const mandantBinding = resolveConfirmedBinding(pending.bundle.discovery, input.mandantBinding);
const credentials: KwpCredentials = { ...pending.bundle.oauth, mandantBinding };
try {
await activateOAuthConnection({
tenantId: input.tenantId,
connectionId: input.connectionId,
appId: KWP_APP_ID,
credentials: credentials as unknown as Record<string, unknown>,
tokenExpiresAt: pending.tokenExpiresAt,
actorUserId: input.userId,
expectedUpdatedAt: expectedVersion,
});
} catch (error) {
if (error instanceof AppsEngineServiceError) {
if (error.messageKey === "integrations.kwp.health.tokenInvalid") {
await restorePendingKwpAttempt(input, pending);
throw new KwpConnectError("selection_expired");
}
throw new KwpConnectError("connection_failed", { diagnosticCode: healthDiagnosticCode(error.messageKey) });
}
if (error instanceof CatalogError && error.code === foundationErrors.notFound.code) {
throw new KwpConnectError("invalid_state");
}
throw new KwpConnectError("persistence_failed");
}
await auditKwpConnection(input.tenantId, input.userId, "INTEGRATION_KWP_MANDANT_BIND", input.connectionId, {
binding: mandantBinding.kind,
source: pending.bundle.discovery.kind,
});
return { connectionId: input.connectionId };
}
/** Explicitly abandon one selection and restore the connection from before reconnect. */
export async function cancelKwpOAuthConnectionAttempt(input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly version: string;
}): Promise<void> {
assertBoundIdentity(input.tenantId, input.userId);
const pending = await loadRestorablePendingAttempt({
...input,
expectedVersion: parseConnectionVersion(input.version),
});
await restorePendingKwpAttempt(input, pending);
await auditKwpConnection(input.tenantId, input.userId, "INTEGRATION_OAUTH_CANCEL", input.connectionId, {
restored: pending.previous !== null,
});
}
async function discoverMandantsOrManualFallback(credentials: KwpUnconfirmedCredentials): Promise<KwpMandantSelectionBundle["discovery"]> {
try {
const options = sanitizeMandantOptions(await discoverKwpMandants(credentials));
return { kind: "available", options };
} catch (error) {
if (error instanceof KwpConnectError && error.diagnosticCode === "discovery_invalid_response") {
return { kind: "manual" };
}
if (isManualDiscoveryFallback(error)) return { kind: "manual" };
throw new KwpConnectError("connection_failed", { diagnosticCode: discoveryDiagnosticCode(error) });
}
}
function isManualDiscoveryFallback(error: unknown): boolean {
if (!(error instanceof KwpError)) return false;
if (error.httpStatus === 401 || error.code === "auth_token_invalid" || error.code === "invalid_credentials" || error.code === "relay_host_invalid") {
return false;
}
return (
error.httpStatus === 403 ||
error.httpStatus === 404 ||
error.code === "auth_scope_missing" ||
error.code === "relay_not_found" ||
error.code === "mandant_discovery_unavailable" ||
error.code === "invalid_response" ||
error.code === "provider_outage" ||
error.code === "rate_limit_exceeded"
);
}
function discoveryDiagnosticCode(error: unknown): string {
return error instanceof KwpError ? `discovery_${error.code}` : "discovery_unexpected";
}
function sanitizeMandantOptions(value: unknown): readonly KwpMandantOption[] {
if (!Array.isArray(value) || value.length > MAX_DISCOVERED_MANDANTS) {
throw new KwpConnectError("connection_failed", { diagnosticCode: "discovery_invalid_response" });
}
const options: KwpMandantOption[] = [];
const seenCodes = new Set<string>();
for (const candidate of value) {
if (!isRecord(candidate)) throw new KwpConnectError("connection_failed", { diagnosticCode: "discovery_invalid_response" });
const { id, code, label } = candidate;
if (
typeof id !== "number" ||
!Number.isSafeInteger(id) ||
!isValidKwpContextCode(code) ||
(label !== undefined && typeof label !== "string") ||
(typeof label === "string" && (label.length > MAX_MANDANT_LABEL_LENGTH || label.trim() !== label)) ||
seenCodes.has(code)
) {
throw new KwpConnectError("connection_failed", { diagnosticCode: "discovery_invalid_response" });
}
seenCodes.add(code);
options.push({ id, code, label: typeof label === "string" && label ? label : code });
}
return options;
}
function toUnconfirmedCredentials(credentials: KwpCredentials): KwpUnconfirmedCredentials {
return {
accessToken: credentials.accessToken,
refreshToken: credentials.refreshToken,
expiresAt: credentials.expiresAt,
issuer: credentials.issuer,
clientId: credentials.clientId,
clientSecret: credentials.clientSecret,
customerCode: credentials.customerCode,
scopes: [...credentials.scopes],
};
}
async function loadPendingMandantSelection(input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly expectedVersion?: Date;
}): Promise<PendingKwpMandantSelection> {
try {
return await withTenantRLS(input.tenantId, async (tx) => {
const row = await findPendingAttemptRow(tx, input);
const plaintext = await decryptTenantField(input.tenantId, row.credentialsCiphertext, { client: tx as never });
const bundle = parseMandantSelectionBundle(plaintext);
if (
row.healthMessageKey !== KWP_MANDANT_SELECTION_HEALTH_KEY ||
row.tokenExpiresAt.toISOString() !== bundle.oauth.expiresAt
) {
throw new KwpConnectError("invalid_state");
}
return {
connectionId: row.id,
version: row.updatedAt.toISOString(),
credentialsCiphertext: row.credentialsCiphertext,
tokenExpiresAt: row.tokenExpiresAt,
bundle,
};
});
} catch (error) {
if (error instanceof KwpConnectError) throw error;
throw new KwpConnectError("persistence_failed");
}
}
async function loadPendingOAuthReservation(input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly expectedVersion?: Date;
}): Promise<PendingKwpOAuthReservation> {
try {
return await withTenantRLS(input.tenantId, async (tx) => {
const row = await findPendingAttemptRow(tx, input);
const plaintext = await decryptTenantField(input.tenantId, row.credentialsCiphertext, { client: tx as never });
const bundle = parseKwpOAuthReservationBundle(plaintext);
if (
!bundle ||
row.healthMessageKey !== KWP_OAUTH_PENDING_HEALTH_KEY ||
row.tokenExpiresAt.toISOString() !== bundle.expiresAt
) {
throw new KwpConnectError("invalid_state");
}
return {
connectionId: row.id,
version: row.updatedAt.toISOString(),
credentialsCiphertext: row.credentialsCiphertext,
tokenExpiresAt: row.tokenExpiresAt,
bundle,
};
});
} catch (error) {
if (error instanceof KwpConnectError) throw error;
throw new KwpConnectError("persistence_failed");
}
}
async function loadRestorablePendingAttempt(input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly expectedVersion?: Date;
}): Promise<RestorablePendingKwpAttempt> {
try {
return await withTenantRLS(input.tenantId, async (tx) => {
const row = await findPendingAttemptRow(tx, input);
const plaintext = await decryptTenantField(input.tenantId, row.credentialsCiphertext, { client: tx as never });
const lifecycle = parseKwpPendingAttemptLifecycle(plaintext);
const expectedHealthKey = lifecycle?.phase === "oauth" ? KWP_OAUTH_PENDING_HEALTH_KEY : KWP_MANDANT_SELECTION_HEALTH_KEY;
if (!lifecycle || row.healthMessageKey !== expectedHealthKey) throw new KwpConnectError("invalid_state");
return {
connectionId: row.id,
version: row.updatedAt.toISOString(),
credentialsCiphertext: row.credentialsCiphertext,
tokenExpiresAt: row.tokenExpiresAt,
healthMessageKey: expectedHealthKey,
previous: lifecycle.previous,
};
});
} catch (error) {
if (error instanceof KwpConnectError) throw error;
throw new KwpConnectError("persistence_failed");
}
}
async function findPendingAttemptRow(
tx: TenantRlsClient,
input: {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly expectedVersion?: Date;
}
) {
const row = await tx.dataConnection.findFirst({
where: {
id: input.connectionId,
tenantId: input.tenantId,
appId: KWP_APP_ID,
archivedAt: null,
connectionStatus: "pending",
createdByUserId: input.userId,
...(input.expectedVersion ? { updatedAt: input.expectedVersion } : {}),
},
select: {
id: true,
updatedAt: true,
credentialsCiphertext: true,
tokenExpiresAt: true,
healthMessageKey: true,
},
});
if (!row?.credentialsCiphertext || !row.tokenExpiresAt) throw new KwpConnectError("invalid_state");
return {
...row,
credentialsCiphertext: row.credentialsCiphertext,
tokenExpiresAt: row.tokenExpiresAt,
};
}
async function restorePendingKwpAttempt(
input: { readonly tenantId: string; readonly userId: string; readonly connectionId: string },
pending: PendingKwpMandantSelection | PendingKwpOAuthReservation | RestorablePendingKwpAttempt
): Promise<void> {
const previous = "bundle" in pending ? pending.bundle.previous : pending.previous;
const healthMessageKey =
"healthMessageKey" in pending
? pending.healthMessageKey
: pending.bundle.kind === KWP_OAUTH_RESERVATION_KIND
? KWP_OAUTH_PENDING_HEALTH_KEY
: KWP_MANDANT_SELECTION_HEALTH_KEY;
try {
const restored = await withTenantRLS(input.tenantId, (tx) =>
tx.dataConnection.updateMany({
where: {
id: input.connectionId,
tenantId: input.tenantId,
appId: KWP_APP_ID,
archivedAt: null,
connectionStatus: "pending",
createdByUserId: input.userId,
updatedAt: new Date(pending.version),
credentialsCiphertext: pending.credentialsCiphertext,
tokenExpiresAt: pending.tokenExpiresAt,
healthMessageKey,
},
data: {
...restorationData(previous, input.userId),
// Always invalidate the browser's old callback/selection fence.
updatedAt: new Date(Math.max(Date.now(), new Date(pending.version).getTime() + 1)),
},
})
);
if (restored.count !== 1) throw new KwpConnectError("invalid_state");
} catch (error) {
if (error instanceof KwpConnectError) throw error;
throw new KwpConnectError("persistence_failed");
}
}
function parseMandantSelectionBundle(plaintext: string): KwpMandantSelectionBundle {
let value: unknown;
try {
value = JSON.parse(plaintext);
} catch {
throw new KwpConnectError("invalid_state");
}
if (
!isRecord(value) ||
(value.kind !== KWP_MANDANT_SELECTION_KIND && value.kind !== KWP_LEGACY_MANDANT_SELECTION_KIND) ||
!isRecord(value.oauth) ||
!isRecord(value.discovery)
) {
throw new KwpConnectError("invalid_state");
}
const lifecycle = parseKwpPendingAttemptLifecycle(plaintext);
if (!lifecycle || lifecycle.phase !== "mandant") throw new KwpConnectError("invalid_state");
const oauth = value.oauth;
if (
typeof oauth.accessToken !== "string" ||
!oauth.accessToken ||
typeof oauth.refreshToken !== "string" ||
!oauth.refreshToken ||
typeof oauth.expiresAt !== "string" ||
!Number.isFinite(Date.parse(oauth.expiresAt)) ||
typeof oauth.issuer !== "string" ||
!oauth.issuer ||
typeof oauth.clientId !== "string" ||
!oauth.clientId ||
typeof oauth.clientSecret !== "string" ||
!oauth.clientSecret ||
!isValidKwpContextCode(oauth.customerCode) ||
!Array.isArray(oauth.scopes) ||
!oauth.scopes.every((scope) => typeof scope === "string" && scope.length > 0) ||
oauth.mandantBinding !== undefined ||
typeof value.issuedAt !== "string" ||
!Number.isFinite(Date.parse(value.issuedAt))
) {
throw new KwpConnectError("invalid_state");
}
let discovery: KwpMandantSelectionBundle["discovery"];
if (value.discovery.kind === "manual") {
discovery = { kind: "manual" };
} else if (value.discovery.kind === "available") {
try {
discovery = { kind: "available", options: sanitizeMandantOptions(value.discovery.options) };
} catch {
throw new KwpConnectError("invalid_state");
}
} else {
throw new KwpConnectError("invalid_state");
}
return {
kind: KWP_MANDANT_SELECTION_KIND,
previous: lifecycle.previous,
oauth: {
accessToken: oauth.accessToken,
refreshToken: oauth.refreshToken,
expiresAt: oauth.expiresAt,
issuer: oauth.issuer,
clientId: oauth.clientId,
clientSecret: oauth.clientSecret,
customerCode: oauth.customerCode,
scopes: [...oauth.scopes],
},
discovery,
issuedAt: value.issuedAt,
};
}
function resolveConfirmedBinding(discovery: KwpMandantSelectionBundle["discovery"], requested: KwpMandantBinding): KwpMandantBinding {
if (discovery.kind === "available" && discovery.options.length > 0) {
if (requested.kind !== "selected") throw new KwpConnectError("invalid_selection");
const option = discovery.options.find((candidate) => candidate.code === requested.code);
if (!option) throw new KwpConnectError("invalid_selection");
return { kind: "selected", code: option.code, label: option.label };
}
if (requested.kind === "none") return { kind: "none" };
if (requested.kind !== "selected" || !isValidKwpContextCode(requested.code) || requested.code.trim() !== requested.code) {
throw new KwpConnectError("invalid_selection");
}
return { kind: "selected", code: requested.code };
}
function restorationData(previous: KwpRestorableConnectionSnapshot | null, actorUserId: string) {
if (!previous) {
return {
credentialsCiphertext: null,
tokenExpiresAt: null,
connectionStatus: "pending" as const,
healthMessageKey: KWP_NOT_CONNECTED_HEALTH_KEY,
lastHealthCheck: new Date(),
createdByUserId: actorUserId,
};
}
return {
credentialsCiphertext: previous.credentialsCiphertext,
tokenExpiresAt: previous.tokenExpiresAt ? new Date(previous.tokenExpiresAt) : null,
connectionStatus: previous.connectionStatus,
healthMessageKey: previous.healthMessageKey,
lastHealthCheck: previous.lastHealthCheck ? new Date(previous.lastHealthCheck) : null,
createdByUserId: previous.createdByUserId,
};
}
function isExpired(pending: { readonly tokenExpiresAt: Date }): boolean {
return !Number.isFinite(pending.tokenExpiresAt.getTime()) || pending.tokenExpiresAt.getTime() <= Date.now();
}
function parseConnectionVersion(value: string): Date {
const timestamp = Date.parse(value);
if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString() !== value) throw new KwpConnectError("invalid_state");
return new Date(timestamp);
}
function healthDiagnosticCode(messageKey: string): string {
switch (messageKey) {
case "integrations.kwp.health.tokenInvalid":
return "health_token_invalid";
case "integrations.kwp.health.scopeMissing":
return "health_scope_missing";
case "integrations.kwp.health.rateLimited":
return "health_rate_limited";
case "integrations.kwp.health.providerOutage":
return "health_provider_outage";
case "integrations.kwp.health.relayInvalid":
return "health_relay_invalid";
case "integrations.kwp.health.credentialsInvalid":
return "health_credentials_invalid";
case "integrations.kwp.health.mandantUnconfirmed":
return "health_mandant_unconfirmed";
default:
return "health_unknown";
}
}
async function ensureKwpConnectionSlot(
tenantId: string,
actorUserId: string,
customerCode: string
): Promise<PendingKwpOAuthReservation> {
let created = false;
const issuedAt = new Date();
const expiresAt = new Date(issuedAt.getTime() + KWP_OAUTH_CHALLENGE_TTL_MS);
const connection = await withTenantRLS(tenantId, async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`kwp-oauth-slot:${tenantId}`}, ${KWP_SLOT_LOCK_SALT}))`;
const candidates = await tx.dataConnection.findMany({
where: { tenantId, appId: KWP_APP_ID, archivedAt: null },
select: {
id: true,
updatedAt: true,
connectionStatus: true,
credentialsCiphertext: true,
tokenExpiresAt: true,
healthMessageKey: true,
lastHealthCheck: true,
createdByUserId: true,
},
orderBy: { createdAt: "asc" },
take: 2,
});
if (candidates.length > 1) throw new KwpConnectError("slot_conflict");
if (candidates[0]) {
const candidate = candidates[0];
if (candidate.healthMessageKey === "integrations.health.refreshInProgress") {
throw new KwpConnectError("slot_conflict");
}
const previous = await resolvePreviousConnectionSnapshot(tenantId, tx, candidate);
const bundle: KwpOAuthReservationBundle = {
kind: KWP_OAUTH_RESERVATION_KIND,
customerCode,
previous,
issuedAt: issuedAt.toISOString(),
expiresAt: expiresAt.toISOString(),
};
const credentialsCiphertext = await encryptTenantField(tenantId, JSON.stringify(bundle), { client: tx as never });
const attemptVersion = new Date(Math.max(Date.now(), candidate.updatedAt.getTime() + 1));
const invalidated = await tx.dataConnection.updateMany({
where: {
id: candidate.id,
tenantId,
appId: KWP_APP_ID,
archivedAt: null,
connectionStatus: candidate.connectionStatus,
updatedAt: candidate.updatedAt,
credentialsCiphertext: candidate.credentialsCiphertext,
tokenExpiresAt: candidate.tokenExpiresAt,
healthMessageKey: candidate.healthMessageKey,
lastHealthCheck: candidate.lastHealthCheck,
},
data: {
credentialsCiphertext,
tokenExpiresAt: expiresAt,
connectionStatus: "pending",
healthMessageKey: KWP_OAUTH_PENDING_HEALTH_KEY,
lastHealthCheck: null,
createdByUserId: actorUserId,
updatedAt: attemptVersion,
},
});
if (invalidated.count !== 1) throw new KwpConnectError("slot_conflict");
return {
connectionId: candidate.id,
version: attemptVersion.toISOString(),
credentialsCiphertext,
tokenExpiresAt: expiresAt,
bundle,
};
}
const bundle: KwpOAuthReservationBundle = {
kind: KWP_OAUTH_RESERVATION_KIND,
customerCode,
previous: null,
issuedAt: issuedAt.toISOString(),
expiresAt: expiresAt.toISOString(),
};
const credentialsCiphertext = await encryptTenantField(tenantId, JSON.stringify(bundle), { client: tx as never });
const connection = await tx.dataConnection.create({
data: {
tenantId,
appId: KWP_APP_ID,
label: KWP_CONNECTION_LABEL,
credentialsCiphertext,
connectionStatus: "pending",
healthMessageKey: KWP_OAUTH_PENDING_HEALTH_KEY,
tokenExpiresAt: expiresAt,
createdByUserId: actorUserId,
},
select: { id: true, updatedAt: true },
});
created = true;
return {
connectionId: connection.id,
version: connection.updatedAt.toISOString(),
credentialsCiphertext,
tokenExpiresAt: expiresAt,
bundle,
};
});
await auditKwpConnection(tenantId, actorUserId, "INTEGRATION_OAUTH_RESERVE", connection.connectionId, { created });
return connection;
}
async function resolvePreviousConnectionSnapshot(
tenantId: string,
tx: TenantRlsClient,
candidate: {
readonly connectionStatus: string;
readonly credentialsCiphertext: string | null;
readonly tokenExpiresAt: Date | null;
readonly healthMessageKey: string | null;
readonly lastHealthCheck: Date | null;
readonly createdByUserId: string | null;
}
): Promise<KwpRestorableConnectionSnapshot | null> {
if (candidate.connectionStatus === "pending") {
if (!candidate.credentialsCiphertext) return null;
const plaintext = await decryptTenantField(tenantId, candidate.credentialsCiphertext, { client: tx as never });
const lifecycle = parseKwpPendingAttemptLifecycle(plaintext);
if (!lifecycle) throw new KwpConnectError("slot_conflict");
return lifecycle.previous;
}
if (!isRestorableConnectionStatus(candidate.connectionStatus)) throw new KwpConnectError("slot_conflict");
return {
credentialsCiphertext: candidate.credentialsCiphertext,
connectionStatus: candidate.connectionStatus,
tokenExpiresAt: candidate.tokenExpiresAt?.toISOString() ?? null,
healthMessageKey: candidate.healthMessageKey,
lastHealthCheck: candidate.lastHealthCheck?.toISOString() ?? null,
createdByUserId: candidate.createdByUserId,
};
}
function isRestorableConnectionStatus(value: string): value is KwpRestorableConnectionStatus {
return value === "active" || value === "degraded" || value === "broken" || value === "revoked";
}
async function auditKwpConnection(tenantId: string, actorId: string, action: string, targetId: string, metadata: Record<string, unknown>): Promise<void> {
await createAuditEvent({
tenantId,
actorId,
actorType: "user",
action,
targetType: "DataConnection",
targetId,
sourceModule: "integrations",
outcome: "success",
metadata: { appId: KWP_APP_ID, ...metadata },
}).catch(() => undefined);
}
function assertBoundIdentity(tenantId: string, userId: string): void {
const context = getRlsExecutionContext();
if (context?.tenantId !== tenantId || context.userId !== userId) {
throw new KwpConnectError("invalid_state");
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -0,0 +1,258 @@
import { createHash, createHmac } from "node:crypto";
import { createSharedStore, MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const { testWebConfig } = vi.hoisted(() => ({
testWebConfig: {
nodeEnv: "test" as string,
cryptoSecret: "crypto-secret-for-kwp-oauth-tests",
sessionSecret: "session-secret-for-kwp-oauth-tests",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as "http" | "https",
},
},
}));
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => testWebConfig,
};
});
import {
__resetKwpOAuthChallengeStoreForTests,
__setKwpOAuthChallengeStoreForTests,
consumeKwpOAuthChallenge,
createKwpOAuthChallenge,
KWP_OAUTH_CHALLENGE_COOKIE,
KWP_OAUTH_CHALLENGE_TTL_MS,
LOCAL_KWP_OAUTH_CHALLENGE_COOKIE,
} from "./kwpOAuthChallenge.server";
const SECRET = "kwp-oauth-state-test-secret";
const NOW = 1_725_000_000_000;
const INPUT = {
tenantId: "tenant-1",
tenantSlug: "acme-shk",
userId: "user-1",
connectionId: "connection-1",
connectionVersion: "2026-07-20T12:00:00.000Z",
customerCode: "geerkens2",
} as const;
let sharedStore: SharedStore;
beforeEach(() => {
testWebConfig.nodeEnv = "test";
testWebConfig.routing.protocol = "https";
testWebConfig.routing.appBaseDomain = "example.test";
sharedStore = createSharedStore({ namespace: "kwp-oauth-test", adapter: new MemoryAdapter() });
__setKwpOAuthChallengeStoreForTests(sharedStore);
});
afterEach(async () => {
__resetKwpOAuthChallengeStoreForTests();
await sharedStore.close();
});
function cookieValue(cookie: string): string {
const assignment = cookie.split(";", 1)[0] ?? "";
return assignment.slice(assignment.indexOf("=") + 1);
}
function requestWithCookie(value: string, name = KWP_OAUTH_CHALLENGE_COOKIE): Request {
return new Request("https://app.example.test/integrations/kwp/oauth/callback", {
headers: { cookie: `${name}=${value}` },
});
}
function createChallenge(now = NOW) {
return createKwpOAuthChallenge(INPUT, { secret: SECRET, now: () => now });
}
function signedCookieFor(payload: unknown): string {
const body = Buffer.from(JSON.stringify({ v: "v2", p: payload }), "utf8").toString("base64url");
const signature = createHmac("sha256", SECRET).update(body).digest("base64url");
return `${body}.${signature}`;
}
describe("KWP OAuth challenge creation", () => {
it("creates the complete payload and derives PKCE exclusively with S256", () => {
const { payload } = createChallenge();
expect(payload).toMatchObject({ ...INPUT, createdAt: NOW });
expect(payload.state).toMatch(/^[0-9a-f]{64}$/u);
expect(payload.nonce).toMatch(/^[0-9a-f]{64}$/u);
expect(payload.codeVerifier).toMatch(/^[A-Za-z0-9._~-]{43,128}$/u);
expect(payload.codeChallenge).toBe(createHash("sha256").update(payload.codeVerifier, "ascii").digest("base64url"));
expect(payload.codeChallenge).not.toBe(payload.codeVerifier);
});
it("emits a host-prefixed HttpOnly SameSite=Lax cookie on HTTPS", () => {
const { cookie } = createChallenge();
expect(cookie).toContain(`${KWP_OAUTH_CHALLENGE_COOKIE}=`);
expect(cookie).toContain("Path=/");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).toContain("Max-Age=600");
expect(cookie).not.toContain("Domain=");
});
it("uses a distinct, host-only fallback cookie name on local HTTP", () => {
testWebConfig.nodeEnv = "development";
testWebConfig.routing.protocol = "http";
testWebConfig.routing.appBaseDomain = "localhost:3000";
const { cookie } = createChallenge();
expect(cookie).toContain(`${LOCAL_KWP_OAUTH_CHALLENGE_COOKIE}=`);
expect(cookie).not.toContain(KWP_OAUTH_CHALLENGE_COOKIE);
expect(cookie).not.toContain("Secure");
expect(cookie).not.toContain("Domain=");
});
});
describe("KWP OAuth challenge consumption", () => {
it("round-trips a fresh challenge and always returns a clear-cookie header", async () => {
const challenge = createChallenge();
const result = await consumeKwpOAuthChallenge(requestWithCookie(cookieValue(challenge.cookie)), challenge.payload.state, {
secret: SECRET,
now: () => NOW + 60_000,
});
expect(result).toEqual({
ok: true,
payload: challenge.payload,
clearCookie: expect.stringContaining(`${KWP_OAUTH_CHALLENGE_COOKIE}=`),
});
expect(result.clearCookie).toContain("Max-Age=0");
});
it("rejects a tampered signed body before trusting its tenant context", async () => {
const challenge = createChallenge();
const value = cookieValue(challenge.cookie);
const separator = value.lastIndexOf(".");
const tamperIndex = separator - 1;
const replacement = value[tamperIndex] === "A" ? "B" : "A";
const tampered = `${value.slice(0, tamperIndex)}${replacement}${value.slice(tamperIndex + 1)}`;
const result = await consumeKwpOAuthChallenge(requestWithCookie(tampered), challenge.payload.state, { secret: SECRET, now: () => NOW });
expect(result).toMatchObject({ ok: false, reason: "bad-signature" });
expect(result.clearCookie).toContain("Max-Age=0");
});
it.each([
["missing", new Request("https://app.example.test/integrations/kwp/oauth/callback"), "missing"],
["malformed", requestWithCookie("not-signed"), "malformed"],
["oversized", requestWithCookie("x".repeat(4_097)), "malformed"],
] as const)("rejects a %s cookie and still clears it", async (_case, request, reason) => {
const result = await consumeKwpOAuthChallenge(request, "a".repeat(64), { secret: SECRET, now: () => NOW });
expect(result).toMatchObject({ ok: false, reason });
expect(result.clearCookie).toContain("Max-Age=0");
});
it("rejects expired and implausibly future-dated challenges", async () => {
const expired = createChallenge();
const future = createChallenge(NOW + 60_001);
await expect(
consumeKwpOAuthChallenge(requestWithCookie(cookieValue(expired.cookie)), expired.payload.state, {
secret: SECRET,
now: () => NOW + KWP_OAUTH_CHALLENGE_TTL_MS,
}),
).resolves.toMatchObject({ ok: false, reason: "expired" });
await expect(
consumeKwpOAuthChallenge(requestWithCookie(cookieValue(future.cookie)), future.payload.state, { secret: SECRET, now: () => NOW }),
).resolves.toMatchObject({ ok: false, reason: "malformed" });
});
it("rejects a returned-state mismatch without consuming the valid nonce", async () => {
const challenge = createChallenge();
const request = requestWithCookie(cookieValue(challenge.cookie));
await expect(consumeKwpOAuthChallenge(request, "b".repeat(64), { secret: SECRET, now: () => NOW })).resolves.toMatchObject({
ok: false,
reason: "state-mismatch",
});
await expect(consumeKwpOAuthChallenge(request, challenge.payload.state, { secret: SECRET, now: () => NOW })).resolves.toMatchObject({ ok: true });
});
it("rejects validly signed payloads with extra, oversized, or inconsistent fields", async () => {
const { payload } = createChallenge();
const invalidPayloads: unknown[] = [
{ ...payload, unexpected: true },
{ ...payload, customerCode: "x".repeat(129) },
{ ...payload, customerCode: "geerkens.2" },
{ ...payload, connectionVersion: "2026-07-20" },
{ ...payload, codeChallenge: "A".repeat(43) },
];
for (const invalidPayload of invalidPayloads) {
await expect(
consumeKwpOAuthChallenge(requestWithCookie(signedCookieFor(invalidPayload)), payload.state, { secret: SECRET, now: () => NOW }),
).resolves.toMatchObject({ ok: false, reason: "malformed" });
}
});
it("claims the nonce with SET NX and the ten-minute TTL", async () => {
const set = vi.fn(async () => true);
__setKwpOAuthChallengeStoreForTests({ set });
const challenge = createChallenge();
await expect(
consumeKwpOAuthChallenge(requestWithCookie(cookieValue(challenge.cookie)), challenge.payload.state, { secret: SECRET, now: () => NOW }),
).resolves.toMatchObject({ ok: true });
expect(set).toHaveBeenCalledWith(expect.stringMatching(/^oauth:kwp:nonce:[0-9a-f]{64}$/u), expect.stringMatching(/^[0-9a-f]{64}$/u), {
nx: true,
ttlSeconds: 600,
});
expect(JSON.stringify(set.mock.calls)).not.toContain(challenge.payload.nonce);
});
it("rejects a sequential replay of the same nonce", async () => {
const challenge = createChallenge();
const request = requestWithCookie(cookieValue(challenge.cookie));
await expect(consumeKwpOAuthChallenge(request, challenge.payload.state, { secret: SECRET, now: () => NOW })).resolves.toMatchObject({ ok: true });
await expect(consumeKwpOAuthChallenge(request, challenge.payload.state, { secret: SECRET, now: () => NOW })).resolves.toMatchObject({
ok: false,
reason: "replayed",
});
});
it("allows exactly one of two parallel consumers to claim the nonce", async () => {
const challenge = createChallenge();
const request = requestWithCookie(cookieValue(challenge.cookie));
const results = await Promise.all([
consumeKwpOAuthChallenge(request, challenge.payload.state, { secret: SECRET, now: () => NOW }),
consumeKwpOAuthChallenge(request, challenge.payload.state, { secret: SECRET, now: () => NOW }),
]);
expect(results.filter((result) => result.ok)).toHaveLength(1);
expect(results.filter((result) => !result.ok && result.reason === "replayed")).toHaveLength(1);
expect(results.every((result) => result.clearCookie.includes("Max-Age=0"))).toBe(true);
});
it("fails closed when the distributed replay store is unavailable", async () => {
__setKwpOAuthChallengeStoreForTests({ set: () => Promise.reject(new Error("redis unavailable")) });
const challenge = createChallenge();
await expect(
consumeKwpOAuthChallenge(requestWithCookie(cookieValue(challenge.cookie)), challenge.payload.state, { secret: SECRET, now: () => NOW }),
).resolves.toMatchObject({ ok: false, reason: "store-unavailable" });
});
});
@@ -0,0 +1,320 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { isValidKwpContextCode } from "@hivegrid/integrations";
import type { SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
export const KWP_OAUTH_CHALLENGE_COOKIE = "__Host-hivegrid_kwp_oauth_challenge";
export const LOCAL_KWP_OAUTH_CHALLENGE_COOKIE = "hivegrid_kwp_oauth_challenge";
export const KWP_OAUTH_CHALLENGE_TTL_MS = 10 * 60 * 1_000;
const KWP_OAUTH_CHALLENGE_TTL_SECONDS = Math.ceil(KWP_OAUTH_CHALLENGE_TTL_MS / 1_000);
const KWP_OAUTH_CHALLENGE_FUTURE_SKEW_MS = 60 * 1_000;
const MAX_COOKIE_VALUE_LENGTH = 4_096;
const MAX_CONTEXT_ID_LENGTH = 256;
const MAX_TENANT_SLUG_LENGTH = 128;
const PAYLOAD_VERSION = "v2";
const STATE_PATTERN = /^[0-9a-f]{64}$/u;
const NONCE_PATTERN = /^[0-9a-f]{64}$/u;
const PKCE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/u;
const PKCE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
const TENANT_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]*$/u;
const CONNECTION_VERSION_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f]/u;
const PAYLOAD_KEYS = [
"tenantId",
"tenantSlug",
"userId",
"connectionId",
"connectionVersion",
"customerCode",
"state",
"nonce",
"codeVerifier",
"codeChallenge",
"createdAt",
] as const;
export interface KwpOAuthChallengePayload {
readonly tenantId: string;
readonly tenantSlug: string;
readonly userId: string;
readonly connectionId: string;
/** Exact DataConnection.updatedAt value used as an optimistic callback fence. */
readonly connectionVersion: string;
readonly customerCode: string;
readonly state: string;
readonly nonce: string;
readonly codeVerifier: string;
readonly codeChallenge: string;
/** Epoch milliseconds. */
readonly createdAt: number;
}
export type ConsumeKwpOAuthChallengeResult =
| { readonly ok: true; readonly payload: KwpOAuthChallengePayload; readonly clearCookie: string }
| {
readonly ok: false;
readonly reason: "missing" | "malformed" | "bad-signature" | "expired" | "state-mismatch" | "replayed" | "store-unavailable";
readonly clearCookie: string;
};
type CreateKwpOAuthChallengeOptions = {
readonly now?: () => number;
readonly secret?: string;
};
type ConsumeKwpOAuthChallengeOptions = {
readonly now?: () => number;
readonly secret?: string;
};
type KwpOAuthChallengeStore = Pick<SharedStore, "set">;
let storeFactory: () => KwpOAuthChallengeStore = () => getSharedStore();
/** Create a fresh state, nonce, and RFC 7636 PKCE-S256 tuple. */
export function createKwpOAuthChallenge(
input: Pick<KwpOAuthChallengePayload, "tenantId" | "tenantSlug" | "userId" | "connectionId" | "connectionVersion" | "customerCode">,
options: CreateKwpOAuthChallengeOptions = {},
): { readonly payload: KwpOAuthChallengePayload; readonly cookie: string } {
const codeVerifier = randomBytes(32).toString("base64url");
const payload: KwpOAuthChallengePayload = {
...input,
state: randomBytes(32).toString("hex"),
nonce: randomBytes(32).toString("hex"),
codeVerifier,
codeChallenge: derivePkceS256Challenge(codeVerifier),
createdAt: options.now ? options.now() : Date.now(),
};
if (!isKwpOAuthChallengePayload(payload)) {
throw new TypeError("KWP OAuth challenge input is invalid");
}
return {
payload,
cookie: serializeKwpOAuthChallengeCookie(payload, options.secret),
};
}
/** Serialize a signed, host-only challenge cookie. The payload is not encrypted. */
export function serializeKwpOAuthChallengeCookie(payload: KwpOAuthChallengePayload, secretOverride?: string): string {
if (!isKwpOAuthChallengePayload(payload)) {
throw new TypeError("KWP OAuth challenge payload is invalid");
}
const body = Buffer.from(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }), "utf8").toString("base64url");
const value = `${body}.${sign(body, signingSecret(secretOverride))}`;
return serializeCookie(value, KWP_OAUTH_CHALLENGE_TTL_SECONDS);
}
/** Clear whichever host-only cookie name is valid for the active environment. */
export function clearKwpOAuthChallengeCookie(): string {
return serializeCookie("", 0);
}
/**
* Verify the signed cookie and returned state, then claim its nonce exactly
* once across replicas. Every result includes a cookie deletion header.
*/
export async function consumeKwpOAuthChallenge(
request: Request,
returnedState: string | null | undefined,
options: ConsumeKwpOAuthChallengeOptions = {},
): Promise<ConsumeKwpOAuthChallengeResult> {
const clearCookie = clearKwpOAuthChallengeCookie();
const failed = (reason: Exclude<ConsumeKwpOAuthChallengeResult, { ok: true }>["reason"]): ConsumeKwpOAuthChallengeResult => ({
ok: false,
reason,
clearCookie,
});
const cookie = readCookieValue(request, cookiePolicy().name);
if (cookie.status !== "found") return failed(cookie.status);
if (cookie.value.length > MAX_COOKIE_VALUE_LENGTH) return failed("malformed");
const separator = cookie.value.lastIndexOf(".");
if (separator <= 0 || separator === cookie.value.length - 1) return failed("malformed");
const body = cookie.value.slice(0, separator);
const receivedSignature = cookie.value.slice(separator + 1);
if (!/^[A-Za-z0-9_-]+$/u.test(body) || !PKCE_CHALLENGE_PATTERN.test(receivedSignature)) return failed("malformed");
let expectedSignature: string;
try {
expectedSignature = sign(body, signingSecret(options.secret));
} catch {
return failed("malformed");
}
if (!safeStringEqual(receivedSignature, expectedSignature)) return failed("bad-signature");
let decoded: unknown;
try {
decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
} catch {
return failed("malformed");
}
if (!isChallengeEnvelope(decoded)) return failed("malformed");
const payload = decoded.p;
const now = options.now ? options.now() : Date.now();
const age = now - payload.createdAt;
if (age < -KWP_OAUTH_CHALLENGE_FUTURE_SKEW_MS) return failed("malformed");
if (age >= KWP_OAUTH_CHALLENGE_TTL_MS) return failed("expired");
if (!STATE_PATTERN.test(returnedState ?? "") || !safeStringEqual(returnedState ?? "", payload.state)) {
return failed("state-mismatch");
}
let claimed: boolean;
try {
claimed = await storeFactory().set(nonceClaimKey(payload.nonce), stateFingerprint(payload.state), {
nx: true,
ttlSeconds: KWP_OAUTH_CHALLENGE_TTL_SECONDS,
});
} catch {
return failed("store-unavailable");
}
if (!claimed) return failed("replayed");
return { ok: true, payload, clearCookie };
}
function derivePkceS256Challenge(codeVerifier: string): string {
return createHash("sha256").update(codeVerifier, "ascii").digest("base64url");
}
function signingSecret(override?: string): string {
if (override) return override;
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
const secret = cryptoSecret || sessionSecret;
if (!secret) throw new Error("CRYPTO_SECRET or SESSION_SECRET is required for KWP OAuth challenges");
return secret;
}
function sign(body: string, secret: string): string {
return createHmac("sha256", secret).update(body).digest("base64url");
}
function stateFingerprint(state: string): string {
return createHash("sha256").update(state, "ascii").digest("hex");
}
function nonceClaimKey(nonce: string): string {
const fingerprint = createHash("sha256").update(nonce, "ascii").digest("hex");
return `oauth:kwp:nonce:${fingerprint}`;
}
function safeStringEqual(actual: string, expected: string): boolean {
const actualBytes = Buffer.from(actual, "utf8");
const expectedBytes = Buffer.from(expected, "utf8");
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
}
function cookiePolicy() {
const webConfig = loadRequiredWebConfig();
return resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: KWP_OAUTH_CHALLENGE_COOKIE,
localName: LOCAL_KWP_OAUTH_CHALLENGE_COOKIE,
maxAge: KWP_OAUTH_CHALLENGE_TTL_SECONDS,
});
}
function serializeCookie(value: string, maxAge: number): string {
const policy = cookiePolicy();
const attributes = [`${policy.name}=${value}`, `Path=${policy.path}`, "HttpOnly", `SameSite=${capitalize(policy.sameSite)}`, `Max-Age=${maxAge}`];
if (policy.secure) attributes.push("Secure");
return attributes.join("; ");
}
function capitalize(value: string): string {
return `${value.slice(0, 1).toUpperCase()}${value.slice(1)}`;
}
function readCookieValue(request: Request, name: string):
| { readonly status: "found"; readonly value: string }
| { readonly status: "missing" | "malformed" } {
const header = request.headers.get("cookie");
if (!header) return { status: "missing" };
const matches: string[] = [];
for (const part of header.split(/;\s*/u)) {
const separator = part.indexOf("=");
if (separator < 0) continue;
if (part.slice(0, separator).trim() === name) matches.push(part.slice(separator + 1).trim());
}
if (matches.length === 0) return { status: "missing" };
if (matches.length !== 1 || !matches[0]) return { status: "malformed" };
return { status: "found", value: matches[0] };
}
function isChallengeEnvelope(value: unknown): value is { readonly v: typeof PAYLOAD_VERSION; readonly p: KwpOAuthChallengePayload } {
if (!isRecord(value) || !hasExactKeys(value, ["v", "p"])) return false;
return value.v === PAYLOAD_VERSION && isKwpOAuthChallengePayload(value.p);
}
function isKwpOAuthChallengePayload(value: unknown): value is KwpOAuthChallengePayload {
if (!isRecord(value) || !hasExactKeys(value, PAYLOAD_KEYS)) return false;
const codeVerifier = value.codeVerifier;
const codeChallenge = value.codeChallenge;
if (
!boundedContextString(value.tenantId, MAX_CONTEXT_ID_LENGTH) ||
!boundedPatternString(value.tenantSlug, MAX_TENANT_SLUG_LENGTH, TENANT_SLUG_PATTERN) ||
!boundedContextString(value.userId, MAX_CONTEXT_ID_LENGTH) ||
!boundedContextString(value.connectionId, MAX_CONTEXT_ID_LENGTH) ||
!isCanonicalConnectionVersion(value.connectionVersion) ||
!isValidKwpContextCode(value.customerCode) ||
!STATE_PATTERN.test(typeof value.state === "string" ? value.state : "") ||
!NONCE_PATTERN.test(typeof value.nonce === "string" ? value.nonce : "") ||
typeof codeVerifier !== "string" ||
!PKCE_VERIFIER_PATTERN.test(codeVerifier) ||
typeof codeChallenge !== "string" ||
!PKCE_CHALLENGE_PATTERN.test(codeChallenge) ||
typeof value.createdAt !== "number" ||
!Number.isSafeInteger(value.createdAt) ||
value.createdAt < 0
) {
return false;
}
return safeStringEqual(derivePkceS256Challenge(codeVerifier), codeChallenge);
}
function isCanonicalConnectionVersion(value: unknown): value is string {
if (typeof value !== "string" || !CONNECTION_VERSION_PATTERN.test(value)) return false;
const timestamp = Date.parse(value);
return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
}
function boundedContextString(value: unknown, maxLength: number): value is string {
return (
typeof value === "string" &&
value.length > 0 &&
value.length <= maxLength &&
value.trim() === value &&
!CONTROL_CHARACTER_PATTERN.test(value)
);
}
function boundedPatternString(value: unknown, maxLength: number, pattern: RegExp): value is string {
return boundedContextString(value, maxLength) && pattern.test(value);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function hasExactKeys(value: Record<string, unknown>, expected: readonly string[]): boolean {
const keys = Object.keys(value);
return keys.length === expected.length && expected.every((key) => Object.hasOwn(value, key));
}
export function __setKwpOAuthChallengeStoreForTests(store: KwpOAuthChallengeStore): void {
storeFactory = () => store;
}
export function __resetKwpOAuthChallengeStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -0,0 +1,458 @@
import type { WebConfig } from "@hivegrid/config";
import { Issuer, type AuthorizationParameters, type Client, type ClientMetadata, type TokenSet } from "openid-client";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const configMocks = vi.hoisted(() => ({
loadRequiredWebConfig: vi.fn(),
}));
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: configMocks.loadRequiredWebConfig,
}));
import {
__resetKwpOidcClientForTests,
__setKwpOidcDiscoveryForTests,
buildKwpAuthorizationUrl,
exchangeKwpAuthorizationCode,
getKwpOidcClient,
KwpOidcClientError,
readKwpOidcRuntimeConfig,
} from "./kwpOidcClient.server";
const ISSUER = "https://id.kwp-online.de/realms/kwp-federated";
const AUTHORIZATION_ENDPOINT = `${ISSUER}/protocol/openid-connect/auth`;
const TOKEN_ENDPOINT = `${ISSUER}/protocol/openid-connect/token`;
const JWKS_URI = `${ISSUER}/protocol/openid-connect/certs`;
const CANONICAL_SCOPES = "openid adresse-extern archiv-extern termin-extern vorgang-extern aktivitaet-extern offline_access";
const SHUFFLED_SCOPES = " offline_access aktivitaet-extern openid vorgang-extern adresse-extern termin-extern archiv-extern ";
const SHUFFLED_RETURNED_SCOPES = "offline_access aktivitaet-extern openid vorgang-extern adresse-extern termin-extern archiv-extern";
const DOMAIN_SCOPES = "adresse-extern archiv-extern termin-extern vorgang-extern aktivitaet-extern";
const REDIRECT_URI = "https://app.example.test/integrations/kwp/oauth/callback";
type KwpWebConfig = Pick<WebConfig, "kwp" | "routing">;
type DiscoveredIssuer = Awaited<ReturnType<typeof Issuer.discover>>;
const INVALID_DISCOVERY_CONTRACTS: ReadonlyArray<readonly [string, Record<string, unknown>]> = [
["authorization endpoint", { authorization_endpoint: `${AUTHORIZATION_ENDPOINT}/unexpected` }],
["token endpoint", { token_endpoint: `${TOKEN_ENDPOINT}/unexpected` }],
["JWKS URI", { jwks_uri: `${JWKS_URI}/unexpected` }],
["PKCE S256 support", { code_challenge_methods_supported: ["plain"] }],
["authorization_code grant", { grant_types_supported: ["refresh_token"] }],
["refresh_token grant", { grant_types_supported: ["authorization_code"] }],
["client_secret_post authentication", { token_endpoint_auth_methods_supported: ["client_secret_basic"] }],
["advertised capability metadata", { code_challenge_methods_supported: undefined }],
];
function makeDiscoveryMetadata(overrides: Record<string, unknown> = {}): DiscoveredIssuer["metadata"] {
return {
issuer: ISSUER,
authorization_endpoint: AUTHORIZATION_ENDPOINT,
token_endpoint: TOKEN_ENDPOINT,
jwks_uri: JWKS_URI,
code_challenge_methods_supported: ["S256"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["client_secret_post"],
...overrides,
};
}
function makeWebConfig(kwp: Partial<NonNullable<WebConfig["kwp"]>> = {}): KwpWebConfig {
return {
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
portalAppHost: "portal.example.test",
protocol: "https",
},
kwp: {
clientId: "kwp-client",
clientSecret: "kwp-secret",
scopes: SHUFFLED_SCOPES,
customerCode: "customer-code",
oidcIssuer: ISSUER,
hiveGridTenantId: "tenant-geerkens",
...kwp,
},
};
}
describe("KWP OIDC client", () => {
let authorizationUrl: ReturnType<typeof vi.fn<(parameters?: AuthorizationParameters) => string>>;
let callback: ReturnType<typeof vi.fn<Client["callback"]>>;
let client: Client;
let clientMetadata: ClientMetadata[];
let discover: ReturnType<typeof vi.fn<(issuer: string) => Promise<DiscoveredIssuer>>>;
beforeEach(() => {
__resetKwpOidcClientForTests();
vi.clearAllMocks();
vi.spyOn(Date, "now").mockReturnValue(1_899_999_940_000);
configMocks.loadRequiredWebConfig.mockReturnValue(makeWebConfig() as WebConfig);
clientMetadata = [];
authorizationUrl = vi.fn((parameters = {}) => {
const url = new URL(AUTHORIZATION_ENDPOINT);
for (const [name, value] of Object.entries(parameters)) {
if (value !== undefined) url.searchParams.set(name, String(value));
}
return url.toString();
});
callback = vi.fn();
client = { authorizationUrl, callback } as unknown as Client;
const ClientConstructor = vi.fn(function (metadata: ClientMetadata) {
clientMetadata.push(metadata);
return client;
});
discover = vi.fn(async () => ({ metadata: makeDiscoveryMetadata(), Client: ClientConstructor }) as unknown as DiscoveredIssuer);
__setKwpOidcDiscoveryForTests(discover);
});
afterEach(() => {
__resetKwpOidcClientForTests();
vi.restoreAllMocks();
});
test("requires all five provider values, derives the callback, and normalizes scope order", () => {
expect(readKwpOidcRuntimeConfig(makeWebConfig())).toEqual({
issuer: ISSUER,
clientId: "kwp-client",
clientSecret: "kwp-secret",
customerCode: "customer-code",
hiveGridTenantId: "tenant-geerkens",
scopes: CANONICAL_SCOPES,
redirectUri: REDIRECT_URI,
});
expect(() => readKwpOidcRuntimeConfig(makeWebConfig({ clientSecret: undefined }))).toThrowError(
expect.objectContaining({ code: "missing-config", message: expect.stringContaining("KWP_OAUTH_CLIENT_SECRET") })
);
expect(() => readKwpOidcRuntimeConfig(makeWebConfig({ hiveGridTenantId: undefined }))).toThrowError(
expect.objectContaining({ code: "missing-config", message: expect.stringContaining("KWP_HIVEGRID_TENANT_ID") })
);
});
test("ignores the deprecated process mandant and rejects malformed tenant-bound identifiers", () => {
expect(readKwpOidcRuntimeConfig(makeWebConfig({ mandant: " legacy-mandant " }))).toEqual(
readKwpOidcRuntimeConfig(makeWebConfig()),
);
for (const kwp of [
{ hiveGridTenantId: "tenant/id" },
{ hiveGridTenantId: `t${"_".repeat(256)}` },
{ customerCode: "customer.code" },
]) {
expect(() => readKwpOidcRuntimeConfig(makeWebConfig(kwp))).toThrowError(expect.objectContaining({ code: "invalid-input" }));
}
});
test("adds the technical openid and offline_access scopes to the five configured domain scopes", () => {
const config = makeWebConfig({ scopes: "termin-extern vorgang-extern adresse-extern aktivitaet-extern archiv-extern" });
expect(readKwpOidcRuntimeConfig(config).scopes).toBe(CANONICAL_SCOPES);
});
test("rejects every issuer except the exact approved federated realm", () => {
for (const oidcIssuer of [`${ISSUER}/`, "https://id.kwp-online.de/realms/other", "http://id.kwp-online.de/realms/kwp-federated"]) {
expect(() => readKwpOidcRuntimeConfig(makeWebConfig({ oidcIssuer }))).toThrowError(expect.objectContaining({ code: "invalid-issuer" }));
}
});
test.each([
["missing required scope", "openid adresse-extern archiv-extern termin-extern vorgang-extern offline_access"],
["unknown email scope", `${CANONICAL_SCOPES} email`],
["unapproved plural and project scopes", "openid adressen-extern aktivitaeten-extern archiv-extern projekt-extern termin-extern offline_access"],
])("rejects %s", (_name, scopes) => {
expect(() => readKwpOidcRuntimeConfig(makeWebConfig({ scopes }))).toThrowError(expect.objectContaining({ code: "invalid-scope" }));
});
test("discovers the exact issuer and caches a code-flow client using client_secret_post", async () => {
const first = await getKwpOidcClient();
const second = await getKwpOidcClient();
expect(first).toBe(client);
expect(second).toBe(client);
expect(discover).toHaveBeenCalledTimes(1);
expect(discover).toHaveBeenCalledWith(ISSUER);
expect(clientMetadata).toEqual([
{
client_id: "kwp-client",
client_secret: "kwp-secret",
redirect_uris: [REDIRECT_URI],
response_types: ["code"],
token_endpoint_auth_method: "client_secret_post",
},
]);
await getKwpOidcClient(readKwpOidcRuntimeConfig(makeWebConfig({ clientSecret: "rotated-secret" })));
expect(discover).toHaveBeenCalledTimes(2);
});
test("rejects discovery metadata whose issuer differs from the approved issuer", async () => {
__setKwpOidcDiscoveryForTests(
vi.fn(async () => ({ metadata: makeDiscoveryMetadata({ issuer: `${ISSUER}/` }), Client: vi.fn() }) as unknown as DiscoveredIssuer)
);
await expect(getKwpOidcClient()).rejects.toMatchObject({ code: "issuer-mismatch" });
});
test.each(INVALID_DISCOVERY_CONTRACTS)("rejects discovery metadata without the exact %s contract", async (_name, overrides) => {
const ClientConstructor = vi.fn();
__setKwpOidcDiscoveryForTests(
vi.fn(async () => ({ metadata: makeDiscoveryMetadata(overrides), Client: ClientConstructor }) as unknown as DiscoveredIssuer)
);
await expect(getKwpOidcClient()).rejects.toMatchObject({ code: "discovery-contract-mismatch" });
expect(ClientConstructor).not.toHaveBeenCalled();
});
test("builds authorization URL with canonical scopes, PKCE-S256, state, nonce, and tenant", async () => {
const result = await buildKwpAuthorizationUrl({
state: "state-value",
nonce: "nonce-value",
codeChallenge: "code-challenge-value",
customerCode: "customer-code",
});
expect(authorizationUrl).toHaveBeenCalledWith({
response_type: "code",
redirect_uri: REDIRECT_URI,
scope: CANONICAL_SCOPES,
state: "state-value",
nonce: "nonce-value",
code_challenge: "code-challenge-value",
code_challenge_method: "S256",
tenant: "customer-code",
});
const url = new URL(result);
expect(url.searchParams.get("scope")).toBe(CANONICAL_SCOPES);
expect(url.searchParams.get("tenant")).toBe("customer-code");
});
test("refuses an authorization customer code that differs from runtime config", async () => {
await expect(
buildKwpAuthorizationUrl({ state: "state-value", nonce: "nonce-value", codeChallenge: "challenge", customerCode: "other-customer" })
).rejects.toMatchObject({ code: "invalid-input" });
expect(authorizationUrl).not.toHaveBeenCalled();
});
test("exchanges and verifies callback parameters and returns compatible encrypted-credential fields", async () => {
callback.mockResolvedValue({
access_token: "access-token",
refresh_token: "refresh-token",
expires_at: 1_900_000_000,
scope: SHUFFLED_RETURNED_SCOPES,
} as TokenSet);
const result = await exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
);
expect(callback).toHaveBeenCalledWith(
REDIRECT_URI,
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", code_verifier: "code-verifier" }
);
expect(result).toEqual({
credentials: {
accessToken: "access-token",
refreshToken: "refresh-token",
expiresAt: new Date(1_900_000_000 * 1_000).toISOString(),
issuer: ISSUER,
clientId: "kwp-client",
clientSecret: "kwp-secret",
customerCode: "customer-code",
scopes: CANONICAL_SCOPES.split(" "),
},
tokenExpiresAt: new Date(1_900_000_000 * 1_000),
});
});
test("passes the callback code and state to openid-client with all challenge checks", async () => {
const params = { code: "authorization-code", state: "state-value", iss: ISSUER };
callback.mockResolvedValue({
access_token: "access-token",
refresh_token: "refresh-token",
expires_at: 1_900_000_000,
} as TokenSet);
await exchangeKwpAuthorizationCode(params, {
state: "state-value",
nonce: "nonce-value",
codeVerifier: "code-verifier",
customerCode: "customer-code",
});
expect(callback).toHaveBeenCalledWith(REDIRECT_URI, params, {
state: "state-value",
nonce: "nonce-value",
code_verifier: "code-verifier",
});
});
test("accepts openid-client's elapsed 299-second expires_in getter", async () => {
callback.mockResolvedValue({
access_token: "access-token",
refresh_token: "refresh-token",
expires_at: 1_900_000_239,
get expires_in() {
return this.expires_at - Math.floor(Date.now() / 1_000);
},
} as TokenSet);
await expect(
exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
)
).resolves.toMatchObject({ tokenExpiresAt: new Date(1_900_000_239 * 1_000) });
});
test("keeps the exchanged credential bundle unconfirmed until the user selects a mandant", async () => {
configMocks.loadRequiredWebConfig.mockReturnValue(makeWebConfig({ mandant: "mandant-1" }) as WebConfig);
callback.mockResolvedValue({
access_token: "access-token",
refresh_token: "refresh-token",
expires_at: 1_900_000_000,
scope: CANONICAL_SCOPES,
} as TokenSet);
const result = await exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
);
expect(result.credentials).toMatchObject({ customerCode: "customer-code" });
expect(result.credentials).not.toHaveProperty("mandant");
expect(result.credentials).not.toHaveProperty("mandantBinding");
});
test.each([
["domain scopes only", DOMAIN_SCOPES],
["openid only as technical scope", `openid ${DOMAIN_SCOPES}`],
["offline_access only as technical scope", `${DOMAIN_SCOPES} offline_access`],
["both technical scopes", SHUFFLED_RETURNED_SCOPES],
["mixed repeated whitespace", `\topenid ${DOMAIN_SCOPES.replaceAll(" ", "\n ")}\toffline_access\n`],
])("accepts a callback scope echo with %s and persists the canonical policy", async (_name, scope) => {
callback.mockResolvedValue({
access_token: "access-token",
refresh_token: "refresh-token",
expires_at: 1_900_000_000,
scope,
} as TokenSet);
const result = await exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" },
);
expect(result.credentials.scopes).toEqual(CANONICAL_SCOPES.split(" "));
});
test("accepts an omitted callback scope echo and persists the canonical policy", async () => {
callback.mockResolvedValue({
access_token: "access-token",
refresh_token: "refresh-token",
expires_at: 1_900_000_000,
} as TokenSet);
const result = await exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" },
);
expect(result.credentials.scopes).toEqual(CANONICAL_SCOPES.split(" "));
});
test.each([
["missing access token", { refresh_token: "refresh", expires_at: 1_900_000_000, scope: CANONICAL_SCOPES }, "missing_access_token"],
["missing refresh token", { access_token: "access", expires_at: 1_900_000_000, scope: CANONICAL_SCOPES }, "missing_refresh_token"],
["missing expiry", { access_token: "access", refresh_token: "refresh", scope: CANONICAL_SCOPES }, "invalid_expiry"],
["oversized expires_in", { access_token: "access", refresh_token: "refresh", expires_in: 301, scope: CANONICAL_SCOPES }, "invalid_expiry"],
["fractional expires_in", { access_token: "access", refresh_token: "refresh", expires_in: 300.5, scope: CANONICAL_SCOPES }, "invalid_expiry"],
["negative expires_in", { access_token: "access", refresh_token: "refresh", expires_in: -1, scope: CANONICAL_SCOPES }, "invalid_expiry"],
[
"implausibly distant expires_at",
{ access_token: "access", refresh_token: "refresh", expires_at: 1_900_000_241, scope: CANONICAL_SCOPES },
"invalid_expiry",
],
["returned empty scope", { access_token: "access", refresh_token: "refresh", expires_at: 1_900_000_000, scope: "" }, "scope_mismatch"],
["returned whitespace-only scope", { access_token: "access", refresh_token: "refresh", expires_at: 1_900_000_000, scope: " \t\n " }, "scope_mismatch"],
[
"returned scope missing a domain scope",
{ access_token: "access", refresh_token: "refresh", expires_at: 1_900_000_000, scope: "adresse-extern archiv-extern termin-extern vorgang-extern" },
"scope_mismatch",
],
[
"unknown returned scope",
{ access_token: "access", refresh_token: "refresh", expires_at: 1_900_000_000, scope: `${CANONICAL_SCOPES} email` },
"scope_mismatch",
],
[
"duplicate returned scope",
{ access_token: "access", refresh_token: "refresh", expires_at: 1_900_000_000, scope: `${DOMAIN_SCOPES} adresse-extern` },
"scope_mismatch",
],
[
"wrongly capitalized returned scope",
{
access_token: "access",
refresh_token: "refresh",
expires_at: 1_900_000_000,
scope: "Adresse-extern archiv-extern termin-extern vorgang-extern aktivitaet-extern",
},
"scope_mismatch",
],
])("rejects a token response with %s", async (_name, tokenSet, diagnosticCode) => {
callback.mockResolvedValue(tokenSet as TokenSet);
await expect(
exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
)
).rejects.toMatchObject({ code: "invalid-token-response", diagnosticCode });
});
test("wraps callback failures without exposing provider response details in the message", async () => {
callback.mockRejectedValue(Object.assign(new Error("authorization-code-secret"), { name: "OPError", error: "invalid_grant" }));
let error: unknown;
try {
await exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
);
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(KwpOidcClientError);
expect(error).toMatchObject({ code: "callback-failed", diagnosticCode: "provider_invalid_grant" });
expect((error as Error).message).not.toContain("authorization-code-secret");
});
test.each(["constructor", "toString"])("does not treat inherited provider error key %s as an allowlisted diagnostic", async (providerError) => {
callback.mockRejectedValue(Object.assign(new Error("provider-response-secret"), { error: providerError }));
await expect(
exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
)
).rejects.toMatchObject({ code: "callback-failed", diagnosticCode: "token_exchange_failed" });
});
test("uses a neutral diagnostic for openid-client relying-party errors", async () => {
callback.mockRejectedValue(Object.assign(new Error("provider-response-secret"), { name: "RPError" }));
await expect(
exchangeKwpAuthorizationCode(
{ code: "authorization-code", state: "state-value" },
{ state: "state-value", nonce: "nonce-value", codeVerifier: "code-verifier", customerCode: "customer-code" }
)
).rejects.toMatchObject({ code: "callback-failed", diagnosticCode: "oidc_rp_error" });
});
});
@@ -0,0 +1,422 @@
import { createHash } from "node:crypto";
import { loadRequiredWebConfig, type WebConfig } from "@hivegrid/config";
import {
KWP_OIDC_ISSUER,
KWP_REQUIRED_OAUTH_SCOPES,
isValidKwpContextCode,
isValidKwpReturnedOAuthScopes,
type KwpCredentials as IntegrationKwpCredentials,
} from "@hivegrid/integrations";
import { Issuer, type CallbackParamsType, type Client, type TokenSet } from "openid-client";
import { KWP_OAUTH_CALLBACK_PATH } from "~/utils/integrations/integrationsRoutePaths";
const KWP_AUTHORIZATION_ENDPOINT = `${KWP_OIDC_ISSUER}/protocol/openid-connect/auth`;
const KWP_TOKEN_ENDPOINT = `${KWP_OIDC_ISSUER}/protocol/openid-connect/token`;
const KWP_JWKS_URI = `${KWP_OIDC_ISSUER}/protocol/openid-connect/certs`;
const KWP_SCOPE_ORDER = KWP_REQUIRED_OAUTH_SCOPES;
const KWP_SCOPE_SET = new Set<string>(KWP_SCOPE_ORDER);
const KWP_DOMAIN_SCOPES = KWP_SCOPE_ORDER.filter((scope) => scope.endsWith("-extern"));
const HIVEGRID_TENANT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,255}$/u;
const KWP_ACCESS_TOKEN_TTL_SECONDS = 5 * 60;
type KwpOidcClientErrorCode =
| "missing-config"
| "invalid-issuer"
| "invalid-scope"
| "invalid-input"
| "discovery-failed"
| "issuer-mismatch"
| "discovery-contract-mismatch"
| "client-init-failed"
| "authorization-failed"
| "callback-failed"
| "invalid-token-response";
export type KwpOidcDiagnosticCode =
| "provider_access_denied"
| "provider_invalid_client"
| "provider_invalid_grant"
| "provider_invalid_scope"
| "provider_server_error"
| "provider_temporarily_unavailable"
| "provider_unauthorized_client"
| "oidc_rp_error"
| "token_exchange_failed"
| "missing_access_token"
| "missing_refresh_token"
| "invalid_expiry"
| "scope_mismatch";
export class KwpOidcClientError extends Error {
readonly code: KwpOidcClientErrorCode;
readonly diagnosticCode?: KwpOidcDiagnosticCode;
constructor(code: KwpOidcClientErrorCode, message: string, options?: { cause?: unknown; diagnosticCode?: KwpOidcDiagnosticCode }) {
super(message, options);
this.name = "KwpOidcClientError";
this.code = code;
this.diagnosticCode = options?.diagnosticCode;
}
}
export type KwpOidcRuntimeConfig = {
readonly issuer: typeof KWP_OIDC_ISSUER;
readonly clientId: string;
readonly clientSecret: string;
readonly customerCode: string;
readonly hiveGridTenantId: string;
readonly scopes: string;
readonly redirectUri: string;
};
export type KwpAuthorizationPayload = {
readonly state: string;
readonly nonce: string;
readonly codeChallenge: string;
readonly customerCode: string;
};
export type KwpAuthorizationCodeChecks = {
readonly state: string;
readonly nonce: string;
readonly codeVerifier: string;
readonly customerCode: string;
};
export type KwpAuthorizationCallbackParameters = {
readonly code: string;
readonly state: string;
readonly iss?: string;
};
export type KwpCredentials = IntegrationKwpCredentials;
export type KwpAuthorizationCodeExchangeResult = {
readonly credentials: KwpCredentials;
readonly tokenExpiresAt: Date;
};
type KwpWebConfig = Pick<WebConfig, "kwp" | "routing">;
type DiscoveredIssuer = Awaited<ReturnType<typeof Issuer.discover>>;
type DiscoverIssuer = (issuer: string) => Promise<DiscoveredIssuer>;
const defaultDiscoverIssuer: DiscoverIssuer = (issuer) => Issuer.discover(issuer);
let discoverIssuer: DiscoverIssuer = defaultDiscoverIssuer;
let cachedClient: Promise<Client> | null = null;
let cachedClientFingerprint: string | null = null;
/** Read and strictly validate the process-wide KWP OAuth provider contract. */
export function readKwpOidcRuntimeConfig(config: KwpWebConfig = loadRequiredWebConfig()): KwpOidcRuntimeConfig {
const clientId = present(config.kwp?.clientId);
const clientSecret = present(config.kwp?.clientSecret);
const rawScopes = present(config.kwp?.scopes);
const customerCode = present(config.kwp?.customerCode);
const oidcIssuer = present(config.kwp?.oidcIssuer);
const hiveGridTenantId = present(config.kwp?.hiveGridTenantId);
const missing = [
["KWP_OAUTH_CLIENT_ID", clientId],
["KWP_OAUTH_CLIENT_SECRET", clientSecret],
["KWP_OAUTH_SCOPES", rawScopes],
["KWP_CUSTOMER_CODE", customerCode],
["KWP_OIDC_ISSUER", oidcIssuer],
["KWP_HIVEGRID_TENANT_ID", hiveGridTenantId],
]
.filter((entry): entry is [string, undefined] => entry[1] === undefined)
.map(([name]) => name);
if (!clientId || !clientSecret || !rawScopes || !customerCode || !oidcIssuer || !hiveGridTenantId) {
throw new KwpOidcClientError("missing-config", `KWP OAuth configuration is incomplete: missing ${missing.join(", ")}.`);
}
if (oidcIssuer !== KWP_OIDC_ISSUER) {
throw new KwpOidcClientError("invalid-issuer", "KWP_OIDC_ISSUER must match the approved KWP federated realm exactly.");
}
if (!HIVEGRID_TENANT_ID_PATTERN.test(hiveGridTenantId) || !isValidKwpContextCode(customerCode)) {
throw new KwpOidcClientError("invalid-input", "The configured tenant or KWP context identifier is invalid.");
}
return {
issuer: KWP_OIDC_ISSUER,
clientId,
clientSecret,
customerCode,
hiveGridTenantId,
scopes: normalizeConfiguredScopes(rawScopes),
redirectUri: `${config.routing.protocol}://${config.routing.webAppHost}${KWP_OAUTH_CALLBACK_PATH}`,
};
}
/** Discover and cache the verified KWP OIDC client for the active configuration. */
export async function getKwpOidcClient(runtimeConfig: KwpOidcRuntimeConfig = readKwpOidcRuntimeConfig()): Promise<Client> {
const fingerprint = runtimeFingerprint(runtimeConfig);
if (cachedClient && cachedClientFingerprint === fingerprint) {
return cachedClient;
}
const pendingClient = initializeClient(runtimeConfig);
cachedClient = pendingClient;
cachedClientFingerprint = fingerprint;
try {
return await pendingClient;
} catch (error) {
if (cachedClient === pendingClient) {
cachedClient = null;
cachedClientFingerprint = null;
}
throw error;
}
}
/** Build the Authorization Code + PKCE request for KWP Keycloak. */
export async function buildKwpAuthorizationUrl(payload: KwpAuthorizationPayload): Promise<string> {
const runtimeConfig = readKwpOidcRuntimeConfig();
requireInput("state", payload.state);
requireInput("nonce", payload.nonce);
requireInput("codeChallenge", payload.codeChallenge);
requireInput("customerCode", payload.customerCode);
if (payload.customerCode !== runtimeConfig.customerCode) {
throw new KwpOidcClientError("invalid-input", "The KWP authorization customer code does not match the configured connection.");
}
const client = await getKwpOidcClient(runtimeConfig);
try {
return client.authorizationUrl({
response_type: "code",
redirect_uri: runtimeConfig.redirectUri,
scope: runtimeConfig.scopes,
state: payload.state,
nonce: payload.nonce,
code_challenge: payload.codeChallenge,
code_challenge_method: "S256",
tenant: runtimeConfig.customerCode,
});
} catch (cause) {
throw new KwpOidcClientError("authorization-failed", "The KWP authorization request could not be created.", { cause });
}
}
/** Exchange and verify the returned KWP authorization response. */
export async function exchangeKwpAuthorizationCode(
callbackInput: KwpAuthorizationCallbackParameters,
checks: KwpAuthorizationCodeChecks
): Promise<KwpAuthorizationCodeExchangeResult> {
const runtimeConfig = readKwpOidcRuntimeConfig();
requireInput("code", callbackInput.code);
requireInput("callback state", callbackInput.state);
requireInput("state", checks.state);
requireInput("nonce", checks.nonce);
requireInput("codeVerifier", checks.codeVerifier);
requireInput("customerCode", checks.customerCode);
if (checks.customerCode !== runtimeConfig.customerCode) {
throw new KwpOidcClientError("invalid-input", "The KWP callback customer code does not match the configured connection.");
}
const client = await getKwpOidcClient(runtimeConfig);
let tokenSet: TokenSet;
try {
const callbackParams: CallbackParamsType = {
code: callbackInput.code,
state: callbackInput.state,
...(callbackInput.iss ? { iss: callbackInput.iss } : {}),
};
tokenSet = await client.callback(runtimeConfig.redirectUri, callbackParams, {
state: checks.state,
nonce: checks.nonce,
code_verifier: checks.codeVerifier,
});
} catch (cause) {
throw new KwpOidcClientError("callback-failed", "The KWP authorization response could not be verified or exchanged.", {
cause,
diagnosticCode: callbackFailureDiagnosticCode(cause),
});
}
const accessToken = requiredToken(tokenSet.access_token, "access token", "missing_access_token");
const refreshToken = requiredToken(tokenSet.refresh_token, "refresh token", "missing_refresh_token");
const expiresAt = tokenExpiry(tokenSet);
if (tokenSet.scope !== undefined && !isValidKwpReturnedOAuthScopes(tokenSet.scope)) {
throw new KwpOidcClientError("invalid-token-response", "The returned KWP OAuth scope set is invalid.", {
diagnosticCode: "scope_mismatch",
});
}
return {
credentials: {
accessToken,
refreshToken,
expiresAt: expiresAt.toISOString(),
issuer: runtimeConfig.issuer,
clientId: runtimeConfig.clientId,
clientSecret: runtimeConfig.clientSecret,
customerCode: runtimeConfig.customerCode,
// Persist the canonical HiveGrid request/policy set, not Keycloak's
// permitted reduced scope echo from this individual token response.
scopes: [...KWP_REQUIRED_OAUTH_SCOPES],
},
tokenExpiresAt: expiresAt,
};
}
async function initializeClient(runtimeConfig: KwpOidcRuntimeConfig): Promise<Client> {
let discoveredIssuer: DiscoveredIssuer;
try {
discoveredIssuer = await discoverIssuer(runtimeConfig.issuer);
} catch (cause) {
throw new KwpOidcClientError("discovery-failed", "KWP OIDC discovery failed.", { cause });
}
if (discoveredIssuer.metadata.issuer !== runtimeConfig.issuer) {
throw new KwpOidcClientError("issuer-mismatch", "KWP OIDC discovery returned an unapproved issuer.");
}
validateDiscoveryContract(discoveredIssuer.metadata);
try {
return new discoveredIssuer.Client({
client_id: runtimeConfig.clientId,
client_secret: runtimeConfig.clientSecret,
redirect_uris: [runtimeConfig.redirectUri],
response_types: ["code"],
token_endpoint_auth_method: "client_secret_post",
});
} catch (cause) {
throw new KwpOidcClientError("client-init-failed", "The KWP OIDC client could not be initialized.", { cause });
}
}
function validateDiscoveryContract(metadata: DiscoveredIssuer["metadata"]): void {
const endpointsMatch =
metadata.authorization_endpoint === KWP_AUTHORIZATION_ENDPOINT && metadata.token_endpoint === KWP_TOKEN_ENDPOINT && metadata.jwks_uri === KWP_JWKS_URI;
const capabilitiesMatch =
metadataIncludes(metadata, "code_challenge_methods_supported", ["S256"]) &&
metadataIncludes(metadata, "grant_types_supported", ["authorization_code", "refresh_token"]) &&
metadataIncludes(metadata, "token_endpoint_auth_methods_supported", ["client_secret_post"]);
if (!endpointsMatch || !capabilitiesMatch) {
throw new KwpOidcClientError("discovery-contract-mismatch", "KWP OIDC discovery does not match the approved endpoint and capability contract.");
}
}
function metadataIncludes(metadata: DiscoveredIssuer["metadata"], field: string, requiredValues: readonly string[]): boolean {
const advertisedValues = metadata[field];
return Array.isArray(advertisedValues) && requiredValues.every((value) => advertisedValues.includes(value));
}
function runtimeFingerprint(runtimeConfig: KwpOidcRuntimeConfig): string {
const secretHash = createHash("sha256").update(runtimeConfig.clientSecret).digest("base64url");
return [
runtimeConfig.issuer,
runtimeConfig.clientId,
runtimeConfig.redirectUri,
runtimeConfig.customerCode,
runtimeConfig.hiveGridTenantId,
runtimeConfig.scopes,
secretHash,
].join("|");
}
function normalizeConfiguredScopes(rawScopes: string): string {
const scopes = rawScopes.split(/\s+/u).filter(Boolean);
const scopeSet = new Set(scopes);
const onlyApprovedScopes = [...scopeSet].every((scope) => KWP_SCOPE_SET.has(scope));
const includesEveryDomainScope = KWP_DOMAIN_SCOPES.every((scope) => scopeSet.has(scope));
const valid = onlyApprovedScopes && includesEveryDomainScope;
if (!valid) {
throw new KwpOidcClientError(
"invalid-scope",
"The configured KWP OAuth scopes must include all approved domain scopes and no unapproved scope.",
);
}
return KWP_SCOPE_ORDER.join(" ");
}
function requiredToken(value: string | undefined, label: string, diagnosticCode: KwpOidcDiagnosticCode): string {
const normalized = value?.trim();
if (!normalized) {
throw new KwpOidcClientError("invalid-token-response", `The KWP token response did not contain a ${label}.`, {
diagnosticCode,
});
}
return normalized;
}
function tokenExpiry(tokenSet: TokenSet): Date {
const nowSeconds = Math.floor(Date.now() / 1_000);
const expiresIn = tokenSet.expires_in;
if (
expiresIn !== undefined &&
(typeof expiresIn !== "number" || !Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn > KWP_ACCESS_TOKEN_TTL_SECONDS)
) {
throw invalidExpiryError();
}
const expiresAtSeconds = tokenSet.expires_at ?? (expiresIn !== undefined ? nowSeconds + expiresIn : undefined);
const remainingSeconds = typeof expiresAtSeconds === "number" ? expiresAtSeconds - nowSeconds : Number.NaN;
if (
typeof expiresAtSeconds !== "number" ||
!Number.isSafeInteger(expiresAtSeconds) ||
!Number.isSafeInteger(remainingSeconds) ||
remainingSeconds <= 0 ||
remainingSeconds > KWP_ACCESS_TOKEN_TTL_SECONDS
) {
throw invalidExpiryError();
}
const expiresAt = new Date(expiresAtSeconds * 1_000);
if (Number.isNaN(expiresAt.getTime())) {
throw invalidExpiryError();
}
return expiresAt;
}
function invalidExpiryError(): KwpOidcClientError {
return new KwpOidcClientError("invalid-token-response", "The KWP token response did not contain a valid expiry.", {
diagnosticCode: "invalid_expiry",
});
}
const PROVIDER_ERROR_DIAGNOSTICS: Readonly<Record<string, KwpOidcDiagnosticCode>> = Object.freeze({
access_denied: "provider_access_denied",
invalid_client: "provider_invalid_client",
invalid_grant: "provider_invalid_grant",
invalid_scope: "provider_invalid_scope",
server_error: "provider_server_error",
temporarily_unavailable: "provider_temporarily_unavailable",
unauthorized_client: "provider_unauthorized_client",
});
function callbackFailureDiagnosticCode(cause: unknown): KwpOidcDiagnosticCode {
if (cause && typeof cause === "object") {
const providerError = "error" in cause ? cause.error : undefined;
if (typeof providerError === "string" && Object.hasOwn(PROVIDER_ERROR_DIAGNOSTICS, providerError)) {
return PROVIDER_ERROR_DIAGNOSTICS[providerError];
}
}
if (cause instanceof Error && cause.name === "RPError") {
return "oidc_rp_error";
}
return "token_exchange_failed";
}
function requireInput(name: string, value: string): void {
if (!present(value)) {
throw new KwpOidcClientError("invalid-input", `KWP OAuth ${name} is required.`);
}
}
function present(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
/** Test-only seam for deterministic discovery and client construction. */
export function __setKwpOidcDiscoveryForTests(discovery: DiscoverIssuer): void {
discoverIssuer = discovery;
cachedClient = null;
cachedClientFingerprint = null;
}
/** Test-only: restore real discovery and clear the process-wide client cache. */
export function __resetKwpOidcClientForTests(): void {
discoverIssuer = defaultDiscoverIssuer;
cachedClient = null;
cachedClientFingerprint = null;
}