Skip to content

Your favorite shift management application!

feat(ui): subscribable ICS feed per calendar (#230)

panteLf6793323a7b2
diff --git a/.env.example b/.env.example
index 36f46fd..9f7809a 100644
--- a/.env.example
+++ b/.env.example
@@ -225,6 +225,8 @@ ALLOW_USER_REGISTRATION=true # Enable/disable new user signups
# RATE_LIMIT_EXPORT_PDF_WINDOW=600 # 10 minutes
# RATE_LIMIT_EXPORT_ICS_REQUESTS=20 # Per user
# RATE_LIMIT_EXPORT_ICS_WINDOW=600 # 10 minutes
+# RATE_LIMIT_CALENDAR_FEED_REQUESTS=60 # Per feed owner (subscribed calendar apps poll this)
+# RATE_LIMIT_CALENDAR_FEED_WINDOW=600 # 10 minutes
# Calendar Access Tokens (Share Links)
# RATE_LIMIT_TOKEN_VALIDATION_REQUESTS=10 # Per IP
diff --git a/README.md b/README.md
index 734ec65..2fcb219 100644
--- a/README.md
+++ b/README.md
@@ -51,7 +51,7 @@ _BetterShift is a self-hosted shift management application for teams and individ
| **Authentication** | Email/password, OAuth (Google, GitHub, Discord), or custom OIDC |
| **Admin Panel** | User management, calendar administration, audit logging |
| **Statistics** | Real-time shift tracking with visual charts |
-| **Export** | Download calendars as ICS or PDF |
+| **Export** | Download calendars as ICS or PDF, or subscribe via a live ICS link |
| **Localization** | English, French, German, Italian, Spanish, Czech |
| **PWA** | Installable on mobile and desktop |
@@ -105,6 +105,7 @@ npm run dev
| [Authentication Setup](docs/AUTH_SETUP.md) | Email/password, OAuth, OIDC configuration |
| [Admin Panel](docs/ADMIN_PANEL.md) | User management, calendar administration |
| [Permissions](docs/PERMISSIONS.md) | Sharing, access tokens, guest access |
+| [Calendar Feed](docs/CALENDAR_FEED.md) | Subscribe to a calendar from Google, Apple, Outlook or Home Assistant |
| [Telemetry](docs/TELEMETRY.md) | What data is collected and how to disable it |
| [Enabling Auth on an Existing Instance](docs/ENABLING_AUTH.md) | Turn on accounts for an instance that ran with `AUTH_ENABLED=false` |
| [Upgrade Guide](docs/UPGRADING.md) | Breaking changes between versions and the steps to get through them |
diff --git a/app/api/calendars/[id]/feed-token/route.ts b/app/api/calendars/[id]/feed-token/route.ts
new file mode 100644
index 0000000..49de696
--- /dev/null
+++ b/app/api/calendars/[id]/feed-token/route.ts
@@ -0,0 +1,130 @@
+import { NextRequest, NextResponse } from "next/server";
+import { and, eq } from "drizzle-orm";
+import { db } from "@/lib/db";
+import { calendarFeedTokens, calendars } from "@/lib/db/schema";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { isAuthEnabled } from "@/lib/auth/feature-flags";
+import { generateAccessToken } from "@/lib/auth/token-auth";
+import { logUserAction, type CalendarFeedTokenMetadata } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import { canReadFeed, feedOwnerCondition, getFeedToken } from "@/lib/calendar-feed";
+
+type Params = { params: Promise<{ id: string }> };
+
+// Feeds are bound to an account, so guests get nothing; with auth off the single owner is null.
+async function resolveFeedOwner(
+ request: NextRequest,
+ calendarId: string
+): Promise<{ userId: string | null } | NextResponse> {
+ const user = await getSessionUser(request.headers);
+ if (isAuthEnabled() && !user) {
+ return NextResponse.json({ error: "Authentication required" }, { status: 401 });
+ }
+ const userId = user?.id ?? null;
+ if (!(await canReadFeed(userId, calendarId))) {
+ return NextResponse.json({ error: "Insufficient permissions" }, { status: 403 });
+ }
+ return { userId };
+}
+
+function toResponse(row: { token: string; createdAt: Date; lastUsedAt: Date | null } | null) {
+ return {
+ token: row?.token ?? null,
+ createdAt: row?.createdAt?.toISOString() ?? null,
+ lastUsedAt: row?.lastUsedAt?.toISOString() ?? null,
+ };
+}
+
+export async function GET(request: NextRequest, { params }: Params) {
+ try {
+ const { id: calendarId } = await params;
+ const owner = await resolveFeedOwner(request, calendarId);
+ if (owner instanceof NextResponse) return owner;
+ return NextResponse.json(toResponse(await getFeedToken(owner.userId, calendarId)));
+ } catch (error) {
+ console.error("[API] GET /api/calendars/[id]/feed-token error:", error);
+ return NextResponse.json({ error: "Failed to fetch feed link" }, { status: 500 });
+ }
+}
+
+export async function POST(request: NextRequest, { params }: Params) {
+ try {
+ const { id: calendarId } = await params;
+ const owner = await resolveFeedOwner(request, calendarId);
+ if (owner instanceof NextResponse) return owner;
+
+ const rateLimitResponse = rateLimit(request, owner.userId, "token-creation");
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const ownerWhere = and(
+ eq(calendarFeedTokens.calendarId, calendarId),
+ feedOwnerCondition(owner.userId)
+ );
+ const created = db.transaction((tx) => {
+ const removed = tx.delete(calendarFeedTokens).where(ownerWhere).returning().all();
+ const [row] = tx
+ .insert(calendarFeedTokens)
+ .values({
+ calendarId,
+ userId: owner.userId,
+ token: generateAccessToken(),
+ // SQLite's CURRENT_TIMESTAMP default yields text, not the epoch seconds
+ // "timestamp" mode expects — set it here like other inserts in this codebase.
+ createdAt: new Date(),
+ })
+ .returning()
+ .all();
+ return { row, rotated: removed.length > 0 };
+ });
+
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ columns: { name: true },
+ });
+ void logUserAction<CalendarFeedTokenMetadata>({
+ action: "calendar_feed_token_created",
+ userId: owner.userId,
+ resourceType: "calendar",
+ resourceId: calendarId,
+ metadata: { calendarName: calendar?.name ?? "", rotated: created.rotated },
+ request,
+ });
+
+ return NextResponse.json(toResponse(created.row), { status: 201 });
+ } catch (error) {
+ console.error("[API] POST /api/calendars/[id]/feed-token error:", error);
+ return NextResponse.json({ error: "Failed to create feed link" }, { status: 500 });
+ }
+}
+
+export async function DELETE(request: NextRequest, { params }: Params) {
+ try {
+ const { id: calendarId } = await params;
+ const owner = await resolveFeedOwner(request, calendarId);
+ if (owner instanceof NextResponse) return owner;
+
+ const removed = await db
+ .delete(calendarFeedTokens)
+ .where(and(eq(calendarFeedTokens.calendarId, calendarId), feedOwnerCondition(owner.userId)))
+ .returning();
+
+ if (removed.length > 0) {
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ columns: { name: true },
+ });
+ void logUserAction<CalendarFeedTokenMetadata>({
+ action: "calendar_feed_token_revoked",
+ userId: owner.userId,
+ resourceType: "calendar",
+ resourceId: calendarId,
+ metadata: { calendarName: calendar?.name ?? "" },
+ request,
+ });
+ }
+ return new NextResponse(null, { status: 204 });
+ } catch (error) {
+ console.error("[API] DELETE /api/calendars/[id]/feed-token error:", error);
+ return NextResponse.json({ error: "Failed to revoke feed link" }, { status: 500 });
+ }
+}
diff --git a/app/api/export/ics/route.ts b/app/api/export/ics/route.ts
index 75b5bc4..60e59c1 100644
--- a/app/api/export/ics/route.ts
+++ b/app/api/export/ics/route.ts
@@ -1,15 +1,12 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { calendars, shifts } from "@/lib/db/schema";
+import { calendars } from "@/lib/db/schema";
import { inArray } from "drizzle-orm";
-import ICAL from "ical.js";
import { getSessionUser } from "@/lib/auth/sessions";
import { hasCapability } from "@/lib/auth/permissions";
-import { getServerTimezone, formatDateToLocal } from "@/lib/date-utils";
+import { formatDateToLocal } from "@/lib/date-utils";
import { rateLimit } from "@/lib/rate-limiter";
-import { toTimeRanges } from "@/lib/time-ranges";
-import { getCalendarCustomFields, withShiftCustomFields } from "@/lib/shift-custom-fields";
-import { formatValueForDisplay } from "@/lib/custom-fields";
+import { buildIcsCalendar } from "@/lib/ics";
export async function POST(request: NextRequest) {
try {
@@ -60,138 +57,8 @@ export async function POST(request: NextRequest) {
);
}
- // Get all shifts for accessible calendars
- let allShifts = await db.query.shifts.findMany({
- where: inArray(
- shifts.calendarId,
- accessibleCalendars.map((c) => c.id)
- ),
- orderBy: (shifts, { asc }) => [asc(shifts.date)],
- with: { segments: true },
- });
-
- // A calendar that has since turned split shifts off must fall back to
- // showing only its shifts' primary ranges, without deleting the stored segments.
- const splitShiftsEnabledIds = new Set(
- accessibleCalendars.filter((c) => c.splitShiftsEnabled).map((c) => c.id)
- );
- allShifts = allShifts.map((shift) =>
- splitShiftsEnabledIds.has(shift.calendarId) ? shift : { ...shift, segments: [] }
- );
-
- // Create calendar name lookup
- const calendarMap = new Map(accessibleCalendars.map((c) => [c.id, c.name]));
-
- // Field keys are per calendar, so definitions and values must be resolved calendar by calendar.
- const definitionsByCalendar = new Map(
- await Promise.all(
- accessibleCalendars.map(
- async (c) => [c.id, await getCalendarCustomFields(c.id)] as const
- )
- )
- );
- const customFieldsByShiftId = new Map<string, Record<string, string | number | boolean | null>>();
- for (const c of accessibleCalendars) {
- const definitions = definitionsByCalendar.get(c.id) ?? [];
- const calendarShifts = allShifts.filter((s) => s.calendarId === c.id);
- const withFields = await withShiftCustomFields(calendarShifts, definitions);
- for (const s of withFields) {
- customFieldsByShiftId.set(s.id, s.customFields);
- }
- }
-
- // Get server timezone for proper time conversion
- const serverTimezone = getServerTimezone();
-
- // Determine if multi-calendar export
- const isMultiCalendar = accessibleCalendars.length > 1;
-
- // Create iCalendar
- const cal = new ICAL.Component(["vcalendar", [], []]);
- cal.updatePropertyWithValue(
- "prodid",
- "-//BetterShift//Calendar Export//EN"
- );
- cal.updatePropertyWithValue("version", "2.0");
- cal.updatePropertyWithValue("calscale", "GREGORIAN");
- cal.updatePropertyWithValue("method", "PUBLISH");
- cal.updatePropertyWithValue(
- "x-wr-calname",
- isMultiCalendar
- ? "BetterShift Multi-Calendar"
- : accessibleCalendars[0].name
- );
- cal.updatePropertyWithValue("x-wr-timezone", serverTimezone);
-
- // Add shifts as events
- for (const shift of allShifts) {
- const shiftDate = shift.date as Date;
- const calendarName = calendarMap.get(shift.calendarId);
- const summary = isMultiCalendar
- ? `[${calendarName}] ${shift.title}`
- : shift.title;
-
- const ranges = shift.isAllDay ? [null] : toTimeRanges(shift);
-
- const definitions = definitionsByCalendar.get(shift.calendarId) ?? [];
- const customFields = customFieldsByShiftId.get(shift.id) ?? {};
- const fieldLines = definitions
- .map((d) => {
- const raw = customFields[d.key];
- if (raw === null || raw === undefined || raw === "") return null;
- return `${d.label}: ${formatValueForDisplay(d, String(raw), locale)}`;
- })
- .filter((line): line is string => line !== null);
- const description = [shift.notes, ...fieldLines].filter(Boolean).join("\n");
-
- ranges.forEach((range, index) => {
- const vevent = new ICAL.Component("vevent");
- const event = new ICAL.Event(vevent);
-
- event.uid = index === 0 ? shift.id : `${shift.id}-seg-${index}`;
- event.summary = summary;
- if (description) {
- event.description = description;
- }
-
- if (!range) {
- // All-day event (DTEND is exclusive per RFC 5545)
- const dateStr = formatDateToLocal(shiftDate);
- event.startDate = ICAL.Time.fromDateString(dateStr);
-
- const endDate = new Date(shiftDate);
- endDate.setDate(endDate.getDate() + 1);
- const endYear = endDate.getFullYear();
- const endMonth = String(endDate.getMonth() + 1).padStart(2, "0");
- const endDay = String(endDate.getDate()).padStart(2, "0");
- event.endDate = ICAL.Time.fromDateString(`${endYear}-${endMonth}-${endDay}`);
- } else {
- const [startHour, startMinute] = range.startTime.split(":").map(Number);
- const [endHour, endMinute] = range.endTime.split(":").map(Number);
-
- const startDateTime = new Date(shiftDate);
- startDateTime.setHours(startHour, startMinute, 0, 0);
-
- const endDateTime = new Date(shiftDate);
- endDateTime.setHours(endHour, endMinute, 0, 0);
-
- if (endDateTime <= startDateTime) {
- endDateTime.setDate(endDateTime.getDate() + 1);
- }
-
- event.startDate = ICAL.Time.fromJSDate(startDateTime, true);
- event.endDate = ICAL.Time.fromJSDate(endDateTime, true);
- }
-
- vevent.addPropertyWithValue("color", shift.color);
- vevent.addPropertyWithValue("x-apple-calendar-color", shift.color);
-
- cal.addSubcomponent(vevent);
- });
- }
-
// Generate ICS content
- const icsContent = cal.toString();
+ const icsContent = await buildIcsCalendar({ calendars: accessibleCalendars, locale });
// Create filename from calendar names (truncated)
const calendarNamesParts = accessibleCalendars
diff --git a/app/api/feed/[token]/route.ts b/app/api/feed/[token]/route.ts
new file mode 100644
index 0000000..7adbcd3
--- /dev/null
+++ b/app/api/feed/[token]/route.ts
@@ -0,0 +1,61 @@
+import { NextRequest, NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { db } from "@/lib/db";
+import { calendarFeedTokens } from "@/lib/db/schema";
+import { rateLimit } from "@/lib/rate-limiter";
+import { canReadFeed, findFeedToken } from "@/lib/calendar-feed";
+import { buildIcsCalendar } from "@/lib/ics";
+import { defaultLocale } from "@/lib/locales";
+
+const notFound = () => NextResponse.json({ error: "Not found" }, { status: 404 });
+
+export async function GET(
+ request: NextRequest,
+ { params }: { params: Promise<{ token: string }> }
+) {
+ try {
+ const { token: rawToken } = await params;
+ // Outlook and some other clients only subscribe to URLs ending in .ics
+ const token = rawToken.replace(/\.ics$/i, "");
+
+ const feedToken = await findFeedToken(token);
+ if (!feedToken) return notFound();
+
+ // Tokens minted with auth off have no user; key those on the token so the limit doesn't depend on the proxy's IP.
+ const rateLimitResponse = rateLimit(
+ request,
+ feedToken.userId,
+ "calendar-feed",
+ feedToken.userId ? undefined : feedToken.id
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ if (!(await canReadFeed(feedToken.userId, feedToken.calendarId))) return notFound();
+
+ const calendar = await db.query.calendars.findFirst({
+ where: (c, { eq }) => eq(c.id, feedToken.calendarId),
+ columns: { id: true, name: true, splitShiftsEnabled: true },
+ });
+ if (!calendar) return notFound();
+
+ void db
+ .update(calendarFeedTokens)
+ .set({ lastUsedAt: new Date() })
+ .where(eq(calendarFeedTokens.id, feedToken.id))
+ .catch((error) => console.error("Failed to record feed usage:", error));
+
+ const ics = await buildIcsCalendar({ calendars: [calendar], locale: defaultLocale, feed: true });
+ const filename = calendar.name.replace(/[^a-z0-9]/gi, "_").toLowerCase().substring(0, 40) || "calendar";
+
+ return new NextResponse(ics, {
+ headers: {
+ "Content-Type": "text/calendar; charset=utf-8",
+ "Content-Disposition": `inline; filename="${filename}.ics"`,
+ "Cache-Control": "private, max-age=300",
+ },
+ });
+ } catch (error) {
+ console.error("Error serving calendar feed:", error);
+ return NextResponse.json({ error: "Failed to build feed" }, { status: 500 });
+ }
+}
diff --git a/components/export-dialog.tsx b/components/export-dialog.tsx
index 097cb81..46fc18e 100644
--- a/components/export-dialog.tsx
+++ b/components/export-dialog.tsx
@@ -2,9 +2,12 @@
import { useMemo, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
-import { Check, Download } from "lucide-react";
+import { format } from "date-fns";
+import { Check, Copy, Download, Link } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
import {
Select,
SelectContent,
@@ -17,11 +20,126 @@ import { ChoiceChips, Field, OptionCards, ToggleRow } from "@/components/form-ki
import { isRateLimitError, handleRateLimitError } from "@/lib/rate-limit-client";
import { CalendarWithCount } from "@/lib/types";
import { useCalendars } from "@/hooks/useCalendars";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useCalendarFeedToken } from "@/hooks/useCalendarFeedToken";
+import { getDateLocale } from "@/lib/locales";
import { cn } from "@/lib/utils";
-type Format = "ics" | "pdf";
+type Format = "ics" | "pdf" | "feed";
type Range = "all" | "month" | "year";
+/** The "Subscription link" card: create/copy/rotate/revoke a per-calendar ICS feed token. */
+function FeedSection({
+ feed,
+}: {
+ feed: ReturnType<typeof useCalendarFeedToken>;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const [rotateConfirmOpen, setRotateConfirmOpen] = useState(false);
+ const [revokeConfirmOpen, setRevokeConfirmOpen] = useState(false);
+ const { feed: data, feedUrl, isLoading, isError, isMutating, createFeed, revokeFeed } = feed;
+
+ const copyLink = async () => {
+ if (!feedUrl) return;
+ await navigator.clipboard.writeText(feedUrl);
+ toast.success(t("export.feed.copied"));
+ };
+
+ // Offering "create" before the GET succeeded would silently rotate an existing link.
+ if (isLoading || (isError && !data.token)) {
+ return (
+ <p className="text-[13.5px] text-fg-secondary">
+ {isLoading ? t("common.loading") : t("common.fetchError", { item: t("export.feed.title") })}
+ </p>
+ );
+ }
+
+ if (!data.token) {
+ return (
+ <div className="flex flex-col gap-3">
+ <p className="text-[13.5px] text-fg-secondary">{t("export.feed.empty")}</p>
+ <Button
+ className="h-10 gap-2 self-start font-semibold"
+ onClick={() => createFeed()}
+ disabled={isMutating}
+ >
+ <Link className="size-4" />
+ {t("export.feed.create")}
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <Input readOnly value={feedUrl ?? ""} className="h-10 flex-1 font-mono text-[12.5px]" />
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="h-10 w-10 shrink-0"
+ aria-label={t("export.feed.copy")}
+ title={t("export.feed.copy")}
+ onClick={copyLink}
+ >
+ <Copy className="size-4" />
+ </Button>
+ </div>
+ <p className="text-[12px] text-fg-tertiary">
+ {data.lastUsedAt
+ ? t("export.feed.lastUsed", {
+ date: format(new Date(data.lastUsedAt), "PPp", { locale: getDateLocale(locale) }),
+ })
+ : t("export.feed.neverUsed")}
+ </p>
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ className="h-10 flex-1 font-semibold"
+ onClick={() => setRotateConfirmOpen(true)}
+ disabled={isMutating}
+ >
+ {t("export.feed.rotate")}
+ </Button>
+ <Button
+ variant="destructive"
+ className="h-10 flex-1 font-semibold"
+ onClick={() => setRevokeConfirmOpen(true)}
+ disabled={isMutating}
+ >
+ {t("export.feed.revoke")}
+ </Button>
+ </div>
+ <p className="text-[12px] text-fg-tertiary">{t("export.feed.securityNote")}</p>
+
+ <ConfirmationDialog
+ open={rotateConfirmOpen}
+ onOpenChange={setRotateConfirmOpen}
+ onConfirm={async () => {
+ if (await createFeed()) setRotateConfirmOpen(false);
+ }}
+ title={t("export.feed.rotateConfirm")}
+ description={t("export.feed.rotateConfirmDescription")}
+ confirmText={t("export.feed.rotate")}
+ />
+ <ConfirmationDialog
+ open={revokeConfirmOpen}
+ onOpenChange={setRevokeConfirmOpen}
+ onConfirm={async () => {
+ if (await revokeFeed()) setRevokeConfirmOpen(false);
+ }}
+ title={t("export.feed.revokeConfirm")}
+ description={t("export.feed.revokeConfirmDescription")}
+ confirmText={t("export.feed.revoke")}
+ confirmVariant="destructive"
+ />
+ </div>
+ );
+}
+
function monthValue(date: Date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}
@@ -37,7 +155,7 @@ export function ExportPanel({
const locale = useLocale();
const { calendars } = useCalendars();
const calendar = calendars.find((c) => c.id === calendarId);
- const [format, setFormat] = useState<Format>("ics");
+ const [selectedFormat, setSelectedFormat] = useState<Format>("ics");
const [range, setRange] = useState<Range>("all");
const [month, setMonth] = useState(() => monthValue(new Date()));
const [year, setYear] = useState(() => String(new Date().getFullYear()));
@@ -45,6 +163,11 @@ export function ExportPanel({
const [selectedIds, setSelectedIds] = useState<string[]>([calendarId]);
const [loading, setLoading] = useState(false);
+ const { isAuthenticated } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+ const canUseFeed = isAuthenticated || !isAuthEnabled;
+ const feed = useCalendarFeedToken(calendarId, canUseFeed && selectedFormat === "feed");
+
const monthOptions = useMemo(() => {
const today = new Date();
return Array.from({ length: 25 }, (_, i) => {
@@ -69,11 +192,11 @@ export function ExportPanel({
try {
const params = new URLSearchParams();
params.append("locale", locale);
- if (format === "pdf") {
+ if (selectedFormat === "pdf") {
if (range === "month") params.append("month", month);
if (range === "year") params.append("year", year);
}
- const url = `/api/export/${format}${params.toString() ? `?${params}` : ""}`;
+ const url = `/api/export/${selectedFormat}${params.toString() ? `?${params}` : ""}`;
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -99,7 +222,7 @@ export function ExportPanel({
link.href = downloadUrl;
link.download =
match?.[1] ??
- `${(calendar?.name ?? "calendar").replace(/[^a-z0-9]/gi, "_").toLowerCase()}_export.${format}`;
+ `${(calendar?.name ?? "calendar").replace(/[^a-z0-9]/gi, "_").toLowerCase()}_export.${selectedFormat}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
@@ -121,16 +244,28 @@ export function ExportPanel({
<div className="flex flex-col gap-5">
<Field label={t("export.formatLabel")}>
<OptionCards<Format>
- value={format}
- onChange={setFormat}
+ value={selectedFormat}
+ onChange={setSelectedFormat}
+ columns={canUseFeed ? 3 : 2}
options={[
{ value: "ics", title: t("export.icsFormat"), description: t("export.icsHint") },
{ value: "pdf", title: t("export.pdfFormat"), description: t("export.pdfHint") },
+ ...(canUseFeed
+ ? [
+ {
+ value: "feed" as const,
+ title: t("export.feed.title"),
+ description: t("export.feed.hint"),
+ },
+ ]
+ : []),
]}
/>
</Field>
- {format === "pdf" && (
+ {selectedFormat === "feed" && <FeedSection feed={feed} />}
+
+ {selectedFormat === "pdf" && (
<Field label={t("export.rangeLabel")}>
<ChoiceChips<Range>
value={range}
@@ -172,7 +307,7 @@ export function ExportPanel({
</Field>
)}
- {calendars.length > 1 && (
+ {selectedFormat !== "feed" && calendars.length > 1 && (
<div className="flex flex-col gap-2 border-t border-line pt-4">
<ToggleRow
id="export-multi"
@@ -230,12 +365,14 @@ export function ExportPanel({
</PanelBody>
<PanelFooter>
<Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose} disabled={loading}>
- {t("common.cancel")}
- </Button>
- <Button className="h-10 flex-1 gap-2 font-semibold" onClick={handleExport} disabled={loading}>
- <Download className="size-4" />
- {loading ? t("common.loading") : t("export.download")}
+ {selectedFormat === "feed" ? t("common.close") : t("common.cancel")}
</Button>
+ {selectedFormat !== "feed" && (
+ <Button className="h-10 flex-1 gap-2 font-semibold" onClick={handleExport} disabled={loading}>
+ <Download className="size-4" />
+ {loading ? t("common.loading") : t("export.download")}
+ </Button>
+ )}
</PanelFooter>
</>
);
diff --git a/components/form-kit.tsx b/components/form-kit.tsx
index 317b1df..e2069fa 100644
--- a/components/form-kit.tsx
+++ b/components/form-kit.tsx
@@ -260,7 +260,7 @@ export function OptionCards<T extends string>({
className={cn(
"grid gap-2",
columns === 2 && "grid-cols-2",
- columns === 3 && "grid-cols-3",
+ columns === 3 && "grid-cols-1 sm:grid-cols-3",
columns === 4 && "grid-cols-2 sm:grid-cols-4"
)}
>
diff --git a/docs/CALENDAR_FEED.md b/docs/CALENDAR_FEED.md
new file mode 100644
index 0000000..676bec1
--- /dev/null
+++ b/docs/CALENDAR_FEED.md
@@ -0,0 +1,75 @@
+# Calendar Feed Guide
+
+This guide explains the subscribable ICS feed link for a calendar — what it is, how to add it to Google Calendar, Apple Calendar, Outlook, or Home Assistant, and its limits.
+
+## Table of Contents
+
+1. [What the Link Is](#what-the-link-is)
+2. [Creating, Rotating, and Revoking](#creating-rotating-and-revoking)
+3. [Google Calendar](#google-calendar)
+4. [Apple Calendar](#apple-calendar)
+5. [Outlook](#outlook)
+6. [Home Assistant](#home-assistant)
+7. [Refresh Behavior](#refresh-behavior)
+8. [Rate Limiting](#rate-limiting)
+9. [Times and Locale](#times-and-locale)
+
+---
+
+## What the Link Is
+
+Every calendar can have one feed link per user: a secret URL of the form `https://<your-instance>/api/feed/<token>.ics` (the `.ics` suffix is optional — clients that require it, and clients that don't, both work). Anyone who has the URL can fetch the calendar's shifts as an ICS calendar, read-only; calendar notes are not included.
+
+The link is not a separate grant of access — it follows whatever access you currently have to the calendar. Every fetch re-checks it: if your share is removed, your account is deleted or banned, or (for a link created while `AUTH_ENABLED=false`) the instance later turns auth on, the feed returns `404` from the next fetch on, with no separate step to revoke it. Links created with auth off therefore stop working once auth is on; each user recreates theirs after signing in. Guests without an account cannot create a feed link.
+
+## Creating, Rotating, and Revoking
+
+Feed links live in the calendar's **Export** dialog (Settings → Export), under the "Subscription Link" option alongside the ICS and PDF export formats. From there:
+
+- **Create Link** generates the link for you, for this calendar, if you don't already have one.
+- **Regenerate** (rotate) replaces it with a new token; the old URL stops working immediately, so any app already subscribed needs the new link re-entered.
+- **Revoke** deletes it outright.
+
+There is exactly one link per user and calendar — creating again after a revoke issues a fresh token, it does not reuse the old one.
+
+## Google Calendar
+
+Google Calendar only supports adding a feed by URL from the desktop web app, not the mobile app:
+
+1. In the left sidebar, next to **Other calendars**, click **+** → **From URL**.
+2. Paste the feed URL and click **Add calendar**.
+
+Google Calendar ignores the feed's refresh hint and re-polls on its own internal schedule (see [Refresh Behavior](#refresh-behavior)).
+
+## Apple Calendar
+
+1. **File → New Calendar Subscription…**
+2. Paste the feed URL and click **Subscribe**.
+3. In the subscription's settings, set **Auto-refresh** to how often you want it checked (Apple defaults to every few hours).
+
+## Outlook
+
+1. **Add calendar → Subscribe from web**.
+2. Paste the feed URL and confirm.
+
+## Home Assistant
+
+1. **Settings → Devices & services → Add integration**.
+2. Search for **Remote Calendar** and paste the feed URL.
+
+## Refresh Behavior
+
+The feed publishes `REFRESH-INTERVAL` and `X-PUBLISHED-TTL` as `PT1H` (one hour) to hint how often it should be re-fetched. Most clients honor this loosely; Google Calendar ignores it entirely and refreshes on its own schedule, typically somewhere between several hours and a day. None of this is something BetterShift or the calendar owner can force — a client that has already cached the feed will keep serving stale data until it decides to poll again.
+
+## Rate Limiting
+
+Feed requests are rate limited per feed owner (not per calendar or per client), via:
+
+- `RATE_LIMIT_CALENDAR_FEED_REQUESTS` (default `60`)
+- `RATE_LIMIT_CALENDAR_FEED_WINDOW`, in seconds (default `600`)
+
+An app that polls one feed on a normal schedule stays well under the default; the limit exists mainly to bound abuse of a leaked link.
+
+## Times and Locale
+
+Event times in the feed are written in UTC, computed from the server's `TZ` environment variable — the same conversion the regular ICS export uses. Custom field labels in event descriptions are rendered in the instance's `DEFAULT_LOCALE`, not the subscriber's own locale, since the feed has no per-request user to localize for.
diff --git a/drizzle/0032_heavy_wolfsbane.sql b/drizzle/0032_heavy_wolfsbane.sql
new file mode 100644
index 0000000..f941a78
--- /dev/null
+++ b/drizzle/0032_heavy_wolfsbane.sql
@@ -0,0 +1,13 @@
+CREATE TABLE `calendar_feed_tokens` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `user_id` text,
+ `token` text NOT NULL,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ `last_used_at` integer,
+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `calendar_feed_tokens_token_unique` ON `calendar_feed_tokens` (`token`);--> statement-breakpoint
+CREATE INDEX `calendar_feed_tokens_calendarId_userId_idx` ON `calendar_feed_tokens` (`calendar_id`,`user_id`);
\ No newline at end of file
diff --git a/drizzle/meta/0032_snapshot.json b/drizzle/meta/0032_snapshot.json
new file mode 100644
index 0000000..dd9dcae
--- /dev/null
+++ b/drizzle/meta/0032_snapshot.json
@@ -0,0 +1,2764 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "31efd397-2d99-44ae-86b9-b8d175ed55db",
+ "prevId": "9ce9f984-dc11-4995-94c6-23bb69314be1",
+ "tables": {
+ "account": {
+ "name": "account",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "announcements": {
+ "name": "announcements",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tone": {
+ "name": "tone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'info'"
+ },
+ "show_on_auth": {
+ "name": "show_on_auth",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "show_on_dashboard": {
+ "name": "show_on_dashboard",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "starts_at": {
+ "name": "starts_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ends_at": {
+ "name": "ends_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "announcements_created_by_user_id_fk": {
+ "name": "announcements_created_by_user_id_fk",
+ "tableFrom": "announcements",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "audit_logs": {
+ "name": "audit_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'info'"
+ },
+ "is_user_visible": {
+ "name": "is_user_visible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "audit_logs_userId_timestamp_idx": {
+ "name": "audit_logs_userId_timestamp_idx",
+ "columns": [
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_action_timestamp_idx": {
+ "name": "audit_logs_action_timestamp_idx",
+ "columns": [
+ "action",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_userVisible_userId_timestamp_idx": {
+ "name": "audit_logs_userVisible_userId_timestamp_idx",
+ "columns": [
+ "is_user_visible",
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "audit_logs_user_id_user_id_fk": {
+ "name": "audit_logs_user_id_user_id_fk",
+ "tableFrom": "audit_logs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_access_tokens": {
+ "name": "calendar_access_tokens",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bundle_id": {
+ "name": "bundle_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage_count": {
+ "name": "usage_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "calendar_access_tokens_token_unique": {
+ "name": "calendar_access_tokens_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "calendar_access_tokens_token_idx": {
+ "name": "calendar_access_tokens_token_idx",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_calendarId_isActive_idx": {
+ "name": "calendar_access_tokens_calendarId_isActive_idx",
+ "columns": [
+ "calendar_id",
+ "is_active"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_createdBy_idx": {
+ "name": "calendar_access_tokens_createdBy_idx",
+ "columns": [
+ "created_by"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_bundleId_idx": {
+ "name": "calendar_access_tokens_bundleId_idx",
+ "columns": [
+ "bundle_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_access_tokens_calendar_id_calendars_id_fk": {
+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk": {
+ "name": "calendar_access_tokens_bundle_id_calendar_permission_bundles_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "calendar_permission_bundles",
+ "columnsFrom": [
+ "bundle_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "calendar_access_tokens_created_by_user_id_fk": {
+ "name": "calendar_access_tokens_created_by_user_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_custom_fields": {
+ "name": "calendar_custom_fields",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "required": {
+ "name": "required",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "show_in_calendar": {
+ "name": "show_in_calendar",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_custom_fields_calendarId_idx": {
+ "name": "calendar_custom_fields_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_custom_fields_calendarId_key_idx": {
+ "name": "calendar_custom_fields_calendarId_key_idx",
+ "columns": [
+ "calendar_id",
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "calendar_custom_fields_calendar_id_calendars_id_fk": {
+ "name": "calendar_custom_fields_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_custom_fields",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_custom_fields_created_by_user_id_fk": {
+ "name": "calendar_custom_fields_created_by_user_id_fk",
+ "tableFrom": "calendar_custom_fields",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_feed_tokens": {
+ "name": "calendar_feed_tokens",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "calendar_feed_tokens_token_unique": {
+ "name": "calendar_feed_tokens_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "calendar_feed_tokens_calendarId_userId_idx": {
+ "name": "calendar_feed_tokens_calendarId_userId_idx",
+ "columns": [
+ "calendar_id",
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_feed_tokens_calendar_id_calendars_id_fk": {
+ "name": "calendar_feed_tokens_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_feed_tokens",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_feed_tokens_user_id_user_id_fk": {
+ "name": "calendar_feed_tokens_user_id_user_id_fk",
+ "tableFrom": "calendar_feed_tokens",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_notes": {
+ "name": "calendar_notes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'note'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recurring_pattern": {
+ "name": "recurring_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'none'"
+ },
+ "recurring_interval": {
+ "name": "recurring_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "calendar_notes_calendar_id_calendars_id_fk": {
+ "name": "calendar_notes_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_notes_created_by_user_id_fk": {
+ "name": "calendar_notes_created_by_user_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_permission_bundles": {
+ "name": "calendar_permission_bundles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "seed_key": {
+ "name": "seed_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_permission_bundles_calendarId_idx": {
+ "name": "calendar_permission_bundles_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_permission_bundles_calendarId_seedKey_idx": {
+ "name": "calendar_permission_bundles_calendarId_seedKey_idx",
+ "columns": [
+ "calendar_id",
+ "seed_key"
+ ],
+ "isUnique": true,
+ "where": "\"calendar_permission_bundles\".\"seed_key\" is not null"
+ }
+ },
+ "foreignKeys": {
+ "calendar_permission_bundles_calendar_id_calendars_id_fk": {
+ "name": "calendar_permission_bundles_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_permission_bundles",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_shares": {
+ "name": "calendar_shares",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bundle_id": {
+ "name": "bundle_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shared_by": {
+ "name": "shared_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_shares_calendarId_idx": {
+ "name": "calendar_shares_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_shares_userId_idx": {
+ "name": "calendar_shares_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_shares_bundleId_idx": {
+ "name": "calendar_shares_bundleId_idx",
+ "columns": [
+ "bundle_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_shares_calendar_id_calendars_id_fk": {
+ "name": "calendar_shares_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_user_id_user_id_fk": {
+ "name": "calendar_shares_user_id_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_bundle_id_calendar_permission_bundles_id_fk": {
+ "name": "calendar_shares_bundle_id_calendar_permission_bundles_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "calendar_permission_bundles",
+ "columnsFrom": [
+ "bundle_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_shared_by_user_id_fk": {
+ "name": "calendar_shares_shared_by_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "shared_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendars": {
+ "name": "calendars",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "guest_bundle_id": {
+ "name": "guest_bundle_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "signups_enabled": {
+ "name": "signups_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "split_shifts_enabled": {
+ "name": "split_shifts_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "view_settings": {
+ "name": "view_settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendars_ownerId_idx": {
+ "name": "calendars_ownerId_idx",
+ "columns": [
+ "owner_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendars_owner_id_user_id_fk": {
+ "name": "calendars_owner_id_user_id_fk",
+ "tableFrom": "calendars",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_syncs": {
+ "name": "external_syncs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'icloud'"
+ },
+ "calendar_url": {
+ "name": "calendar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "display_mode": {
+ "name": "display_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "is_hidden": {
+ "name": "is_hidden",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "auto_sync_interval": {
+ "name": "auto_sync_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_one_time_import": {
+ "name": "is_one_time_import",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "external_syncs_calendar_id_calendars_id_fk": {
+ "name": "external_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "external_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "preset_custom_field_values": {
+ "name": "preset_custom_field_values",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "preset_custom_field_values_presetId_idx": {
+ "name": "preset_custom_field_values_presetId_idx",
+ "columns": [
+ "preset_id"
+ ],
+ "isUnique": false
+ },
+ "preset_custom_field_values_presetId_fieldId_idx": {
+ "name": "preset_custom_field_values_presetId_fieldId_idx",
+ "columns": [
+ "preset_id",
+ "field_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "preset_custom_field_values_preset_id_shift_presets_id_fk": {
+ "name": "preset_custom_field_values_preset_id_shift_presets_id_fk",
+ "tableFrom": "preset_custom_field_values",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "preset_custom_field_values_field_id_calendar_custom_fields_id_fk": {
+ "name": "preset_custom_field_values_field_id_calendar_custom_fields_id_fk",
+ "tableFrom": "preset_custom_field_values",
+ "tableTo": "calendar_custom_fields",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "preset_time_segments": {
+ "name": "preset_time_segments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "preset_time_segments_presetId_idx": {
+ "name": "preset_time_segments_presetId_idx",
+ "columns": [
+ "preset_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "preset_time_segments_preset_id_shift_presets_id_fk": {
+ "name": "preset_time_segments_preset_id_shift_presets_id_fk",
+ "tableFrom": "preset_time_segments",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_custom_field_values": {
+ "name": "shift_custom_field_values",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shift_id": {
+ "name": "shift_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "shift_custom_field_values_shiftId_idx": {
+ "name": "shift_custom_field_values_shiftId_idx",
+ "columns": [
+ "shift_id"
+ ],
+ "isUnique": false
+ },
+ "shift_custom_field_values_shiftId_fieldId_idx": {
+ "name": "shift_custom_field_values_shiftId_fieldId_idx",
+ "columns": [
+ "shift_id",
+ "field_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "shift_custom_field_values_shift_id_shifts_id_fk": {
+ "name": "shift_custom_field_values_shift_id_shifts_id_fk",
+ "tableFrom": "shift_custom_field_values",
+ "tableTo": "shifts",
+ "columnsFrom": [
+ "shift_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_custom_field_values_field_id_calendar_custom_fields_id_fk": {
+ "name": "shift_custom_field_values_field_id_calendar_custom_fields_id_fk",
+ "tableFrom": "shift_custom_field_values",
+ "tableTo": "calendar_custom_fields",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_presets": {
+ "name": "shift_presets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_name": {
+ "name": "group_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "default_signup_capacity": {
+ "name": "default_signup_capacity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shift_presets_calendar_id_calendars_id_fk": {
+ "name": "shift_presets_calendar_id_calendars_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_presets_created_by_user_id_fk": {
+ "name": "shift_presets_created_by_user_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_signups": {
+ "name": "shift_signups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shift_id": {
+ "name": "shift_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signed_up_by": {
+ "name": "signed_up_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "shift_signups_shiftId_idx": {
+ "name": "shift_signups_shiftId_idx",
+ "columns": [
+ "shift_id"
+ ],
+ "isUnique": false
+ },
+ "shift_signups_userId_idx": {
+ "name": "shift_signups_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "shift_signups_shiftId_userId_idx": {
+ "name": "shift_signups_shiftId_userId_idx",
+ "columns": [
+ "shift_id",
+ "user_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "shift_signups_shift_id_shifts_id_fk": {
+ "name": "shift_signups_shift_id_shifts_id_fk",
+ "tableFrom": "shift_signups",
+ "tableTo": "shifts",
+ "columnsFrom": [
+ "shift_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_signups_user_id_user_id_fk": {
+ "name": "shift_signups_user_id_user_id_fk",
+ "tableFrom": "shift_signups",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shift_signups_signed_up_by_user_id_fk": {
+ "name": "shift_signups_signed_up_by_user_id_fk",
+ "tableFrom": "shift_signups",
+ "tableTo": "user",
+ "columnsFrom": [
+ "signed_up_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_time_segments": {
+ "name": "shift_time_segments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "shift_id": {
+ "name": "shift_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "shift_time_segments_shiftId_idx": {
+ "name": "shift_time_segments_shiftId_idx",
+ "columns": [
+ "shift_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shift_time_segments_shift_id_shifts_id_fk": {
+ "name": "shift_time_segments_shift_id_shifts_id_fk",
+ "tableFrom": "shift_time_segments",
+ "tableTo": "shifts",
+ "columnsFrom": [
+ "shift_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shifts": {
+ "name": "shifts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "signup_capacity": {
+ "name": "signup_capacity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_event_id": {
+ "name": "external_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "synced_from_external": {
+ "name": "synced_from_external",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shifts_calendar_id_calendars_id_fk": {
+ "name": "shifts_calendar_id_calendars_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_preset_id_shift_presets_id_fk": {
+ "name": "shifts_preset_id_shift_presets_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "shifts_external_sync_id_external_syncs_id_fk": {
+ "name": "shifts_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_created_by_user_id_fk": {
+ "name": "shifts_created_by_user_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sync_logs": {
+ "name": "sync_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_name": {
+ "name": "external_sync_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shifts_created": {
+ "name": "shifts_created",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_updated": {
+ "name": "shifts_updated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_deleted": {
+ "name": "shifts_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "is_read": {
+ "name": "is_read",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "synced_at": {
+ "name": "synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sync_logs_calendar_id_calendars_id_fk": {
+ "name": "sync_logs_calendar_id_calendars_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_logs_external_sync_id_external_syncs_id_fk": {
+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "system_settings": {
+ "name": "system_settings",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'default'"
+ },
+ "update_check_enabled": {
+ "name": "update_check_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "update_banner_visibility": {
+ "name": "update_banner_visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'all'"
+ },
+ "allow_guest_access": {
+ "name": "allow_guest_access",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telemetry_enabled": {
+ "name": "telemetry_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telemetry_instance_id": {
+ "name": "telemetry_instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telemetry_consented_schema": {
+ "name": "telemetry_consented_schema",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telemetry_decided_at": {
+ "name": "telemetry_decided_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telemetry_last_sent_at": {
+ "name": "telemetry_last_sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "must_change_password": {
+ "name": "must_change_password",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_calendar_subscriptions": {
+ "name": "user_calendar_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'subscribed'"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'guest'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_calendar_subscriptions_userId_idx": {
+ "name": "user_calendar_subscriptions_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_calendarId_idx": {
+ "name": "user_calendar_subscriptions_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_status_idx": {
+ "name": "user_calendar_subscriptions_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "user_calendar_subscriptions_user_id_user_id_fk": {
+ "name": "user_calendar_subscriptions_user_id_user_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {
+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_preferences": {
+ "name": "user_preferences",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "view_settings": {
+ "name": "view_settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_preferences_user_id_user_id_fk": {
+ "name": "user_preferences_user_id_user_id_fk",
+ "tableFrom": "user_preferences",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verification": {
+ "name": "verification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index f915231..533735c 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -225,6 +225,13 @@
"when": 1790012837841,
"tag": "0031_tearful_mac_gargan",
"breakpoints": true
+ },
+ {
+ "idx": 32,
+ "version": "6",
+ "when": 1790165253212,
+ "tag": "0032_heavy_wolfsbane",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/hooks/useCalendarFeedToken.ts b/hooks/useCalendarFeedToken.ts
new file mode 100644
index 0000000..a54348f
--- /dev/null
+++ b/hooks/useCalendarFeedToken.ts
@@ -0,0 +1,93 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { queryKeys } from "@/lib/query-keys";
+import { ApiError } from "@/lib/api-error";
+import { isRateLimitError, handleRateLimitError } from "@/lib/rate-limit-client";
+
+export interface CalendarFeed {
+ token: string | null;
+ createdAt: string | null;
+ lastUsedAt: string | null;
+}
+
+const EMPTY_FEED: CalendarFeed = { token: null, createdAt: null, lastUsedAt: null };
+
+/** Marker so mutation `onError` handlers can skip the generic toast — `handleRateLimitError` already showed one. */
+class RateLimitedError extends Error {}
+
+async function fetchFeed(calendarId: string): Promise<CalendarFeed> {
+ const response = await fetch(`/api/calendars/${calendarId}/feed-token`);
+ if (!response.ok) throw new ApiError(`HTTP ${response.status}`, response.status);
+ return response.json();
+}
+
+export function useCalendarFeedToken(calendarId: string, enabled: boolean) {
+ const t = useTranslations();
+ const queryClient = useQueryClient();
+ const key = queryKeys.feedToken.byCalendar(calendarId);
+
+ const { data: feed = EMPTY_FEED, isLoading, isError } = useQuery({
+ queryKey: key,
+ queryFn: () => fetchFeed(calendarId),
+ enabled,
+ });
+
+ const run = async (method: "POST" | "DELETE"): Promise<CalendarFeed> => {
+ const response = await fetch(`/api/calendars/${calendarId}/feed-token`, { method });
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ throw new RateLimitedError();
+ }
+ if (!response.ok) throw new ApiError(`HTTP ${response.status}`, response.status);
+ return method === "POST" ? response.json() : EMPTY_FEED;
+ };
+
+ const createMutation = useMutation({
+ mutationFn: () => run("POST"),
+ onSuccess: (data) => {
+ queryClient.setQueryData(key, data);
+ toast.success(t("export.feed.created"));
+ },
+ onError: (error) => {
+ if (error instanceof RateLimitedError) return;
+ toast.error(t("common.error"));
+ },
+ });
+
+ const revokeMutation = useMutation({
+ mutationFn: () => run("DELETE"),
+ onMutate: async () => {
+ await queryClient.cancelQueries({ queryKey: key });
+ const previous = queryClient.getQueryData<CalendarFeed>(key);
+ queryClient.setQueryData(key, EMPTY_FEED);
+ return { previous };
+ },
+ onError: (error, _vars, context) => {
+ queryClient.setQueryData(key, context?.previous);
+ if (error instanceof RateLimitedError) return;
+ toast.error(t("common.error"));
+ },
+ onSuccess: () => {
+ toast.success(t("export.feed.revoked"));
+ },
+ onSettled: () => queryClient.invalidateQueries({ queryKey: key }),
+ });
+
+ const feedUrl =
+ feed.token && typeof window !== "undefined"
+ ? `${window.location.origin}/api/feed/${feed.token}.ics`
+ : null;
+
+ return {
+ feed,
+ feedUrl,
+ isLoading,
+ isError,
+ isMutating: createMutation.isPending || revokeMutation.isPending,
+ createFeed: async () => !!(await createMutation.mutateAsync().catch(() => null)),
+ revokeFeed: async () => !!(await revokeMutation.mutateAsync().catch(() => null)),
+ };
+}
diff --git a/lib/audit-log.ts b/lib/audit-log.ts
index 66eb31f..960f519 100644
--- a/lib/audit-log.ts
+++ b/lib/audit-log.ts
@@ -114,6 +114,11 @@ export interface CalendarTokenCreatedMetadata {
expiresAt: string | null;
}
+export interface CalendarFeedTokenMetadata {
+ calendarName: string;
+ rotated?: boolean;
+}
+
export interface SyncCreatedMetadata {
calendarName: string;
syncUrl: string;
@@ -280,6 +285,7 @@ export type AuditLogMetadata =
| CalendarPermissionChangedMetadata
| CalendarGuestBundleChangedMetadata
| CalendarTokenCreatedMetadata
+ | CalendarFeedTokenMetadata
| SyncCreatedMetadata
| SyncDeletedMetadata
| SyncExecutedMetadata
diff --git a/lib/auth/permissions.ts b/lib/auth/permissions.ts
index b34f7bc..e545176 100644
--- a/lib/auth/permissions.ts
+++ b/lib/auth/permissions.ts
@@ -64,6 +64,11 @@ function bundleAccess(
};
}
+export interface AccessOptions {
+ /** Skip the requester's share-link cookie, for callers acting as someone else (calendar feeds). */
+ ignoreTokenCookie?: boolean;
+}
+
/**
* Resolves what a caller may do on a calendar: owner (everything), or the
* capability set of whichever bundle they hold (share > token > guest bundle
@@ -72,7 +77,8 @@ function bundleAccess(
*/
async function resolveCalendarAccess(
userId: string | null | undefined,
- calendarId: string
+ calendarId: string,
+ options: AccessOptions = {}
): Promise<ResolvedCalendarAccess | null> {
// guestBundle fetched alongside the calendar (one hop via the relation)
// since almost every branch below may need it.
@@ -94,7 +100,7 @@ async function resolveCalendarAccess(
const guestBundle = calendar.guestBundle ? sanitizeBundle(calendar.guestBundle) : null;
if (!userId) {
- const tokenBundleId = await getTokenBundleId(calendarId);
+ const tokenBundleId = options.ignoreTokenCookie ? null : await getTokenBundleId(calendarId);
if (tokenBundleId) {
const bundle = await getBundleById(tokenBundleId);
if (bundle) return bundleAccess(calendar, "token", bundle);
@@ -121,7 +127,7 @@ async function resolveCalendarAccess(
return bundleAccess(calendar, "share", sanitizeBundle(share.bundle));
}
- const tokenBundleId = await getTokenBundleId(calendarId);
+ const tokenBundleId = options.ignoreTokenCookie ? null : await getTokenBundleId(calendarId);
if (tokenBundleId) {
const bundle = await getBundleById(tokenBundleId);
if (bundle) return bundleAccess(calendar, "token", bundle);
@@ -183,9 +189,10 @@ function ceilingFilteredCapabilities(access: ResolvedCalendarAccess): Capability
*/
export async function getCalendarAccess(
userId: string | null | undefined,
- calendarId: string
+ calendarId: string,
+ options?: AccessOptions
): Promise<CalendarAccess | null> {
- const access = await resolveCalendarAccess(userId, calendarId);
+ const access = await resolveCalendarAccess(userId, calendarId, options);
if (!access) return null;
const effective = ceilingFilteredCapabilities(access);
@@ -242,9 +249,10 @@ export async function getEffectiveAccessSummary(
export async function hasCapability(
userId: string | null | undefined,
calendarId: string,
- capability: Capability
+ capability: Capability,
+ options?: AccessOptions
): Promise<boolean> {
- const access = await getCalendarAccess(userId, calendarId);
+ const access = await getCalendarAccess(userId, calendarId, options);
return access ? access.can(capability) : false;
}
diff --git a/lib/calendar-feed.ts b/lib/calendar-feed.ts
new file mode 100644
index 0000000..b915d86
--- /dev/null
+++ b/lib/calendar-feed.ts
@@ -0,0 +1,38 @@
+import { and, eq, isNull } from "drizzle-orm";
+import { db } from "@/lib/db";
+import { calendarFeedTokens, user, type CalendarFeedToken } from "@/lib/db/schema";
+import { hasCapability } from "@/lib/auth/permissions";
+import { isAuthEnabled } from "@/lib/auth/feature-flags";
+
+export function feedOwnerCondition(userId: string | null) {
+ return userId ? eq(calendarFeedTokens.userId, userId) : isNull(calendarFeedTokens.userId);
+}
+
+export async function getFeedToken(
+ userId: string | null,
+ calendarId: string
+): Promise<CalendarFeedToken | null> {
+ const row = await db.query.calendarFeedTokens.findFirst({
+ where: and(eq(calendarFeedTokens.calendarId, calendarId), feedOwnerCondition(userId)),
+ });
+ return row ?? null;
+}
+
+export async function findFeedToken(token: string): Promise<CalendarFeedToken | null> {
+ const row = await db.query.calendarFeedTokens.findFirst({
+ where: eq(calendarFeedTokens.token, token),
+ });
+ return row ?? null;
+}
+
+// Feeds carry no session, so the owner's ban and share-link cookies must be handled here.
+export async function canReadFeed(userId: string | null, calendarId: string): Promise<boolean> {
+ if (!userId) return !isAuthEnabled();
+ const owner = await db.query.user.findFirst({
+ where: eq(user.id, userId),
+ columns: { banned: true, banExpires: true },
+ });
+ // Same rule as better-auth's admin plugin: an expired ban no longer counts.
+ if (owner?.banned && (!owner.banExpires || owner.banExpires.getTime() > Date.now())) return false;
+ return hasCapability(userId, calendarId, "viewShifts", { ignoreTokenCookie: true });
+}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 19c8f1f..79ec763 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -687,6 +687,31 @@ export const calendarAccessTokens = sqliteTable(
]
);
+export const calendarFeedTokens = sqliteTable(
+ "calendar_feed_tokens",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ // null only while AUTH_ENABLED=false, where there are no accounts
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
+ token: text("token").notNull().unique(),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
+ },
+ (table) => [
+ index("calendar_feed_tokens_calendarId_userId_idx").on(
+ table.calendarId,
+ table.userId
+ ),
+ ]
+);
+
export const shiftSignups = sqliteTable(
"shift_signups",
{
@@ -724,6 +749,8 @@ export type NewCalendar = typeof calendars.$inferInsert;
export type CalendarAccessToken = typeof calendarAccessTokens.$inferSelect;
export type NewCalendarAccessToken = typeof calendarAccessTokens.$inferInsert;
+export type CalendarFeedToken = typeof calendarFeedTokens.$inferSelect;
+
export type CalendarPermissionBundle =
typeof calendarPermissionBundles.$inferSelect;
export type NewCalendarPermissionBundle =
@@ -774,6 +801,7 @@ export const userRelations = relations(user, ({ one, many }) => ({
ownedCalendars: many(calendars),
calendarShares: many(calendarShares),
calendarSubscriptions: many(userCalendarSubscriptions),
+ feedTokens: many(calendarFeedTokens),
auditLogs: many(auditLogs),
}));
@@ -799,6 +827,7 @@ export const calendarsRelations = relations(calendars, ({ one, many }) => ({
shares: many(calendarShares),
subscriptions: many(userCalendarSubscriptions),
accessTokens: many(calendarAccessTokens),
+ feedTokens: many(calendarFeedTokens),
permissionBundles: many(calendarPermissionBundles),
guestBundle: one(calendarPermissionBundles, {
fields: [calendars.guestBundleId],
@@ -972,3 +1001,17 @@ export const calendarAccessTokensRelations = relations(
}),
})
);
+
+export const calendarFeedTokensRelations = relations(
+ calendarFeedTokens,
+ ({ one }) => ({
+ calendar: one(calendars, {
+ fields: [calendarFeedTokens.calendarId],
+ references: [calendars.id],
+ }),
+ user: one(user, {
+ fields: [calendarFeedTokens.userId],
+ references: [user.id],
+ }),
+ })
+);
diff --git a/lib/ics.ts b/lib/ics.ts
new file mode 100644
index 0000000..e9e39da
--- /dev/null
+++ b/lib/ics.ts
@@ -0,0 +1,158 @@
+import ICAL from "ical.js";
+import { inArray } from "drizzle-orm";
+import { db } from "@/lib/db";
+import { shifts, type Calendar } from "@/lib/db/schema";
+import { getServerTimezone, formatDateToLocal } from "@/lib/date-utils";
+import { toTimeRanges } from "@/lib/time-ranges";
+import { getCalendarCustomFields, withShiftCustomFields } from "@/lib/shift-custom-fields";
+import { formatValueForDisplay } from "@/lib/custom-fields";
+
+export type IcsCalendar = Pick<Calendar, "id" | "name" | "splitShiftsEnabled">;
+
+export async function buildIcsCalendar({
+ calendars,
+ locale,
+ feed = false,
+}: {
+ calendars: IcsCalendar[];
+ locale: string;
+ feed?: boolean;
+}): Promise<string> {
+ // Get all shifts for accessible calendars
+ let allShifts = await db.query.shifts.findMany({
+ where: inArray(
+ shifts.calendarId,
+ calendars.map((c) => c.id)
+ ),
+ orderBy: (shifts, { asc }) => [asc(shifts.date)],
+ with: { segments: true },
+ });
+
+ // A calendar that has since turned split shifts off must fall back to
+ // showing only its shifts' primary ranges, without deleting the stored segments.
+ const splitShiftsEnabledIds = new Set(
+ calendars.filter((c) => c.splitShiftsEnabled).map((c) => c.id)
+ );
+ allShifts = allShifts.map((shift) =>
+ splitShiftsEnabledIds.has(shift.calendarId) ? shift : { ...shift, segments: [] }
+ );
+
+ // Create calendar name lookup
+ const calendarMap = new Map(calendars.map((c) => [c.id, c.name]));
+
+ // Field keys are per calendar, so definitions and values must be resolved calendar by calendar.
+ const definitionsByCalendar = new Map(
+ await Promise.all(
+ calendars.map(
+ async (c) => [c.id, await getCalendarCustomFields(c.id)] as const
+ )
+ )
+ );
+ const customFieldsByShiftId = new Map<string, Record<string, string | number | boolean | null>>();
+ for (const c of calendars) {
+ const definitions = definitionsByCalendar.get(c.id) ?? [];
+ const calendarShifts = allShifts.filter((s) => s.calendarId === c.id);
+ const withFields = await withShiftCustomFields(calendarShifts, definitions);
+ for (const s of withFields) {
+ customFieldsByShiftId.set(s.id, s.customFields);
+ }
+ }
+
+ // Get server timezone for proper time conversion
+ const serverTimezone = getServerTimezone();
+
+ // Determine if multi-calendar export
+ const isMultiCalendar = calendars.length > 1;
+
+ // Create iCalendar
+ const cal = new ICAL.Component(["vcalendar", [], []]);
+ cal.updatePropertyWithValue(
+ "prodid",
+ "-//BetterShift//Calendar Export//EN"
+ );
+ cal.updatePropertyWithValue("version", "2.0");
+ cal.updatePropertyWithValue("calscale", "GREGORIAN");
+ cal.updatePropertyWithValue("method", "PUBLISH");
+ cal.updatePropertyWithValue(
+ "x-wr-calname",
+ isMultiCalendar
+ ? "BetterShift Multi-Calendar"
+ : calendars[0].name
+ );
+ cal.updatePropertyWithValue("x-wr-timezone", serverTimezone);
+
+ if (feed) {
+ // Hints only; clients poll on their own schedule (Google: several hours).
+ cal.updatePropertyWithValue("refresh-interval", ICAL.Duration.fromString("PT1H"));
+ cal.updatePropertyWithValue("x-published-ttl", "PT1H");
+ }
+
+ // Add shifts as events
+ for (const shift of allShifts) {
+ const shiftDate = shift.date as Date;
+ const calendarName = calendarMap.get(shift.calendarId);
+ const summary = isMultiCalendar
+ ? `[${calendarName}] ${shift.title}`
+ : shift.title;
+
+ const ranges = shift.isAllDay ? [null] : toTimeRanges(shift);
+
+ const definitions = definitionsByCalendar.get(shift.calendarId) ?? [];
+ const customFields = customFieldsByShiftId.get(shift.id) ?? {};
+ const fieldLines = definitions
+ .map((d) => {
+ const raw = customFields[d.key];
+ if (raw === null || raw === undefined || raw === "") return null;
+ return `${d.label}: ${formatValueForDisplay(d, String(raw), locale)}`;
+ })
+ .filter((line): line is string => line !== null);
+ const description = [shift.notes, ...fieldLines].filter(Boolean).join("\n");
+
+ ranges.forEach((range, index) => {
+ const vevent = new ICAL.Component("vevent");
+ const event = new ICAL.Event(vevent);
+
+ event.uid = index === 0 ? shift.id : `${shift.id}-seg-${index}`;
+ event.summary = summary;
+ if (description) {
+ event.description = description;
+ }
+
+ if (!range) {
+ // All-day event (DTEND is exclusive per RFC 5545)
+ const dateStr = formatDateToLocal(shiftDate);
+ event.startDate = ICAL.Time.fromDateString(dateStr);
+
+ const endDate = new Date(shiftDate);
+ endDate.setDate(endDate.getDate() + 1);
+ const endYear = endDate.getFullYear();
+ const endMonth = String(endDate.getMonth() + 1).padStart(2, "0");
+ const endDay = String(endDate.getDate()).padStart(2, "0");
+ event.endDate = ICAL.Time.fromDateString(`${endYear}-${endMonth}-${endDay}`);
+ } else {
+ const [startHour, startMinute] = range.startTime.split(":").map(Number);
+ const [endHour, endMinute] = range.endTime.split(":").map(Number);
+
+ const startDateTime = new Date(shiftDate);
+ startDateTime.setHours(startHour, startMinute, 0, 0);
+
+ const endDateTime = new Date(shiftDate);
+ endDateTime.setHours(endHour, endMinute, 0, 0);
+
+ if (endDateTime <= startDateTime) {
+ endDateTime.setDate(endDateTime.getDate() + 1);
+ }
+
+ event.startDate = ICAL.Time.fromJSDate(startDateTime, true);
+ event.endDate = ICAL.Time.fromJSDate(endDateTime, true);
+ }
+
+ vevent.addPropertyWithValue("color", shift.color);
+ vevent.addPropertyWithValue("x-apple-calendar-color", shift.color);
+
+ cal.addSubcomponent(vevent);
+ });
+ }
+
+ return cal.toString();
+}
diff --git a/lib/query-keys.ts b/lib/query-keys.ts
index d545dc9..e67865f 100644
--- a/lib/query-keys.ts
+++ b/lib/query-keys.ts
@@ -81,6 +81,9 @@ export const queryKeys = {
tokens: {
byCalendar: (calendarId: string) => ["tokens", calendarId] as const,
},
+ feedToken: {
+ byCalendar: (calendarId: string) => ["feed-token", calendarId] as const,
+ },
permissionBundles: {
byCalendar: (calendarId: string) =>
["permission-bundles", calendarId] as const,
diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.ts
index e1dec5f..f68419b 100644
--- a/lib/rate-limiter.ts
+++ b/lib/rate-limiter.ts
@@ -115,6 +115,11 @@ const config = {
windowMs:
parseInt(process.env.RATE_LIMIT_EXPORT_ICS_WINDOW || "600", 10) * 1000, // 10 minutes
},
+ calendarFeed: {
+ requests: parseInt(process.env.RATE_LIMIT_CALENDAR_FEED_REQUESTS || "60", 10),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_CALENDAR_FEED_WINDOW || "600", 10) * 1000, // 10 minutes
+ },
tokenValidation: {
requests: parseInt(
process.env.RATE_LIMIT_TOKEN_VALIDATION_REQUESTS || "10",
@@ -250,6 +255,7 @@ const limitsByType = {
"external-sync": config.externalSync,
"export-pdf": config.exportPdf,
"export-ics": config.exportIcs,
+ "calendar-feed": config.calendarFeed,
"token-validation": config.tokenValidation,
"token-creation": config.tokenCreation,
"user-search": config.userSearch,
@@ -474,6 +480,8 @@ export function rateLimit(
resourceId
) {
identifier = `calendar:${resourceId}`;
+ } else if (type === "calendar-feed" && resourceId) {
+ identifier = `feed:${resourceId}`;
} else {
identifier = getClientIdentifier(req, userId);
}
diff --git a/messages/cs.json b/messages/cs.json
index 8392b5c..2001054 100644
--- a/messages/cs.json
+++ b/messages/cs.json
@@ -364,7 +364,26 @@
"multiCalendar": "Exportovat více kalendářů",
"multiCalendarHint": "Zkombinujte směny z více kalendářů do jednoho souboru exportu",
"selectedCount": "{count, plural, =0 {Nevybrány žádné kalendáře} =1 {Vybrán 1 kalendář} few {Vybrány # kalendáře} other {Vybráno # kalendářů}}",
- "selectAtLeastOne": "Vyberte prosím alespoň jeden kalendář"
+ "selectAtLeastOne": "Vyberte prosím alespoň jeden kalendář",
+ "feed": {
+ "title": "Odběrový odkaz",
+ "hint": "Tajný odkaz pro odběr v kalendářových aplikacích",
+ "empty": "Vytvořte odkaz pro odběr tohoto kalendáře v Google Kalendáři, Apple Kalendáři, Outlooku nebo Home Assistant.",
+ "create": "Vytvořit odkaz",
+ "created": "Odběrový odkaz vytvořen",
+ "copy": "Kopírovat odkaz",
+ "copied": "Odběrový odkaz zkopírován",
+ "lastUsed": "Naposledy načteno: {date}",
+ "neverUsed": "Zatím nenačteno",
+ "rotate": "Vygenerovat nový",
+ "rotateConfirm": "Vygenerovat nový odběrový odkaz?",
+ "rotateConfirmDescription": "Starý odkaz poté přestane fungovat. Odebírající kalendářové aplikace musí dostat nový odkaz.",
+ "revoke": "Odvolat",
+ "revokeConfirm": "Odvolat odběrový odkaz?",
+ "revokeConfirmDescription": "Odebírající kalendářové aplikace pak už nebudou dostávat směny z tohoto kalendáře.",
+ "revoked": "Odběrový odkaz odvolán",
+ "securityNote": "Kdokoli s tímto odkazem může číst směny tohoto kalendáře. Google Kalendář aktualizuje odběry jen jednou za pár hodin."
+ }
},
"update": {
"newVersion": "Je dostupná verze {version}",
@@ -866,7 +885,7 @@
"permissions": "Oprávnění",
"permissionsHint": "{count, plural, =0 {Skupiny, přiřazení, odkazy} one {Skupiny, přiřazení, # aktivní odkaz} few {Skupiny, přiřazení, # aktivní odkazy} other {Skupiny, přiřazení, # aktivních odkazů}}",
"export": "Export",
- "exportHint": "Soubor ICS nebo PDF",
+ "exportHint": "Soubor ICS, PDF nebo odběrový odkaz",
"view": "Zobrazení kalendáře",
"viewHint": "Vlastní zobrazení, hustota, řazení",
"notifications": "Oznámení",
diff --git a/messages/de.json b/messages/de.json
index b2cb2e0..5535dfb 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -364,7 +364,26 @@
"multiCalendar": "Mehrere Kalender exportieren",
"multiCalendarHint": "Schichten aus mehreren Kalendern in einer Export-Datei kombinieren",
"selectedCount": "{count, plural, =0 {Keine Kalender ausgewählt} =1 {1 Kalender ausgewählt} other {# Kalender ausgewählt}}",
- "selectAtLeastOne": "Bitte wähle mindestens einen Kalender aus"
+ "selectAtLeastOne": "Bitte wähle mindestens einen Kalender aus",
+ "feed": {
+ "title": "Abo-Link",
+ "hint": "Geheimer Link zum Abonnieren in Kalender-Apps",
+ "empty": "Erstelle einen Link, um diesen Kalender in Google Kalender, Apple Kalender, Outlook oder Home Assistant zu abonnieren.",
+ "create": "Link erstellen",
+ "created": "Abo-Link erstellt",
+ "copy": "Link kopieren",
+ "copied": "Abo-Link kopiert",
+ "lastUsed": "Zuletzt abgerufen: {date}",
+ "neverUsed": "Noch nicht abgerufen",
+ "rotate": "Neu erzeugen",
+ "rotateConfirm": "Abo-Link neu erzeugen?",
+ "rotateConfirmDescription": "Der bisherige Link funktioniert danach nicht mehr. Abonnierte Kalender-Apps müssen den neuen Link erhalten.",
+ "revoke": "Widerrufen",
+ "revokeConfirm": "Abo-Link widerrufen?",
+ "revokeConfirmDescription": "Abonnierte Kalender-Apps erhalten danach keine Schichten mehr aus diesem Kalender.",
+ "revoked": "Abo-Link widerrufen",
+ "securityNote": "Jeder mit diesem Link kann die Schichten dieses Kalenders lesen. Google Kalender aktualisiert Abos nur alle paar Stunden."
+ }
},
"update": {
"newVersion": "Version {version} ist verfügbar",
@@ -866,7 +885,7 @@
"permissions": "Berechtigungen",
"permissionsHint": "{count, plural, =0 {Gruppen, Zuweisungen, Links} one {Gruppen, Zuweisungen, # aktiver Link} other {Gruppen, Zuweisungen, # aktive Links}}",
"export": "Exportieren",
- "exportHint": "ICS-Datei oder PDF",
+ "exportHint": "ICS-Datei, PDF oder Abo-Link",
"view": "Kalenderansicht",
"viewHint": "Eigene Ansicht, Dichte, Sortierung",
"notifications": "Benachrichtigungen",
diff --git a/messages/en.json b/messages/en.json
index f633c1d..a78dfee 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -364,7 +364,26 @@
"multiCalendar": "Export multiple calendars",
"multiCalendarHint": "Combine shifts from multiple calendars into one export file",
"selectedCount": "{count, plural, =0 {No calendars selected} =1 {1 calendar selected} other {# calendars selected}}",
- "selectAtLeastOne": "Please select at least one calendar"
+ "selectAtLeastOne": "Please select at least one calendar",
+ "feed": {
+ "title": "Subscription Link",
+ "hint": "Secret link to subscribe from calendar apps",
+ "empty": "Create a link to subscribe to this calendar in Google Calendar, Apple Calendar, Outlook or Home Assistant.",
+ "create": "Create Link",
+ "created": "Subscription link created",
+ "copy": "Copy link",
+ "copied": "Subscription link copied",
+ "lastUsed": "Last fetched: {date}",
+ "neverUsed": "Not fetched yet",
+ "rotate": "Regenerate",
+ "rotateConfirm": "Regenerate subscription link?",
+ "rotateConfirmDescription": "The old link will stop working. Subscribed calendar apps will need to receive the new link.",
+ "revoke": "Revoke",
+ "revokeConfirm": "Revoke subscription link?",
+ "revokeConfirmDescription": "Subscribed calendar apps will no longer receive shifts from this calendar.",
+ "revoked": "Subscription link revoked",
+ "securityNote": "Anyone with this link can read this calendar's shifts. Google Calendar only refreshes subscriptions every few hours."
+ }
},
"update": {
"newVersion": "Version {version} is available",
@@ -866,7 +885,7 @@
"permissions": "Permissions",
"permissionsHint": "{count, plural, =0 {Groups, assignments, links} one {Groups, assignments, # active link} other {Groups, assignments, # active links}}",
"export": "Export",
- "exportHint": "ICS file or PDF",
+ "exportHint": "ICS file, PDF or subscription link",
"view": "Calendar view",
"viewHint": "Own view, density, sorting",
"notifications": "Notifications",
diff --git a/messages/es.json b/messages/es.json
index 9f591bb..9699e98 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -364,7 +364,26 @@
"multiCalendar": "Exportar múltiples calendarios",
"multiCalendarHint": "Combina turnos de varios calendarios en un solo archivo",
"selectedCount": "{count, plural, =0 {Sin calendarios seleccionados} =1 {1 calendario seleccionado} other {# calendarios seleccionados}}",
- "selectAtLeastOne": "Por favor, selecciona al menos un calendario"
+ "selectAtLeastOne": "Por favor, selecciona al menos un calendario",
+ "feed": {
+ "title": "Enlace de suscripción",
+ "hint": "Enlace secreto para suscribirse desde apps de calendario",
+ "empty": "Crea un enlace para suscribirte a este calendario en Google Calendar, Apple Calendar, Outlook o Home Assistant.",
+ "create": "Crear enlace",
+ "created": "Enlace de suscripción creado",
+ "copy": "Copiar enlace",
+ "copied": "Enlace de suscripción copiado",
+ "lastUsed": "Última consulta: {date}",
+ "neverUsed": "Aún no consultado",
+ "rotate": "Regenerar",
+ "rotateConfirm": "¿Regenerar el enlace de suscripción?",
+ "rotateConfirmDescription": "El enlace anterior dejará de funcionar. Las apps de calendario suscritas necesitarán el nuevo enlace.",
+ "revoke": "Revocar",
+ "revokeConfirm": "¿Revocar el enlace de suscripción?",
+ "revokeConfirmDescription": "Las apps de calendario suscritas dejarán de recibir turnos de este calendario.",
+ "revoked": "Enlace de suscripción revocado",
+ "securityNote": "Cualquiera con este enlace puede leer los turnos de este calendario. Google Calendar solo actualiza las suscripciones cada pocas horas."
+ }
},
"update": {
"newVersion": "La versión {version} está disponible",
@@ -866,7 +885,7 @@
"permissions": "Permisos",
"permissionsHint": "{count, plural, =0 {Grupos, asignaciones, enlaces} one {Grupos, asignaciones, # enlace activo} other {Grupos, asignaciones, # enlaces activos}}",
"export": "Exportar",
- "exportHint": "Archivo ICS o PDF",
+ "exportHint": "Archivo ICS, PDF o enlace de suscripción",
"view": "Vista del calendario",
"viewHint": "Vista propia, densidad, orden",
"notifications": "Notificaciones",
diff --git a/messages/fr.json b/messages/fr.json
index 858d622..8482535 100755
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -364,7 +364,26 @@
"multiCalendar": "Exporter plusieurs calendriers",
"multiCalendarHint": "Combiner les créneaux de plusieurs calendriers dans un seul fichier d'export",
"selectedCount": "{count, plural, =0 {Aucun calendrier sélectionné} =1 {1 calendrier sélectionné} other {# calendriers sélectionnés}}",
- "selectAtLeastOne": "Veuillez sélectionner au moins un calendrier"
+ "selectAtLeastOne": "Veuillez sélectionner au moins un calendrier",
+ "feed": {
+ "title": "Lien d'abonnement",
+ "hint": "Lien secret pour s'abonner depuis des applications de calendrier",
+ "empty": "Créez un lien pour abonner ce calendrier dans Google Agenda, Calendrier Apple, Outlook ou Home Assistant.",
+ "create": "Créer le lien",
+ "created": "Lien d'abonnement créé",
+ "copy": "Copier le lien",
+ "copied": "Lien d'abonnement copié",
+ "lastUsed": "Dernière consultation : {date}",
+ "neverUsed": "Pas encore consulté",
+ "rotate": "Régénérer",
+ "rotateConfirm": "Régénérer le lien d'abonnement ?",
+ "rotateConfirmDescription": "L'ancien lien cessera de fonctionner. Les applications de calendrier abonnées devront recevoir le nouveau lien.",
+ "revoke": "Révoquer",
+ "revokeConfirm": "Révoquer le lien d'abonnement ?",
+ "revokeConfirmDescription": "Les applications de calendrier abonnées ne recevront plus les créneaux de ce calendrier.",
+ "revoked": "Lien d'abonnement révoqué",
+ "securityNote": "Toute personne disposant de ce lien peut lire les créneaux de ce calendrier. Google Agenda n'actualise les abonnements que toutes les quelques heures."
+ }
},
"update": {
"newVersion": "La version {version} est disponible",
@@ -866,7 +885,7 @@
"permissions": "Autorisations",
"permissionsHint": "{count, plural, =0 {Groupes, attributions, liens} one {Groupes, attributions, # lien actif} other {Groupes, attributions, # liens actifs}}",
"export": "Exporter",
- "exportHint": "Fichier ICS ou PDF",
+ "exportHint": "Fichier ICS, PDF ou lien d'abonnement",
"view": "Affichage du calendrier",
"viewHint": "Affichage propre, densité, tri",
"notifications": "Notifications",
diff --git a/messages/it.json b/messages/it.json
index a6b9d99..eec1f4a 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -364,7 +364,26 @@
"multiCalendar": "Esporta più calendari",
"multiCalendarHint": "Combina i turni da più calendari in un unico file di esportazione",
"selectedCount": "{count, plural, =0 {Nessun calendario selezionato} =1 {1 calendario selezionato} other {# calendari selezionati}}",
- "selectAtLeastOne": "Seleziona almeno un calendario"
+ "selectAtLeastOne": "Seleziona almeno un calendario",
+ "feed": {
+ "title": "Link di abbonamento",
+ "hint": "Link segreto per abbonarsi dalle app di calendario",
+ "empty": "Crea un link per abbonarti a questo calendario in Google Calendar, Calendario Apple, Outlook o Home Assistant.",
+ "create": "Crea link",
+ "created": "Link di abbonamento creato",
+ "copy": "Copia link",
+ "copied": "Link di abbonamento copiato",
+ "lastUsed": "Ultimo accesso: {date}",
+ "neverUsed": "Non ancora consultato",
+ "rotate": "Rigenera",
+ "rotateConfirm": "Rigenerare il link di abbonamento?",
+ "rotateConfirmDescription": "Il vecchio link smetterà di funzionare. Le app di calendario abbonate dovranno ricevere il nuovo link.",
+ "revoke": "Revoca",
+ "revokeConfirm": "Revocare il link di abbonamento?",
+ "revokeConfirmDescription": "Le app di calendario abbonate non riceveranno più i turni da questo calendario.",
+ "revoked": "Link di abbonamento revocato",
+ "securityNote": "Chiunque abbia questo link può leggere i turni di questo calendario. Google Calendar aggiorna gli abbonamenti solo ogni poche ore."
+ }
},
"update": {
"newVersion": "Versione {version} è disponibile",
@@ -866,7 +885,7 @@
"permissions": "Permessi",
"permissionsHint": "{count, plural, =0 {Gruppi, assegnazioni, link} one {Gruppi, assegnazioni, # link attivo} other {Gruppi, assegnazioni, # link attivi}}",
"export": "Esporta",
- "exportHint": "File ICS o PDF",
+ "exportHint": "File ICS, PDF o link di abbonamento",
"view": "Vista del calendario",
"viewHint": "Vista propria, densità, ordinamento",
"notifications": "Notifiche",
diff --git a/proxy.ts b/proxy.ts
index 4c32339..1415fe7 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -299,6 +299,7 @@ export async function proxy(request: NextRequest) {
"/api/releases", // Changelog/releases (always public)
"/api/announcements", // Instance announcements (shown on the logged-out auth pages)
"/api/health", // Health check endpoint
+ "/api/feed/", // Calendar feed subscriptions (secret token in the URL, no cookies)
"/manifest.json", // Browsers fetch the PWA manifest without cookies
];