Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,115 @@
// AK-P16a · calendar DB access (thin Prisma wrappers). Every read is tenant- AND
// user-scoped (leak-protection, DoD 3). Token ciphertext columns are NEVER
// selected into these read shapes — only the connect/refresh services touch them.
import { db } from "~/utils/db.server";
/** Connection fields safe to surface (no token ciphertext). */
export type CalendarConnectionListRow = {
id: string;
userId: string;
provider: "google";
externalAccountEmail: string;
status: "active" | "paused" | "error" | "revoked";
syncDirection: "bidirectional" | "hivegrid_to_external_only" | "external_to_hivegrid_only";
lastSyncAt: Date | null;
lastErrorText: string | null;
selectedCalendars: unknown;
};
const CONNECTION_SAFE_SELECT = {
id: true,
userId: true,
provider: true,
externalAccountEmail: true,
status: true,
syncDirection: true,
lastSyncAt: true,
lastErrorText: true,
selectedCalendars: true,
} as const;
/** The current user's own calendar connections (newest first). */
export async function listConnectionsForUser(tenantId: string, userId: string): Promise<CalendarConnectionListRow[]> {
return db.calendarConnection.findMany({
where: { tenantId, userId, archivedAt: null },
select: CONNECTION_SAFE_SELECT,
orderBy: { createdAt: "desc" },
}) as unknown as Promise<CalendarConnectionListRow[]>;
}
/** One connection by id (tenant-scoped). Returns userId so the route owner-checks. */
export async function getConnectionForTenant(tenantId: string, connectionId: string): Promise<CalendarConnectionListRow | null> {
return db.calendarConnection.findFirst({
where: { id: connectionId, tenantId, archivedAt: null },
select: CONNECTION_SAFE_SELECT,
}) as unknown as Promise<CalendarConnectionListRow | null>;
}
/**
* Resolve the connection a Google push channel belongs to. The webhook entrypoint
* has NO tenant context (Google calls a fixed URL), so this is a deliberate
* cross-tenant lookup by the stored subscription id; the caller then scopes every
* follow-up to the returned tenantId.
*/
export async function findConnectionByWebhookSubscription(subscriptionId: string): Promise<{ id: string; tenantId: string; userId: string } | null> {
return db.calendarConnection.findFirst({
where: { webhookSubscriptionId: subscriptionId, archivedAt: null },
select: { id: true, tenantId: true, userId: true },
});
}
/** Persist an inbound webhook notification as pending (idempotency + retry). */
export async function recordWebhookEvent(input: {
tenantId: string;
connectionId: string;
notificationPayload: Record<string, unknown>;
externalResourceState: string | null;
}): Promise<void> {
await db.calendarWebhookEvent.create({
data: {
tenantId: input.tenantId,
connectionId: input.connectionId,
provider: "google",
notificationPayload: input.notificationPayload as never,
processingStatus: "pending",
externalResourceState: input.externalResourceState,
},
});
}
export type CalendarConflictRow = {
id: string;
resolution: "external_won" | "hivegrid_won" | "external_deleted" | "hivegrid_deleted";
descriptionText: string;
createdAt: Date;
};
/** The last `take` conflicts of a connection, newest first (DoD 4). */
export async function listConflictsForConnection(tenantId: string, connectionId: string, take = 50): Promise<CalendarConflictRow[]> {
return db.calendarConflict.findMany({
where: { tenantId, connectionId },
select: { id: true, resolution: true, descriptionText: true, createdAt: true },
orderBy: { createdAt: "desc" },
take,
}) as unknown as Promise<CalendarConflictRow[]>;
}
export type CalendarEventRow = {
id: string;
source: "hivegrid_internal" | "external_synced";
title: string | null;
startsAt: Date;
endsAt: Date;
isAllDay: boolean;
internalEntityLink: unknown;
};
/** The current user's own events in a window (for the calendar view, DoD 5). */
export async function listEventsForUser(tenantId: string, userId: string, rangeStart: Date, rangeEnd: Date): Promise<CalendarEventRow[]> {
return db.calendarEvent.findMany({
where: { tenantId, userId, archivedAt: null, startsAt: { gte: rangeStart, lte: rangeEnd } },
select: { id: true, source: true, title: true, startsAt: true, endsAt: true, isAllDay: true, internalEntityLink: true },
orderBy: { startsAt: "asc" },
}) as unknown as Promise<CalendarEventRow[]>;
}
@@ -0,0 +1,45 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
// AK-P16a · static authorization-boundary guard for the calendar mutation routes
// (DoD A.5 / DoD 3). Asserts every state-changing action runs the module/permission
// guard, the owner-check (where applicable) and CSRF validation BEFORE it reads the
// form body — so a missing module/permission/owner/CSRF can never reach a mutation.
const appRoot = resolveRepoPath("apps/web/app");
const mutationRoutes = [
"routes/app.$tenant/settings.integrations.calendar._index.tsx",
"routes/app.$tenant/settings.integrations.calendar.$id.tsx",
];
describe("calendar route authorization boundary", () => {
test("guards permission + CSRF before parsing the form body", () => {
for (const relativePath of mutationRoutes) {
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt, relativePath).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn)");
expect(permissionAt, relativePath).toBeGreaterThanOrEqual(0);
expect(permissionAt, relativePath).toBeLessThan(formDataAt);
const csrfAt = source.indexOf("await validateCSRFToken(request)");
expect(csrfAt, relativePath).toBeGreaterThanOrEqual(0);
expect(csrfAt, relativePath).toBeLessThan(formDataAt);
}
});
test("detail route owner-checks the connection before mutating", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/settings.integrations.calendar.$id.tsx"), "utf8");
const ownerAt = source.indexOf("requireConnectionOwner(ctx, connection.userId)");
const formDataAt = source.indexOf("await request.formData()");
expect(ownerAt).toBeGreaterThanOrEqual(0);
// The action's owner-check (the second occurrence) precedes the form read.
const actionOwnerAt = source.indexOf("requireConnectionOwner(ctx, connection.userId)", ownerAt + 1);
expect(actionOwnerAt).toBeGreaterThanOrEqual(0);
expect(actionOwnerAt).toBeLessThan(formDataAt);
});
});
@@ -0,0 +1,85 @@
// AK-P16a · shared loader/action guard for the calendar module (mirrors
// integrationsAccess / taskAccess). Calendar is an Apps-Engine integration, so the
// MODULE gate reuses the `integrations` feature (tenantHasModule) — there is no
// separate plan-gated "calendar" feature (M25 Block I: connecting your own
// calendar is a default tenant-user capability). The PER-USER capability is gated
// by the `calendar.connect_own` permission; `calendar.admin` is tenant-wide
// oversight. Module-off renders a locked empty VM on GET and 404s on write
// (Bauprinzip A.5.3); a permission miss is also a 404, never a 403.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { INTEGRATIONS_MODULE_KEY } from "~/utils/integrations/integrationsRoutePaths";
/** Calendar atomic permissions (M25 Block I). */
export const CALENDAR_PERMISSIONS = {
/** Connect/manage your OWN calendar connection (default tenant-user capability). */
connectOwn: "calendar.connect_own",
/** Tenant-wide oversight + force-disconnect on user offboarding. */
admin: "calendar.admin",
} as const;
export type CalendarRouteContext = {
tenantId: string;
userId: string;
permissions: readonly string[];
hasModule: boolean;
};
/**
* Resolve the calendar route context: auth + tenant + the integrations module gate
* + the user's permissions. With `requireModule` a module-off tenant 404s (write
* paths); GET paths can render a locked empty VM from `hasModule === false`.
*/
export async function loadCalendarContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<CalendarRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: INTEGRATIONS_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: INTEGRATIONS_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** True if the user holds `permission` or the broader `calendar.admin` bundle. */
export function calendarHasPermission(ctx: CalendarRouteContext, permission: string): boolean {
return ctx.permissions.includes(permission) || ctx.permissions.includes(CALENDAR_PERMISSIONS.admin);
}
/** Require a calendar.* permission (admin-aware); 404 if missing (A.5.3). */
export function requireCalendarPermission(ctx: CalendarRouteContext, permission: string): CalendarRouteContext {
if (!calendarHasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound, { permission });
}
return ctx;
}
/**
* Owner-check for connection-scoped routes (leak-protection, DoD 3): only the
* owning user may see/manage a connection's external event details — UNLESS the
* caller holds `calendar.admin` (tenant oversight). A miss is a 404, not a 403.
*/
export function requireConnectionOwner(ctx: CalendarRouteContext, connectionUserId: string): CalendarRouteContext {
if (ctx.userId === connectionUserId || ctx.permissions.includes(CALENDAR_PERMISSIONS.admin)) {
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { owner: "mismatch" });
}
@@ -0,0 +1,33 @@
// AK-P16a · pure client-safe route-path builders for the calendar module. Loaders
// build these and pass them into the VMs so the VMs stay routing-agnostic (mirrors
// integrationsRoutePaths). Calendar reuses the `integrations` tenant-connector
// module key (calendar is an Apps-Engine integration; see calendarAccess.server).
export { INTEGRATIONS_MODULE_KEY as CALENDAR_MODULE_KEY } from "~/utils/integrations/integrationsRoutePaths";
/** The calendar grid view (all sources). */
export function calendarViewPath(tenantSlug: string): string {
return `/${tenantSlug}/calendar`;
}
/** The calendar connections settings list. */
export function calendarConnectionsPath(tenantSlug: string): string {
return `/${tenantSlug}/settings/integrations/calendar`;
}
/** A single connection's detail (selected calendars, status, conflict log). */
export function calendarConnectionDetailPath(tenantSlug: string, connectionId: string): string {
return `/${tenantSlug}/settings/integrations/calendar/${connectionId}`;
}
/**
* The OAuth callback URI. NOT tenant-scoped: EXT-10 registered exactly
* `/integrations/google/oauth/callback` at the app root (Google redirects here);
* the signed `state` carries the tenant + user.
*/
export const GOOGLE_OAUTH_CALLBACK_PATH = "/integrations/google/oauth/callback";
/** 404 helper (Bauprinzip A.5.3 — permission/owner miss renders 404, not 403). */
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
@@ -0,0 +1,163 @@
// AK-P16a · calendar connection lifecycle (connect / callback / disconnect).
//
// OAuth tokens are sealed with the per-tenant DEK envelope (AD-8) — never stored
// plain, never logged. Writes are audited automatically by the M001 Prisma
// middleware (DoD 13); connect/disconnect are USER-account events, not CRM
// activity-stream entries (the activity model is CRM-subject only — the
// appointment-sync activity belongs to AK-P16b's booking). Webhook subscription is
// best-effort: a failure degrades the connection with a Klartext hint, it does not
// block the connect.
import { decryptTenantField, encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { db } from "~/utils/db.server";
import { googleCalendarAdapter, CalendarNotConfiguredError } from "./adapters/GoogleCalendarAdapter.server";
import type { CalendarCreds } from "./adapters/CalendarAdapter";
import { signCalendarOAuthState, verifyCalendarOAuthState } from "./oauthState.server";
import { GOOGLE_OAUTH_CALLBACK_PATH } from "../routes/calendarRoutePaths";
export class CalendarConnectError extends Error {
readonly code: "not_configured" | "invalid_state" | "exchange_failed";
constructor(code: CalendarConnectError["code"]) {
super(code);
this.name = "CalendarConnectError";
this.code = code;
}
}
/** Build the Google consent URL for the current tenant user. */
export function buildConnectUrl(input: { tenantId: string; userId: string; tenantSlug: string }): string {
if (!googleCalendarAdapter.isConfigured()) {
throw new CalendarConnectError("not_configured");
}
const state = signCalendarOAuthState(input);
return googleCalendarAdapter.buildAuthorizationUrl(state);
}
/**
* Complete the OAuth callback: verify state, exchange the code, seal the tokens,
* upsert the per-user connection, and best-effort subscribe the push channel.
* Returns the tenant slug + ids so the callback route can trigger the initial sync
* (kept out of this service to avoid a CalendarSyncService import cycle).
*/
export async function completeOAuthCallback(input: { code: string; state: string }): Promise<{ tenantSlug: string; tenantId: string; connectionId: string }> {
const verified = verifyCalendarOAuthState(input.state);
if (!verified.ok) {
throw new CalendarConnectError("invalid_state");
}
const { tenantId, userId, tenantSlug } = verified.payload;
let exchange: Awaited<ReturnType<typeof googleCalendarAdapter.exchangeCode>>;
try {
exchange = await googleCalendarAdapter.exchangeCode(input.code);
} catch (error) {
if (error instanceof CalendarNotConfiguredError) {
throw new CalendarConnectError("not_configured");
}
throw new CalendarConnectError("exchange_failed");
}
const { tokens, account } = exchange;
// Seal refresh + access tokens separately (AD-8). A refresh token is only
// returned on first consent; keep an existing one if Google omits it.
const refreshCiphertext = tokens.refreshToken ? await encryptTenantField(tenantId, tokens.refreshToken) : null;
const accessCiphertext = await encryptTenantField(tenantId, tokens.accessToken);
const connection = await db.calendarConnection.upsert({
where: { tenantId_userId_provider_externalAccountId: { tenantId, userId, provider: "google", externalAccountId: account.accountId } },
create: {
tenantId,
userId,
provider: "google",
externalAccountEmail: account.email,
externalAccountId: account.accountId,
oauthRefreshTokenCiphertext: refreshCiphertext,
oauthAccessTokenCiphertext: accessCiphertext,
oauthAccessTokenExpiresAt: tokens.expiresAt,
oauthScopes: [...tokens.scopes],
status: "active",
},
update: {
externalAccountEmail: account.email,
// Preserve the stored refresh token when Google omits it on re-consent.
...(refreshCiphertext ? { oauthRefreshTokenCiphertext: refreshCiphertext } : {}),
oauthAccessTokenCiphertext: accessCiphertext,
oauthAccessTokenExpiresAt: tokens.expiresAt,
oauthScopes: [...tokens.scopes],
status: "active",
lastErrorText: null,
archivedAt: null,
},
select: { id: true },
});
await trySubscribeWebhook({ tenantId, connectionId: connection.id, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken ?? "" });
return { tenantSlug, tenantId, connectionId: connection.id };
}
/**
* Best-effort push-channel subscription for the primary calendar. Needs a public
* webhook URL (GOOGLE_CALENDAR_WEBHOOK_URL); absent or failing it degrades the
* connection with a Klartext hint rather than failing the connect.
*/
async function trySubscribeWebhook(input: { tenantId: string; connectionId: string; accessToken: string; refreshToken: string }): Promise<void> {
const webhookUrl = process.env.GOOGLE_CALENDAR_WEBHOOK_URL;
if (!webhookUrl) {
return;
}
const creds: CalendarCreds = { accessToken: input.accessToken, refreshToken: input.refreshToken };
// The channel id doubles as the per-connection lookup; the token is the
// verification secret echoed back as X-Goog-Channel-Token.
const channelId = `cal_${input.connectionId}`;
try {
const sub = await googleCalendarAdapter.subscribeWebhook(creds, "primary", channelId, webhookUrl, input.connectionId);
await db.calendarConnection.update({
where: { id: input.connectionId },
data: { webhookSubscriptionId: sub.subscriptionId, webhookSubscriptionExpiresAt: sub.expiresAt },
});
} catch {
await db.calendarConnection.update({
where: { id: input.connectionId },
data: { status: "active", lastErrorText: "calendar.health.webhookSubscriptionFailed" },
});
}
}
/** Decrypt a connection's sealed tokens into adapter creds (server-only). */
export async function loadConnectionCreds(tenantId: string, connectionId: string): Promise<CalendarCreds | null> {
const row = await db.calendarConnection.findFirst({
where: { id: connectionId, tenantId },
select: { oauthRefreshTokenCiphertext: true, oauthAccessTokenCiphertext: true, oauthAccessTokenExpiresAt: true },
});
if (!row?.oauthRefreshTokenCiphertext || !row.oauthAccessTokenCiphertext) {
return null;
}
const [refreshToken, accessToken] = await Promise.all([
decryptTenantField(tenantId, row.oauthRefreshTokenCiphertext),
decryptTenantField(tenantId, row.oauthAccessTokenCiphertext),
]);
return { refreshToken, accessToken, expiresAt: row.oauthAccessTokenExpiresAt };
}
/**
* Disconnect a connection (owner or admin). Best-effort revoke of the push channel
* + provider tokens, then soft-revoke locally (status revoked, soft-delete). The
* external mirror events are optionally removed (M25 disconnect dialog) — deferred
* to the sync service; here we drop the local connection + its push channel.
*/
export async function disconnectConnection(input: { tenantId: string; connectionId: string }): Promise<void> {
const row = await db.calendarConnection.findFirst({
where: { id: input.connectionId, tenantId: input.tenantId, archivedAt: null },
select: { id: true, webhookSubscriptionId: true },
});
if (!row) {
return;
}
const creds = await loadConnectionCreds(input.tenantId, input.connectionId);
if (creds && row.webhookSubscriptionId) {
await googleCalendarAdapter.unsubscribeWebhook(creds, row.webhookSubscriptionId, row.webhookSubscriptionId).catch(() => undefined);
}
await db.calendarConnection.update({
where: { id: row.id },
data: { status: "revoked", archivedAt: new Date(), oauthRefreshTokenCiphertext: null, oauthAccessTokenCiphertext: null, webhookSubscriptionId: null },
});
}
@@ -0,0 +1,116 @@
// AK-P16a · calendar sync engine (M25 Block D/E). The external -> HiveGrid
// read-only path: pull the provider delta via the stored cursor and upsert each
// event into the CalendarEvent cache (through the pure eventMapping). Tokens are
// refreshed transparently when expired. The cache feeds availability (busy slots
// only — leak-protection happens at the availability boundary, not here).
//
// A 410 (sync_token_invalid) triggers a full re-pull of the rolling window. The
// bidirectional WRITE path (HiveGrid -> Google) + the conflict-on-mapped-event
// path build on top of this and the ConflictResolver; they require the write
// service (mappings) and are wired as that lands.
import { encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { db } from "~/utils/db.server";
import { googleCalendarAdapter } from "./adapters/GoogleCalendarAdapter.server";
import type { CalendarCreds } from "./adapters/CalendarAdapter";
import { loadConnectionCreds } from "./CalendarConnectionService.server";
import { toExternalEventFields } from "./eventMapping";
const WINDOW_PAST_DAYS = 7;
const WINDOW_FUTURE_DAYS = 60;
const PRIMARY_CALENDAR = "primary";
/** Ensure the access token is fresh; refresh + re-seal when within 60s of expiry. */
async function ensureFreshCreds(tenantId: string, connectionId: string, creds: CalendarCreds): Promise<CalendarCreds> {
const soon = Date.now() + 60_000;
if (creds.expiresAt && creds.expiresAt.getTime() > soon) {
return creds;
}
const next = await googleCalendarAdapter.refreshTokens(creds.refreshToken);
const accessCiphertext = await encryptTenantField(tenantId, next.accessToken);
await db.calendarConnection.update({
where: { id: connectionId },
data: { oauthAccessTokenCiphertext: accessCiphertext, oauthAccessTokenExpiresAt: next.expiresAt, status: "active", lastErrorText: null },
});
return { accessToken: next.accessToken, refreshToken: creds.refreshToken, expiresAt: next.expiresAt };
}
export interface SyncResult {
readonly upserted: number;
readonly fullResync: boolean;
}
/**
* Run one incremental external -> cache sync for a connection's primary calendar.
* Idempotent: re-running with the same cursor is a no-op; a 410 forces a full
* window re-pull. Returns the number of events written.
*/
export async function syncConnection(tenantId: string, connectionId: string, now: Date = new Date()): Promise<SyncResult> {
const baseCreds = await loadConnectionCreds(tenantId, connectionId);
if (!baseCreds) {
return { upserted: 0, fullResync: false };
}
const connection = await db.calendarConnection.findFirst({ where: { id: connectionId, tenantId }, select: { userId: true } });
if (!connection) {
return { upserted: 0, fullResync: false };
}
let creds: CalendarCreds;
try {
creds = await ensureFreshCreds(tenantId, connectionId, baseCreds);
} catch {
await db.calendarConnection.update({ where: { id: connectionId }, data: { status: "error", lastErrorText: "calendar.health.tokenExpired" } });
return { upserted: 0, fullResync: false };
}
const cursor = await db.calendarSyncCursor.findFirst({ where: { connectionId, externalCalendarId: PRIMARY_CALENDAR }, select: { cursorToken: true } });
let upserted = 0;
let fullResync = false;
let pageToken: string | undefined;
let nextSyncToken: string | undefined;
let syncToken = cursor?.cursorToken ?? undefined;
do {
const page = await googleCalendarAdapter.fetchEvents(creds, PRIMARY_CALENDAR, {
syncToken,
pageToken,
timeMin: syncToken ? undefined : new Date(now.getTime() - WINDOW_PAST_DAYS * 86_400_000),
timeMax: syncToken ? undefined : new Date(now.getTime() + WINDOW_FUTURE_DAYS * 86_400_000),
});
if (page.fullResyncRequired) {
// Cursor expired (410): drop it and restart this run as an initial pull.
fullResync = true;
syncToken = undefined;
pageToken = undefined;
await db.calendarSyncCursor.updateMany({ where: { connectionId, externalCalendarId: PRIMARY_CALENDAR }, data: { cursorToken: null } });
continue;
}
for (const event of page.events) {
const fields = toExternalEventFields(event, { tenantId, userId: connection.userId, connectionId, provider: "google", externalCalendarId: PRIMARY_CALENDAR }, now);
await db.calendarEvent.upsert({
where: { tenantId_userId_provider_externalEventId: { tenantId, userId: connection.userId, provider: "google", externalEventId: event.externalId } },
create: fields,
update: { ...fields, createdAt: undefined } as never,
});
upserted += 1;
}
pageToken = page.nextPageToken;
nextSyncToken = page.nextSyncToken ?? nextSyncToken;
} while (pageToken);
// Persist the new cursor + stamp the successful sync.
if (nextSyncToken) {
await db.calendarSyncCursor.upsert({
where: { connectionId_externalCalendarId: { connectionId, externalCalendarId: PRIMARY_CALENDAR } },
create: { tenantId, connectionId, externalCalendarId: PRIMARY_CALENDAR, cursorToken: nextSyncToken, lastFullSyncAt: fullResync ? now : null },
update: { cursorToken: nextSyncToken, ...(fullResync ? { lastFullSyncAt: now } : {}) },
});
}
await db.calendarConnection.update({ where: { id: connectionId }, data: { lastSyncAt: now, status: "active" } });
return { upserted, fullResync };
}
@@ -0,0 +1,115 @@
// AK-P16a · provider-agnostic CalendarAdapter contract (M25 Block G).
//
// v1 ships only the Google implementation (GoogleCalendarAdapter.server.ts);
// Outlook/Microsoft is a v2 adapter against this SAME interface. The adapter is a
// thin PROVIDER BOUNDARY: given decrypted creds it performs one network op and
// returns provider-neutral data. The per-user orchestration (cursor persistence,
// mapping upserts, Last-Write-Wins) lives in the sync services, not here.
//
// Neutral types deliberately avoid any Google naming so a second provider drops in
// without leaking provider shapes into the domain layer.
/** A connection's decrypted OAuth credentials (the engine handles envelope crypto). */
export interface CalendarCreds {
readonly accessToken: string;
readonly refreshToken: string;
readonly expiresAt?: Date | null;
}
export interface CalendarTokens {
readonly accessToken: string;
/** Present on the initial code exchange; absent on a refresh. */
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}
export interface CalendarAccount {
readonly email: string;
readonly accountId: string;
}
export interface NeutralCalendar {
readonly id: string;
readonly name: string;
readonly isPrimary: boolean;
}
export interface NeutralEvent {
readonly externalId: string;
/** false when the provider reports the event as cancelled/deleted. */
readonly isActive: boolean;
readonly title: string | null;
readonly description: string | null;
readonly location: string | null;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay: boolean;
readonly timeZone: string | null;
readonly recurrenceRule: string | null;
readonly attendees: ReadonlyArray<{ email: string; status: string | null }>;
readonly etag: string | null;
readonly lastModifiedExternal: Date | null;
/** Whether this event blocks availability (false = provider "Free"). */
readonly isBusy: boolean;
}
export interface NeutralEventInput {
readonly title: string;
readonly description?: string;
readonly location?: string;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay?: boolean;
readonly timeZone?: string;
readonly attendees?: ReadonlyArray<{ email: string }>;
}
export interface DeltaResult {
readonly events: readonly NeutralEvent[];
/** Persist as the next cursor when present (page complete). */
readonly nextSyncToken?: string;
/** Continue paging within the same sync when present. */
readonly nextPageToken?: string;
/** True when the cursor expired (HTTP 410) → caller must full-resync. */
readonly fullResyncRequired?: boolean;
}
export interface WebhookSubscription {
readonly subscriptionId: string;
readonly resourceId: string;
readonly expiresAt: Date | null;
}
export interface WriteResult {
readonly externalId: string;
readonly etag: string | null;
}
/** Thrown by updateEvent when the provider reports a concurrent external edit. */
export class CalendarConflictError extends Error {
constructor(message = "external_concurrent_edit") {
super(message);
this.name = "CalendarConflictError";
}
}
export interface CalendarAdapter {
readonly provider: "google";
/** True only when the provider OAuth config is present (EXT-10 env). */
isConfigured(): boolean;
buildAuthorizationUrl(state: string): string;
exchangeCode(code: string): Promise<{ tokens: CalendarTokens; account: CalendarAccount }>;
refreshTokens(refreshToken: string): Promise<CalendarTokens>;
listCalendars(creds: CalendarCreds): Promise<NeutralCalendar[]>;
subscribeWebhook(creds: CalendarCreds, calendarId: string, channelId: string, address: string, token: string): Promise<WebhookSubscription>;
unsubscribeWebhook(creds: CalendarCreds, subscriptionId: string, resourceId: string): Promise<void>;
fetchEvents(
creds: CalendarCreds,
calendarId: string,
opts: { syncToken?: string; pageToken?: string; timeMin?: Date; timeMax?: Date },
): Promise<DeltaResult>;
createEvent(creds: CalendarCreds, calendarId: string, input: NeutralEventInput): Promise<WriteResult>;
updateEvent(creds: CalendarCreds, calendarId: string, externalId: string, input: NeutralEventInput, ifMatchEtag?: string | null): Promise<WriteResult>;
deleteEvent(creds: CalendarCreds, calendarId: string, externalId: string): Promise<void>;
}
@@ -0,0 +1,180 @@
// AK-P16a · Google implementation of the provider-agnostic CalendarAdapter.
//
// Maps the neutral domain shapes to/from the shared @hivegrid/integrations Google
// REST client. No Prisma here — the adapter only does network I/O against Google
// and provider↔neutral mapping. Token storage/crypto + orchestration live in the
// sync services.
import {
buildAuthorizationUrl,
deleteEvent as gDeleteEvent,
exchangeCodeForTokens,
fetchUserInfo,
GoogleCalendarError,
insertEvent,
listCalendars as gListCalendars,
listEvents,
patchEvent,
refreshAccessToken,
resolveGoogleOAuthConfig,
stopChannel,
watchCalendar,
type GoogleEvent,
type GoogleEventInput,
type GoogleOAuthConfig,
} from "@hivegrid/integrations";
import {
CalendarConflictError,
type CalendarAccount,
type CalendarAdapter,
type CalendarCreds,
type CalendarTokens,
type DeltaResult,
type NeutralCalendar,
type NeutralEvent,
type NeutralEventInput,
type WebhookSubscription,
type WriteResult,
} from "./CalendarAdapter";
/** Thrown when the OAuth config (EXT-10 env) is absent — surfaced as Klartext. */
export class CalendarNotConfiguredError extends Error {
constructor() {
super("calendar_not_configured");
this.name = "CalendarNotConfiguredError";
}
}
function requireConfig(): GoogleOAuthConfig {
const config = resolveGoogleOAuthConfig();
if (!config) {
throw new CalendarNotConfiguredError();
}
return config;
}
function parseBoundary(b: { dateTime?: string; date?: string } | undefined): { at: Date; isAllDay: boolean } {
if (b?.dateTime) {
return { at: new Date(b.dateTime), isAllDay: false };
}
if (b?.date) {
return { at: new Date(`${b.date}T00:00:00.000Z`), isAllDay: true };
}
return { at: new Date(0), isAllDay: false };
}
function toNeutralEvent(g: GoogleEvent): NeutralEvent {
const start = parseBoundary(g.start);
const end = parseBoundary(g.end);
return {
externalId: g.id,
isActive: g.status !== "cancelled",
title: g.summary ?? null,
description: g.description ?? null,
location: g.location ?? null,
startsAt: start.at,
endsAt: end.at,
isAllDay: start.isAllDay || end.isAllDay,
timeZone: g.start?.timeZone ?? null,
recurrenceRule: g.recurrence && g.recurrence.length > 0 ? g.recurrence[0] : null,
attendees: (g.attendees ?? []).map((a) => ({ email: a.email ?? "", status: a.responseStatus ?? null })),
etag: g.etag ?? null,
lastModifiedExternal: g.updated ? new Date(g.updated) : null,
// Google "transparent" == Free → not busy. Default (opaque/undefined) = busy.
isBusy: g.transparency !== "transparent",
};
}
function toGoogleInput(input: NeutralEventInput): GoogleEventInput {
const tz = input.timeZone ?? "UTC";
const boundary = (d: Date): GoogleEventInput["start"] =>
input.isAllDay ? { date: d.toISOString().slice(0, 10) } : { dateTime: d.toISOString(), timeZone: tz };
return {
summary: input.title,
description: input.description,
location: input.location,
start: boundary(input.startsAt),
end: boundary(input.endsAt),
attendees: input.attendees ? input.attendees.map((a) => ({ email: a.email })) : undefined,
};
}
export const googleCalendarAdapter: CalendarAdapter = {
provider: "google",
isConfigured(): boolean {
return resolveGoogleOAuthConfig() !== null;
},
buildAuthorizationUrl(state: string): string {
return buildAuthorizationUrl(requireConfig(), state);
},
async exchangeCode(code: string): Promise<{ tokens: CalendarTokens; account: CalendarAccount }> {
const config = requireConfig();
const tokenSet = await exchangeCodeForTokens(config, code);
const info = await fetchUserInfo(tokenSet.accessToken);
return {
tokens: { accessToken: tokenSet.accessToken, refreshToken: tokenSet.refreshToken, expiresAt: tokenSet.expiresAt, scopes: tokenSet.scopes },
account: { email: info.email, accountId: info.sub },
};
},
async refreshTokens(refreshToken: string): Promise<CalendarTokens> {
const set = await refreshAccessToken(requireConfig(), refreshToken);
return { accessToken: set.accessToken, refreshToken: set.refreshToken, expiresAt: set.expiresAt, scopes: set.scopes };
},
async listCalendars(creds: CalendarCreds): Promise<NeutralCalendar[]> {
const cals = await gListCalendars(creds.accessToken);
return cals.map((c) => ({ id: c.id, name: c.summary, isPrimary: c.primary }));
},
async subscribeWebhook(creds: CalendarCreds, calendarId: string, channelId: string, address: string, token: string): Promise<WebhookSubscription> {
const channel = await watchCalendar(creds.accessToken, calendarId, channelId, address, token);
return { subscriptionId: channel.channelId, resourceId: channel.resourceId, expiresAt: channel.expiresAt };
},
async unsubscribeWebhook(creds: CalendarCreds, subscriptionId: string, resourceId: string): Promise<void> {
await stopChannel(creds.accessToken, subscriptionId, resourceId);
},
async fetchEvents(creds: CalendarCreds, calendarId: string, opts): Promise<DeltaResult> {
try {
const page = await listEvents(creds.accessToken, calendarId, {
syncToken: opts.syncToken,
pageToken: opts.pageToken,
timeMin: opts.timeMin?.toISOString(),
timeMax: opts.timeMax?.toISOString(),
});
return { events: page.events.map(toNeutralEvent), nextSyncToken: page.nextSyncToken, nextPageToken: page.nextPageToken };
} catch (error) {
if (error instanceof GoogleCalendarError && error.fullResyncRequired) {
return { events: [], fullResyncRequired: true };
}
throw error;
}
},
async createEvent(creds: CalendarCreds, calendarId: string, input: NeutralEventInput): Promise<WriteResult> {
const result = await insertEvent(creds.accessToken, calendarId, toGoogleInput(input));
return { externalId: result.id, etag: result.etag ?? null };
},
async updateEvent(creds: CalendarCreds, calendarId: string, externalId: string, input: NeutralEventInput, ifMatchEtag?: string | null): Promise<WriteResult> {
try {
const result = await patchEvent(creds.accessToken, calendarId, externalId, toGoogleInput(input), ifMatchEtag ?? undefined);
return { externalId: result.id, etag: result.etag ?? null };
} catch (error) {
// 412 precondition-failed = a concurrent external edit (M25 Block F).
if (error instanceof GoogleCalendarError && error.httpStatus === 412) {
throw new CalendarConflictError();
}
throw error;
}
},
async deleteEvent(creds: CalendarCreds, calendarId: string, externalId: string): Promise<void> {
await gDeleteEvent(creds.accessToken, calendarId, externalId);
},
};
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { extractBusyIntervals, mergeBusyIntervals, overlapsBusy, type BusyCandidate, type BusyInterval } from "./availability";
const d = (iso: string): Date => new Date(iso);
describe("extractBusyIntervals (leak-protection, DoD 3)", () => {
const base: Omit<BusyCandidate, "startsAt" | "endsAt"> = { isBusyForAvailability: true, archivedAt: null };
it("returns only anonymous {from,to} — never any content field", () => {
const events: BusyCandidate[] = [{ ...base, startsAt: d("2026-07-01T09:00:00Z"), endsAt: d("2026-07-01T10:00:00Z") }];
const result = extractBusyIntervals(events);
expect(result).toEqual([{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") }]);
// Structural leak check: the only keys are from/to.
expect(Object.keys(result[0]).sort()).toEqual(["from", "to"]);
});
it("drops non-busy (Free), archived, and zero/negative-length events", () => {
const events: BusyCandidate[] = [
{ ...base, isBusyForAvailability: false, startsAt: d("2026-07-01T09:00:00Z"), endsAt: d("2026-07-01T10:00:00Z") },
{ ...base, archivedAt: d("2026-07-01T08:00:00Z"), startsAt: d("2026-07-01T11:00:00Z"), endsAt: d("2026-07-01T12:00:00Z") },
{ ...base, startsAt: d("2026-07-01T13:00:00Z"), endsAt: d("2026-07-01T13:00:00Z") },
];
expect(extractBusyIntervals(events)).toEqual([]);
});
it("sorts ascending by start", () => {
const events: BusyCandidate[] = [
{ ...base, startsAt: d("2026-07-01T15:00:00Z"), endsAt: d("2026-07-01T16:00:00Z") },
{ ...base, startsAt: d("2026-07-01T09:00:00Z"), endsAt: d("2026-07-01T10:00:00Z") },
];
expect(extractBusyIntervals(events).map((i) => i.from.toISOString())).toEqual(["2026-07-01T09:00:00.000Z", "2026-07-01T15:00:00.000Z"]);
});
});
describe("mergeBusyIntervals", () => {
it("merges overlapping and touching intervals", () => {
const intervals: BusyInterval[] = [
{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") },
{ from: d("2026-07-01T10:00:00Z"), to: d("2026-07-01T11:00:00Z") },
{ from: d("2026-07-01T10:30:00Z"), to: d("2026-07-01T12:00:00Z") },
];
expect(mergeBusyIntervals(intervals)).toEqual([{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T12:00:00Z") }]);
});
it("keeps disjoint intervals separate", () => {
const intervals: BusyInterval[] = [
{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") },
{ from: d("2026-07-01T11:00:00Z"), to: d("2026-07-01T12:00:00Z") },
];
expect(mergeBusyIntervals(intervals)).toHaveLength(2);
});
it("returns [] for empty input", () => {
expect(mergeBusyIntervals([])).toEqual([]);
});
});
describe("overlapsBusy", () => {
const intervals: BusyInterval[] = [{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") }];
it("detects an overlapping slot", () => {
expect(overlapsBusy(d("2026-07-01T09:30:00Z"), d("2026-07-01T10:30:00Z"), intervals)).toBe(true);
});
it("treats back-to-back as free (half-open)", () => {
expect(overlapsBusy(d("2026-07-01T10:00:00Z"), d("2026-07-01T11:00:00Z"), intervals)).toBe(false);
});
});
@@ -0,0 +1,67 @@
// AK-P16a · availability extraction (PURE) — the leak-protection boundary (DoD 3).
//
// External calendar events carry private content (title/description/attendees).
// Outside the owning user's own views, the ONLY thing other users (and the Booking
// slot calculator in AK-P16b) may learn is "busy from X to Y" — never a title or
// any other field. This module is the single chokepoint that turns rich events
// into anonymous busy intervals, so the leak-protection is enforced in one pure,
// unit-tested place rather than scattered across queries.
//
// No Prisma / no React import — pure functions over plain inputs.
/** The minimal event fields availability needs (a structural subset). */
export interface BusyCandidate {
readonly startsAt: Date;
readonly endsAt: Date;
readonly isBusyForAvailability: boolean;
readonly archivedAt: Date | null;
}
/** An anonymous busy interval — deliberately NO title/description/owner field. */
export interface BusyInterval {
readonly from: Date;
readonly to: Date;
}
/**
* Project events to anonymous busy intervals. Drops events that are not busy
* (provider "Free"), archived/cancelled, or zero/negative length. The result
* contains ONLY {from,to} — by construction it cannot leak event content (DoD 3).
*/
export function extractBusyIntervals(events: readonly BusyCandidate[]): BusyInterval[] {
return events
.filter((e) => e.isBusyForAvailability && e.archivedAt === null && e.endsAt.getTime() > e.startsAt.getTime())
.map((e) => ({ from: e.startsAt, to: e.endsAt }))
.sort((a, b) => a.from.getTime() - b.from.getTime());
}
/**
* Merge overlapping/adjacent busy intervals into a minimal set. Used by the
* Booking slot calculator (AK-P16b) so back-to-back external events read as one
* contiguous busy block. Input need not be sorted.
*/
export function mergeBusyIntervals(intervals: readonly BusyInterval[]): BusyInterval[] {
if (intervals.length === 0) {
return [];
}
const sorted = [...intervals].sort((a, b) => a.from.getTime() - b.from.getTime());
const merged: BusyInterval[] = [{ from: sorted[0].from, to: sorted[0].to }];
for (let i = 1; i < sorted.length; i += 1) {
const last = merged[merged.length - 1];
const cur = sorted[i];
if (cur.from.getTime() <= last.to.getTime()) {
// Overlapping or touching → extend the current block.
if (cur.to.getTime() > last.to.getTime()) {
merged[merged.length - 1] = { from: last.from, to: cur.to };
}
} else {
merged.push({ from: cur.from, to: cur.to });
}
}
return merged;
}
/** True when [from,to) overlaps any busy interval (used for anti-double-booking). */
export function overlapsBusy(from: Date, to: Date, intervals: readonly BusyInterval[]): boolean {
return intervals.some((iv) => from.getTime() < iv.to.getTime() && to.getTime() > iv.from.getTime());
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { resolveConflict, type ConflictInput } from "./conflictResolution";
const d = (iso: string): Date => new Date(iso);
const base: ConflictInput = { internalLastModified: null, externalLastModified: null, internalDeleted: false, externalDeleted: false };
describe("resolveConflict (Last-Write-Wins, M25 Block F)", () => {
it("external newer → external_won", () => {
const out = resolveConflict({ ...base, internalLastModified: d("2026-07-01T09:00:00Z"), externalLastModified: d("2026-07-01T10:00:00Z") });
expect(out.resolution).toBe("external_won");
expect(out.winner).toBe("external");
});
it("hivegrid newer → hivegrid_won", () => {
const out = resolveConflict({ ...base, internalLastModified: d("2026-07-01T11:00:00Z"), externalLastModified: d("2026-07-01T10:00:00Z") });
expect(out.resolution).toBe("hivegrid_won");
expect(out.winner).toBe("hivegrid");
});
it("tie → external wins (authoritative default)", () => {
const t = d("2026-07-01T10:00:00Z");
const out = resolveConflict({ ...base, internalLastModified: t, externalLastModified: t });
expect(out.resolution).toBe("external_won");
});
it("external deleted but internal alive → external_deleted, no overwrite", () => {
const out = resolveConflict({ ...base, externalDeleted: true });
expect(out.resolution).toBe("external_deleted");
expect(out.winner).toBe("none");
});
it("internal deleted → hivegrid_deleted (push delete) even if external also changed", () => {
const out = resolveConflict({ ...base, internalDeleted: true, externalLastModified: d("2026-07-01T10:00:00Z") });
expect(out.resolution).toBe("hivegrid_deleted");
expect(out.winner).toBe("hivegrid");
});
it("every decision carries a Klartext i18n key", () => {
for (const input of [
{ ...base, externalLastModified: d("2026-07-01T10:00:00Z") },
{ ...base, internalLastModified: d("2026-07-01T10:00:00Z") },
{ ...base, externalDeleted: true },
{ ...base, internalDeleted: true },
]) {
expect(resolveConflict(input).descriptionKey).toMatch(/^calendar\.conflict\./);
}
});
});
@@ -0,0 +1,56 @@
// AK-P16a · conflict resolution decision (PURE) — Last-Write-Wins (M25 Block F).
//
// When a calendar event changed on BOTH sides between two syncs, HiveGrid resolves
// with Last-Write-Wins and tells the user in Klartext (DoD 4). This module holds
// the DECISION only (no DB, no network) so it is unit-tested in isolation; the
// ConflictResolver service applies the decision (persist + notify + conflict-log).
//
// Default tie-breaker: the EXTERNAL provider wins (M25 Block F-1) — the user can
// then manually re-apply their HiveGrid edit from the Klartext notification.
/** Mirror of the Prisma enum CalendarConflictResolution (kept in sync). */
export type ConflictResolution = "external_won" | "hivegrid_won" | "external_deleted" | "hivegrid_deleted";
export interface ConflictInput {
/** Last HiveGrid-side modification (null = unknown/never). */
readonly internalLastModified: Date | null;
/** Last external modification reported by the provider (null = unknown). */
readonly externalLastModified: Date | null;
/** The HiveGrid-internal event was deleted. */
readonly internalDeleted: boolean;
/** The external mirror was deleted/cancelled at the provider. */
readonly externalDeleted: boolean;
}
export interface ConflictDecision {
readonly resolution: ConflictResolution;
/** Which side's state should be applied. `none` = no content overwrite. */
readonly winner: "external" | "hivegrid" | "none";
/** i18n key for the Klartext conflict-log entry + notification (M002/M003). */
readonly descriptionKey: string;
}
/**
* Decide a single event conflict. Deletion beats edit; otherwise the most-recent
* write wins, with the external provider winning ties (authoritative default).
*/
export function resolveConflict(input: ConflictInput): ConflictDecision {
// Deletion cases first — a delete is a terminal state, not a timestamp race.
if (input.externalDeleted && !input.internalDeleted) {
// External mirror gone; the HiveGrid event stays (e.g. a Booking still exists).
return { resolution: "external_deleted", winner: "none", descriptionKey: "calendar.conflict.externalDeleted" };
}
if (input.internalDeleted) {
// HiveGrid event deleted → push the delete to the external mirror.
return { resolution: "hivegrid_deleted", winner: "hivegrid", descriptionKey: "calendar.conflict.hivegridDeleted" };
}
const internalAt = input.internalLastModified?.getTime() ?? 0;
const externalAt = input.externalLastModified?.getTime() ?? 0;
if (internalAt > externalAt) {
return { resolution: "hivegrid_won", winner: "hivegrid", descriptionKey: "calendar.conflict.hivegridWon" };
}
// external newer OR tie → external wins (authoritative default, M25 Block F-1).
return { resolution: "external_won", winner: "external", descriptionKey: "calendar.conflict.externalWon" };
}
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import type { NeutralEvent } from "./adapters/CalendarAdapter";
import { toExternalEventFields, type EventOwnerContext } from "./eventMapping";
const ctx: EventOwnerContext = { tenantId: "t1", userId: "u1", connectionId: "c1", provider: "google", externalCalendarId: "primary" };
const now = new Date("2026-07-01T12:00:00Z");
function event(overrides: Partial<NeutralEvent> = {}): NeutralEvent {
return {
externalId: "ext-1",
isActive: true,
title: "Kundentermin",
description: "Details",
location: "Berlin",
startsAt: new Date("2026-07-02T09:00:00Z"),
endsAt: new Date("2026-07-02T10:00:00Z"),
isAllDay: false,
timeZone: "Europe/Berlin",
recurrenceRule: null,
attendees: [{ email: "kunde@example.com", status: "accepted" }],
etag: "etag-1",
lastModifiedExternal: new Date("2026-07-01T11:00:00Z"),
isBusy: true,
...overrides,
};
}
describe("toExternalEventFields", () => {
it("maps an active event to an external-synced cache row", () => {
const fields = toExternalEventFields(event(), ctx, now);
expect(fields.source).toBe("external_synced");
expect(fields.provider).toBe("google");
expect(fields.externalEventId).toBe("ext-1");
expect(fields.externalCalendarId).toBe("primary");
expect(fields.isBusyForAvailability).toBe(true);
expect(fields.archivedAt).toBeNull();
expect(fields.tenantId).toBe("t1");
expect(fields.userId).toBe("u1");
});
it("soft-archives and de-busies a cancelled event", () => {
const fields = toExternalEventFields(event({ isActive: false }), ctx, now);
expect(fields.archivedAt).toEqual(now);
expect(fields.isBusyForAvailability).toBe(false);
});
it("carries the Free flag through (provider transparency)", () => {
const fields = toExternalEventFields(event({ isBusy: false }), ctx, now);
expect(fields.isBusyForAvailability).toBe(false);
expect(fields.archivedAt).toBeNull();
});
});
@@ -0,0 +1,72 @@
// AK-P16a · external-event → cache-row mapping (PURE).
//
// Turns a provider-neutral NeutralEvent (from the CalendarAdapter) into the field
// set persisted in CalendarEvent for the external-synced cache. Pure + decoupled
// from Prisma's generated input types so it can be unit-tested with plain objects;
// the db wrapper spreads the result into `db.calendarEvent.upsert`.
import type { NeutralEvent } from "./adapters/CalendarAdapter";
export interface EventOwnerContext {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly provider: "google";
readonly externalCalendarId: string;
}
/** The persisted field set for an external-synced CalendarEvent row. */
export interface ExternalEventFields {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly source: "external_synced";
readonly provider: "google";
readonly externalEventId: string;
readonly externalCalendarId: string;
readonly title: string | null;
readonly description: string | null;
readonly location: string | null;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay: boolean;
readonly timeZone: string | null;
readonly recurrenceRule: string | null;
readonly attendees: ReadonlyArray<{ email: string; status: string | null }>;
readonly etag: string | null;
readonly lastModifiedExternal: Date | null;
readonly isBusyForAvailability: boolean;
/** Set when the provider cancelled/deleted the event (soft-delete the cache). */
readonly archivedAt: Date | null;
}
/**
* Map one external event to its cache-row fields. A cancelled/deleted provider
* event (`isActive=false`) is soft-archived (`archivedAt`) and forced non-busy so
* it drops out of availability immediately.
*/
export function toExternalEventFields(event: NeutralEvent, ctx: EventOwnerContext, now: Date): ExternalEventFields {
const cancelled = !event.isActive;
return {
tenantId: ctx.tenantId,
userId: ctx.userId,
connectionId: ctx.connectionId,
source: "external_synced",
provider: ctx.provider,
externalEventId: event.externalId,
externalCalendarId: ctx.externalCalendarId,
title: event.title,
description: event.description,
location: event.location,
startsAt: event.startsAt,
endsAt: event.endsAt,
isAllDay: event.isAllDay,
timeZone: event.timeZone,
recurrenceRule: event.recurrenceRule,
attendees: event.attendees,
etag: event.etag,
lastModifiedExternal: event.lastModifiedExternal,
isBusyForAvailability: cancelled ? false : event.isBusy,
archivedAt: cancelled ? now : null,
};
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { signCalendarOAuthState, verifyCalendarOAuthState } from "./oauthState.server";
const secret = "test-calendar-oauth-secret-please-rotate-32b";
const input = { tenantId: "tenant-1", userId: "user-1", tenantSlug: "acme" };
describe("calendar OAuth state (CSRF)", () => {
it("round-trips a signed state", () => {
const token = signCalendarOAuthState(input, { secret });
const result = verifyCalendarOAuthState(token, { secret });
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("expected ok");
expect(result.payload.tenantId).toBe("tenant-1");
expect(result.payload.userId).toBe("user-1");
expect(result.payload.tenantSlug).toBe("acme");
});
it("rejects a tampered payload", () => {
const token = signCalendarOAuthState(input, { secret });
const tampered = `x${token.slice(1)}`;
expect(verifyCalendarOAuthState(tampered, { secret })).toEqual({ ok: false, reason: "bad-signature" });
});
it("rejects a wrong-secret signature", () => {
const token = signCalendarOAuthState(input, { secret });
expect(verifyCalendarOAuthState(token, { secret: "a-different-secret-value-of-length-32xx" })).toEqual({ ok: false, reason: "bad-signature" });
});
it("rejects a malformed token", () => {
expect(verifyCalendarOAuthState("not-a-token", { secret })).toEqual({ ok: false, reason: "malformed" });
});
it("rejects an expired state", () => {
const token = signCalendarOAuthState(input, { secret, now: () => 1_000_000 });
const later = () => 1_000_000 + 11 * 60 * 1000; // 11 minutes later (> 10m TTL)
expect(verifyCalendarOAuthState(token, { secret, now: later })).toEqual({ ok: false, reason: "expired" });
});
});
@@ -0,0 +1,99 @@
// AK-P16a · OAuth state signing for the Google connect flow (CSRF + context).
//
// The OAuth callback at /integrations/google/oauth/callback is NOT tenant-scoped
// (Google redirects to a fixed URI), so the tenant + user travel inside a SIGNED
// `state` parameter rather than a cookie. We HMAC-SHA256 the JSON payload with
// CRYPTO_SECRET||SESSION_SECRET (same convention as admin-sso/state.server) and
// URL-safe-base64 encode it. 10-minute TTL bounds the replay window.
import { createHmac, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
const STATE_TTL_MS = 10 * 60 * 1000;
const PAYLOAD_VERSION = "v1";
export interface CalendarOAuthStatePayload {
readonly tenantId: string;
readonly userId: string;
readonly tenantSlug: string;
/** Epoch milliseconds. */
readonly createdAt: number;
}
export type VerifyStateResult =
| { readonly ok: true; readonly payload: CalendarOAuthStatePayload }
| { readonly ok: false; readonly reason: "malformed" | "bad-signature" | "expired" };
function getSecret(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 calendar OAuth state.");
}
return secret;
}
function base64UrlEncode(input: string): string {
return Buffer.from(input, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64UrlDecode(value: string): string {
const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - (value.length % 4));
return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
}
function sign(body: string, secret: string): string {
return Buffer.from(createHmac("sha256", secret).update(body).digest()).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
/** Sign a fresh state token for the consent redirect. */
export function signCalendarOAuthState(
input: { tenantId: string; userId: string; tenantSlug: string },
options: { now?: () => number; secret?: string } = {},
): string {
const payload: CalendarOAuthStatePayload = {
tenantId: input.tenantId,
userId: input.userId,
tenantSlug: input.tenantSlug,
createdAt: options.now ? options.now() : Date.now(),
};
const body = base64UrlEncode(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }));
return `${body}.${sign(body, getSecret(options.secret))}`;
}
/** Verify + decode a state token returned by Google. */
export function verifyCalendarOAuthState(state: string, options: { now?: () => number; secret?: string } = {}): VerifyStateResult {
const dot = state.lastIndexOf(".");
if (dot <= 0) {
return { ok: false, reason: "malformed" };
}
const body = state.slice(0, dot);
const sig = state.slice(dot + 1);
let secret: string;
try {
secret = getSecret(options.secret);
} catch {
return { ok: false, reason: "malformed" };
}
const expected = sign(body, secret);
const a = Buffer.from(sig);
const b = Buffer.from(expected);
if (a.length !== b.length || !timingSafeEqual(a, b)) {
return { ok: false, reason: "bad-signature" };
}
let decoded: { v: string; p: CalendarOAuthStatePayload };
try {
decoded = JSON.parse(base64UrlDecode(body)) as { v: string; p: CalendarOAuthStatePayload };
} catch {
return { ok: false, reason: "malformed" };
}
if (decoded.v !== PAYLOAD_VERSION || !decoded.p || typeof decoded.p.createdAt !== "number") {
return { ok: false, reason: "malformed" };
}
const now = options.now ? options.now() : Date.now();
if (now - decoded.p.createdAt > STATE_TTL_MS) {
return { ok: false, reason: "expired" };
}
return { ok: true, payload: decoded.p };
}