fix: resolve cron calendar and auth regressions from open issues

This commit is contained in:
Nyk 2026-03-04 22:18:57 +07:00
parent 0e01f5d4b3
commit d1d75b3b15
9 changed files with 380 additions and 55 deletions

View File

@ -510,7 +510,12 @@ export function MemoryTab({
return ( return (
<div className="p-6 space-y-4"> <div className="p-6 space-y-4">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<h4 className="text-lg font-medium text-foreground">Working Memory</h4> <div>
<h4 className="text-lg font-medium text-foreground">Working Memory</h4>
<p className="text-xs text-muted-foreground mt-1">
Agent-level scratchpad only. Use the global Memory page to browse all workspace memory files.
</p>
</div>
<div className="flex gap-2"> <div className="flex gap-2">
{!editing && ( {!editing && (
<> <>

View File

@ -1,7 +1,8 @@
'use client' 'use client'
import { useState, useEffect, useCallback } from 'react' import { useState, useEffect, useCallback, useMemo } from 'react'
import { useMissionControl, CronJob } from '@/store' import { useMissionControl, CronJob } from '@/store'
import { buildDayKey, getCronOccurrences } from '@/lib/cron-occurrences'
interface NewJobForm { interface NewJobForm {
name: string name: string
@ -56,6 +57,7 @@ export function CronManagementPanel() {
const [availableModels, setAvailableModels] = useState<string[]>([]) const [availableModels, setAvailableModels] = useState<string[]>([])
const [calendarView, setCalendarView] = useState<CalendarViewMode>('week') const [calendarView, setCalendarView] = useState<CalendarViewMode>('week')
const [calendarDate, setCalendarDate] = useState<Date>(startOfDay(new Date())) const [calendarDate, setCalendarDate] = useState<Date>(startOfDay(new Date()))
const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date>(startOfDay(new Date()))
const [searchQuery, setSearchQuery] = useState('') const [searchQuery, setSearchQuery] = useState('')
const [agentFilter, setAgentFilter] = useState('all') const [agentFilter, setAgentFilter] = useState('all')
const [stateFilter, setStateFilter] = useState<'all' | 'enabled' | 'disabled'>('all') const [stateFilter, setStateFilter] = useState<'all' | 'enabled' | 'disabled'>('all')
@ -307,39 +309,69 @@ export function CronManagementPanel() {
return matchesQuery && matchesAgent && matchesState return matchesQuery && matchesAgent && matchesState
}) })
const agendaJobs = [...filteredJobs].sort((a, b) => {
const aRun = typeof a.nextRun === 'number' ? a.nextRun : Number.POSITIVE_INFINITY
const bRun = typeof b.nextRun === 'number' ? b.nextRun : Number.POSITIVE_INFINITY
return aRun - bRun
})
const dayStart = startOfDay(calendarDate) const dayStart = startOfDay(calendarDate)
const dayEnd = addDays(dayStart, 1) const dayEnd = addDays(dayStart, 1)
const dayJobs = filteredJobs
.filter((job) => typeof job.nextRun === 'number' && job.nextRun >= dayStart.getTime() && job.nextRun < dayEnd.getTime())
.sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
const weekStart = getWeekStart(calendarDate) const weekStart = getWeekStart(calendarDate)
const weekDays = Array.from({ length: 7 }, (_, idx) => addDays(weekStart, idx)) const weekDays = Array.from({ length: 7 }, (_, idx) => addDays(weekStart, idx))
const jobsByWeekDay = weekDays.map((date) => {
const start = startOfDay(date).getTime()
const end = addDays(date, 1).getTime()
const jobs = filteredJobs
.filter((job) => typeof job.nextRun === 'number' && job.nextRun >= start && job.nextRun < end)
.sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
return { date, jobs }
})
const monthGridStart = getMonthStartGrid(calendarDate) const monthGridStart = getMonthStartGrid(calendarDate)
const monthDays = Array.from({ length: 42 }, (_, idx) => addDays(monthGridStart, idx)) const monthDays = Array.from({ length: 42 }, (_, idx) => addDays(monthGridStart, idx))
const jobsByMonthDay = monthDays.map((date) => {
const start = startOfDay(date).getTime() const calendarBounds = useMemo(() => {
const end = addDays(date, 1).getTime() if (calendarView === 'day') {
const jobs = filteredJobs return { startMs: dayStart.getTime(), endMs: dayEnd.getTime() }
.filter((job) => typeof job.nextRun === 'number' && job.nextRun >= start && job.nextRun < end) }
.sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0)) if (calendarView === 'week') {
return { date, jobs } return { startMs: weekStart.getTime(), endMs: addDays(weekStart, 7).getTime() }
}) }
if (calendarView === 'month') {
return { startMs: monthGridStart.getTime(), endMs: addDays(monthGridStart, 42).getTime() }
}
const agendaStart = Date.now()
return { startMs: agendaStart, endMs: addDays(startOfDay(new Date()), 30).getTime() }
}, [calendarView, dayEnd, dayStart, monthGridStart, weekStart])
const calendarOccurrences = useMemo(() => {
const rows: Array<{ job: CronJob; atMs: number; dayKey: string }> = []
for (const job of filteredJobs) {
const occurrences = getCronOccurrences(job.schedule, calendarBounds.startMs, calendarBounds.endMs, 1000)
for (const occurrence of occurrences) {
rows.push({ job, atMs: occurrence.atMs, dayKey: occurrence.dayKey })
}
if (occurrences.length === 0 && typeof job.nextRun === 'number' && job.nextRun >= calendarBounds.startMs && job.nextRun < calendarBounds.endMs) {
rows.push({ job, atMs: job.nextRun, dayKey: buildDayKey(new Date(job.nextRun)) })
}
}
rows.sort((a, b) => a.atMs - b.atMs)
return rows
}, [calendarBounds.endMs, calendarBounds.startMs, filteredJobs])
const occurrencesByDay = useMemo(() => {
const dayMap = new Map<string, Array<{ job: CronJob; atMs: number }>>()
for (const row of calendarOccurrences) {
const existing = dayMap.get(row.dayKey) || []
existing.push({ job: row.job, atMs: row.atMs })
dayMap.set(row.dayKey, existing)
}
return dayMap
}, [calendarOccurrences])
const dayJobs = occurrencesByDay.get(buildDayKey(dayStart)) || []
const jobsByWeekDay = weekDays.map((date) => ({
date,
jobs: occurrencesByDay.get(buildDayKey(date)) || [],
}))
const jobsByMonthDay = monthDays.map((date) => ({
date,
jobs: occurrencesByDay.get(buildDayKey(date)) || [],
}))
const selectedDayJobs = occurrencesByDay.get(buildDayKey(selectedCalendarDate)) || []
const moveCalendar = (direction: -1 | 1) => { const moveCalendar = (direction: -1 | 1) => {
setCalendarDate((prev) => { setCalendarDate((prev) => {
@ -392,7 +424,7 @@ export function CronManagementPanel() {
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<h2 className="text-xl font-semibold">Calendar View</h2> <h2 className="text-xl font-semibold">Calendar View</h2>
<p className="text-sm text-muted-foreground">Read-only schedule visibility across all cron jobs</p> <p className="text-sm text-muted-foreground">Interactive schedule across all matching cron jobs</p>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <button
@ -466,21 +498,25 @@ export function CronManagementPanel() {
{calendarView === 'agenda' && ( {calendarView === 'agenda' && (
<div className="border border-border rounded-lg overflow-hidden"> <div className="border border-border rounded-lg overflow-hidden">
<div className="max-h-80 overflow-y-auto divide-y divide-border"> <div className="max-h-80 overflow-y-auto divide-y divide-border">
{agendaJobs.length === 0 ? ( {calendarOccurrences.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">No jobs match the current filters.</div> <div className="p-4 text-sm text-muted-foreground">No jobs match the current filters.</div>
) : ( ) : (
agendaJobs.map((job) => ( calendarOccurrences.map((row) => (
<div key={`agenda-${job.id || job.name}`} className="p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2"> <button
key={`agenda-${row.job.id || row.job.name}-${row.atMs}`}
onClick={() => handleJobSelect(row.job)}
className="w-full p-3 text-left flex flex-col md:flex-row md:items-center md:justify-between gap-2 hover:bg-secondary transition-colors"
>
<div> <div>
<div className="font-medium text-foreground">{job.name}</div> <div className="font-medium text-foreground">{row.job.name}</div>
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
{job.agentId || 'system'} · {job.enabled ? 'enabled' : 'disabled'} · {job.schedule} {row.job.agentId || 'system'} · {row.job.enabled ? 'enabled' : 'disabled'} · {row.job.schedule}
</div> </div>
</div> </div>
<div className="text-sm text-muted-foreground"> <div className="text-sm text-muted-foreground">
{job.nextRun ? new Date(job.nextRun).toLocaleString() : 'No upcoming run'} {new Date(row.atMs).toLocaleString()}
</div> </div>
</div> </button>
)) ))
)} )}
</div> </div>
@ -493,13 +529,17 @@ export function CronManagementPanel() {
<div className="text-sm text-muted-foreground">No scheduled jobs for this day.</div> <div className="text-sm text-muted-foreground">No scheduled jobs for this day.</div>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
{dayJobs.map((job) => ( {dayJobs.map((row) => (
<div key={`day-${job.id || job.name}`} className="p-2 rounded border border-border bg-secondary/40"> <button
<div className="text-sm font-medium text-foreground">{job.name}</div> key={`day-${row.job.id || row.job.name}-${row.atMs}`}
onClick={() => handleJobSelect(row.job)}
className="w-full p-2 rounded border border-border bg-secondary/40 hover:bg-secondary transition-colors text-left"
>
<div className="text-sm font-medium text-foreground">{row.job.name}</div>
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
{job.nextRun ? new Date(job.nextRun).toLocaleTimeString() : 'Unknown time'} · {job.agentId || 'system'} · {job.enabled ? 'enabled' : 'disabled'} {new Date(row.atMs).toLocaleTimeString()} · {row.job.agentId || 'system'} · {row.job.enabled ? 'enabled' : 'disabled'}
</div> </div>
</div> </button>
))} ))}
</div> </div>
)} )}
@ -509,21 +549,25 @@ export function CronManagementPanel() {
{calendarView === 'week' && ( {calendarView === 'week' && (
<div className="grid grid-cols-1 md:grid-cols-7 gap-2"> <div className="grid grid-cols-1 md:grid-cols-7 gap-2">
{jobsByWeekDay.map(({ date, jobs }) => ( {jobsByWeekDay.map(({ date, jobs }) => (
<div key={`week-${date.toISOString()}`} className="border border-border rounded-lg p-2 min-h-36"> <button
key={`week-${date.toISOString()}`}
onClick={() => setSelectedCalendarDate(startOfDay(date))}
className={`border border-border rounded-lg p-2 min-h-36 text-left ${isSameDay(date, selectedCalendarDate) ? 'bg-primary/10 border-primary/40' : 'hover:bg-secondary/50'}`}
>
<div className={`text-xs font-medium mb-2 ${isSameDay(date, new Date()) ? 'text-primary' : 'text-muted-foreground'}`}> <div className={`text-xs font-medium mb-2 ${isSameDay(date, new Date()) ? 'text-primary' : 'text-muted-foreground'}`}>
{date.toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' })} {date.toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' })}
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
{jobs.slice(0, 4).map((job) => ( {jobs.slice(0, 4).map((row) => (
<div key={`week-job-${job.id || job.name}`} className="text-xs px-2 py-1 rounded bg-secondary text-foreground truncate" title={job.name}> <div key={`week-job-${row.job.id || row.job.name}-${row.atMs}`} className="text-xs px-2 py-1 rounded bg-secondary text-foreground truncate" title={row.job.name}>
{job.nextRun ? new Date(job.nextRun).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '--:--'} {job.name} {new Date(row.atMs).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} {row.job.name}
</div> </div>
))} ))}
{jobs.length > 4 && ( {jobs.length > 4 && (
<div className="text-xs text-muted-foreground">+{jobs.length - 4} more</div> <div className="text-xs text-muted-foreground">+{jobs.length - 4} more</div>
)} )}
</div> </div>
</div> </button>
))} ))}
</div> </div>
)} )}
@ -535,15 +579,16 @@ export function CronManagementPanel() {
return ( return (
<div <div
key={`month-${date.toISOString()}`} key={`month-${date.toISOString()}`}
className={`border border-border rounded-lg p-2 min-h-24 ${inCurrentMonth ? 'bg-transparent' : 'bg-secondary/30'}`} onClick={() => setSelectedCalendarDate(startOfDay(date))}
className={`border border-border rounded-lg p-2 min-h-24 cursor-pointer ${inCurrentMonth ? 'bg-transparent' : 'bg-secondary/30'} ${isSameDay(date, selectedCalendarDate) ? 'border-primary/40 bg-primary/10' : 'hover:bg-secondary/50'}`}
> >
<div className={`text-xs mb-1 ${isSameDay(date, new Date()) ? 'text-primary font-semibold' : inCurrentMonth ? 'text-foreground' : 'text-muted-foreground'}`}> <div className={`text-xs mb-1 ${isSameDay(date, new Date()) ? 'text-primary font-semibold' : inCurrentMonth ? 'text-foreground' : 'text-muted-foreground'}`}>
{date.getDate()} {date.getDate()}
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
{jobs.slice(0, 2).map((job) => ( {jobs.slice(0, 2).map((row) => (
<div key={`month-job-${job.id || job.name}`} className="text-[11px] px-1.5 py-0.5 rounded bg-secondary text-foreground truncate" title={job.name}> <div key={`month-job-${row.job.id || row.job.name}-${row.atMs}`} className="text-[11px] px-1.5 py-0.5 rounded bg-secondary text-foreground truncate" title={row.job.name}>
{job.name} {row.job.name}
</div> </div>
))} ))}
{jobs.length > 2 && <div className="text-[11px] text-muted-foreground">+{jobs.length - 2}</div>} {jobs.length > 2 && <div className="text-[11px] text-muted-foreground">+{jobs.length - 2}</div>}
@ -553,6 +598,35 @@ export function CronManagementPanel() {
})} })}
</div> </div>
)} )}
{calendarView !== 'agenda' && (
<div className="border border-border rounded-lg p-3">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-medium text-foreground">
{selectedCalendarDate.toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric', year: 'numeric' })}
</h3>
<span className="text-xs text-muted-foreground">{selectedDayJobs.length} jobs</span>
</div>
{selectedDayJobs.length === 0 ? (
<div className="text-sm text-muted-foreground">No jobs scheduled on this date.</div>
) : (
<div className="space-y-2">
{selectedDayJobs.map((row) => (
<button
key={`selected-day-${row.job.id || row.job.name}-${row.atMs}`}
onClick={() => handleJobSelect(row.job)}
className="w-full text-left p-2 rounded border border-border bg-secondary/40 hover:bg-secondary transition-colors"
>
<div className="text-sm font-medium text-foreground">{row.job.name}</div>
<div className="text-xs text-muted-foreground">
{new Date(row.atMs).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} · {row.job.agentId || 'system'}
</div>
</button>
))}
</div>
)}
</div>
)}
</div> </div>
</div> </div>

View File

@ -353,6 +353,9 @@ export function MemoryBrowserPanel() {
? 'Browse and manage local knowledge files and memory' ? 'Browse and manage local knowledge files and memory'
: 'Explore knowledge files and memory structure'} : 'Explore knowledge files and memory structure'}
</p> </p>
<p className="text-xs text-muted-foreground mt-1">
This page shows all workspace memory files. The agent profile Memory tab only edits that single agent&apos;s working memory.
</p>
{/* Tab Navigation */} {/* Tab Navigation */}
<div className="flex gap-2 mt-4"> <div className="flex gap-2 mt-4">

View File

@ -461,6 +461,9 @@ export function SuperAdminPanel() {
</button> </button>
{createExpanded && ( {createExpanded && (
<div className="p-4 space-y-3"> <div className="p-4 space-y-3">
<div className="text-xs text-muted-foreground">
Add a new workspace/client instance here. Fill the form below and click <span className="text-foreground font-medium">Create + Queue</span>.
</div>
{gatewayLoadError && ( {gatewayLoadError && (
<div className="px-3 py-2 rounded-md text-xs border bg-amber-500/10 text-amber-300 border-amber-500/20"> <div className="px-3 py-2 rounded-md text-xs border bg-amber-500/10 text-amber-300 border-amber-500/20">
Gateway list unavailable: {gatewayLoadError}. Using fallback owner value. Gateway list unavailable: {gatewayLoadError}. Using fallback owner value.

View File

@ -105,4 +105,23 @@ describe('requireRole', () => {
) )
expect(result.user).toBeDefined() expect(result.user).toBeDefined()
}) })
it('accepts Authorization Bearer API key', () => {
const result = requireRole(
makeRequest({ authorization: 'Bearer test-api-key-secret' }),
'admin',
)
expect(result.user).toBeDefined()
expect(result.user!.username).toBe('api')
})
it('rejects API key auth when API_KEY is not configured', () => {
process.env = { ...originalEnv, API_KEY: '' }
const result = requireRole(
makeRequest({ 'x-api-key': 'test-api-key-secret' }),
'viewer',
)
expect(result.status).toBe(401)
expect(result.user).toBeUndefined()
})
}) })

View File

@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { buildDayKey, getCronOccurrences } from '@/lib/cron-occurrences'
describe('buildDayKey', () => {
it('formats YYYY-MM-DD in local time', () => {
const date = new Date(2026, 2, 4, 9, 15, 0, 0)
expect(buildDayKey(date)).toBe('2026-03-04')
})
})
describe('getCronOccurrences', () => {
it('expands daily schedule across range', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 5, 0, 0, 0, 0).getTime()
const rows = getCronOccurrences('0 0 * * *', start, end)
expect(rows).toHaveLength(4)
expect(rows.map((r) => r.dayKey)).toEqual([
'2026-03-01',
'2026-03-02',
'2026-03-03',
'2026-03-04',
])
})
it('supports step values', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 1, 3, 0, 0, 0).getTime()
const rows = getCronOccurrences('*/30 * * * *', start, end)
expect(rows).toHaveLength(6)
})
it('ignores OpenClaw timezone suffix in display schedule', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 2, 0, 0, 0, 0).getTime()
const rows = getCronOccurrences('0 6 * * * (UTC)', start, end)
expect(rows).toHaveLength(1)
})
it('returns empty list for invalid cron', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 2, 0, 0, 0, 0).getTime()
expect(getCronOccurrences('invalid', start, end)).toEqual([])
})
})

View File

@ -277,8 +277,9 @@ export function getUserFromRequest(request: Request): User | null {
} }
// Check API key - return synthetic user // Check API key - return synthetic user
const apiKey = request.headers.get('x-api-key') const configuredApiKey = (process.env.API_KEY || '').trim()
if (apiKey && safeCompare(apiKey, process.env.API_KEY || '')) { const apiKey = extractApiKeyFromHeaders(request.headers)
if (configuredApiKey && apiKey && safeCompare(apiKey, configuredApiKey)) {
return { return {
id: 0, id: 0,
username: 'api', username: 'api',
@ -294,6 +295,24 @@ export function getUserFromRequest(request: Request): User | null {
return null return null
} }
function extractApiKeyFromHeaders(headers: Headers): string | null {
const direct = (headers.get('x-api-key') || '').trim()
if (direct) return direct
const authorization = (headers.get('authorization') || '').trim()
if (!authorization) return null
const [scheme, ...rest] = authorization.split(/\s+/)
if (!scheme || rest.length === 0) return null
const normalized = scheme.toLowerCase()
if (normalized === 'bearer' || normalized === 'apikey' || normalized === 'token') {
return rest.join(' ').trim() || null
}
return null
}
/** /**
* Role hierarchy levels for access control. * Role hierarchy levels for access control.
* viewer < operator < admin * viewer < operator < admin

139
src/lib/cron-occurrences.ts Normal file
View File

@ -0,0 +1,139 @@
export interface CronOccurrence {
atMs: number
dayKey: string
}
interface ParsedField {
any: boolean
matches: (value: number) => boolean
}
interface ParsedCron {
minute: ParsedField
hour: ParsedField
dayOfMonth: ParsedField
month: ParsedField
dayOfWeek: ParsedField
}
function normalizeCronExpression(raw: string): string {
const trimmed = raw.trim()
const tzSuffixMatch = trimmed.match(/^(.*)\s+\([^)]+\)$/)
return (tzSuffixMatch?.[1] || trimmed).trim()
}
function parseToken(token: string, min: number, max: number): { any: boolean; values: Set<number> } {
const valueSet = new Set<number>()
const trimmed = token.trim()
if (trimmed === '*') {
for (let i = min; i <= max; i += 1) valueSet.add(i)
return { any: true, values: valueSet }
}
for (const part of trimmed.split(',')) {
const section = part.trim()
if (!section) continue
const [rangePart, stepPart] = section.split('/')
const step = stepPart ? Number(stepPart) : 1
if (!Number.isFinite(step) || step <= 0) continue
if (rangePart === '*') {
for (let i = min; i <= max; i += step) valueSet.add(i)
continue
}
if (rangePart.includes('-')) {
const [fromRaw, toRaw] = rangePart.split('-')
const from = Number(fromRaw)
const to = Number(toRaw)
if (!Number.isFinite(from) || !Number.isFinite(to)) continue
const start = Math.max(min, Math.min(max, from))
const end = Math.max(min, Math.min(max, to))
for (let i = start; i <= end; i += step) valueSet.add(i)
continue
}
const single = Number(rangePart)
if (!Number.isFinite(single)) continue
if (single >= min && single <= max) valueSet.add(single)
}
return { any: false, values: valueSet }
}
function parseField(token: string, min: number, max: number): ParsedField {
const parsed = parseToken(token, min, max)
return {
any: parsed.any,
matches: (value: number) => parsed.values.has(value),
}
}
function parseCron(raw: string): ParsedCron | null {
const normalized = normalizeCronExpression(raw)
const parts = normalized.split(/\s+/).filter(Boolean)
if (parts.length !== 5) return null
return {
minute: parseField(parts[0], 0, 59),
hour: parseField(parts[1], 0, 23),
dayOfMonth: parseField(parts[2], 1, 31),
month: parseField(parts[3], 1, 12),
dayOfWeek: parseField(parts[4], 0, 6),
}
}
function matchesDay(parsed: ParsedCron, date: Date): boolean {
const dayOfMonthMatches = parsed.dayOfMonth.matches(date.getDate())
const dayOfWeekMatches = parsed.dayOfWeek.matches(date.getDay())
if (parsed.dayOfMonth.any && parsed.dayOfWeek.any) return true
if (parsed.dayOfMonth.any) return dayOfWeekMatches
if (parsed.dayOfWeek.any) return dayOfMonthMatches
return dayOfMonthMatches || dayOfWeekMatches
}
export function buildDayKey(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export function getCronOccurrences(
schedule: string,
rangeStartMs: number,
rangeEndMs: number,
max = 1000
): CronOccurrence[] {
if (!schedule || !Number.isFinite(rangeStartMs) || !Number.isFinite(rangeEndMs)) return []
if (rangeEndMs <= rangeStartMs || max <= 0) return []
const parsed = parseCron(schedule)
if (!parsed) return []
const occurrences: CronOccurrence[] = []
const cursor = new Date(rangeStartMs)
cursor.setSeconds(0, 0)
if (cursor.getTime() < rangeStartMs) {
cursor.setMinutes(cursor.getMinutes() + 1, 0, 0)
}
while (cursor.getTime() < rangeEndMs && occurrences.length < max) {
if (
parsed.month.matches(cursor.getMonth() + 1) &&
matchesDay(parsed, cursor) &&
parsed.hour.matches(cursor.getHours()) &&
parsed.minute.matches(cursor.getMinutes())
) {
occurrences.push({
atMs: cursor.getTime(),
dayKey: buildDayKey(cursor),
})
}
cursor.setMinutes(cursor.getMinutes() + 1, 0, 0)
}
return occurrences
}

View File

@ -52,6 +52,22 @@ function applySecurityHeaders(response: NextResponse): NextResponse {
return response return response
} }
function extractApiKeyFromRequest(request: NextRequest): string {
const direct = (request.headers.get('x-api-key') || '').trim()
if (direct) return direct
const authorization = (request.headers.get('authorization') || '').trim()
if (!authorization) return ''
const [scheme, ...rest] = authorization.split(/\s+/)
if (!scheme || rest.length === 0) return ''
const normalized = scheme.toLowerCase()
if (normalized === 'bearer' || normalized === 'apikey' || normalized === 'token') {
return rest.join(' ').trim()
}
return ''
}
export function proxy(request: NextRequest) { export function proxy(request: NextRequest) {
// Network access control. // Network access control.
// In production: default-deny unless explicitly allowed. // In production: default-deny unless explicitly allowed.
@ -63,7 +79,8 @@ export function proxy(request: NextRequest) {
.map((s) => s.trim()) .map((s) => s.trim())
.filter(Boolean) .filter(Boolean)
const isAllowedHost = allowAnyHost || allowedPatterns.some((p) => hostMatches(p, hostName)) const enforceAllowlist = !allowAnyHost && allowedPatterns.length > 0
const isAllowedHost = !enforceAllowlist || allowedPatterns.some((p) => hostMatches(p, hostName))
if (!isAllowedHost) { if (!isAllowedHost) {
return new NextResponse('Forbidden', { status: 403 }) return new NextResponse('Forbidden', { status: 403 })
@ -97,8 +114,10 @@ export function proxy(request: NextRequest) {
// API routes: accept session cookie OR API key // API routes: accept session cookie OR API key
if (pathname.startsWith('/api/')) { if (pathname.startsWith('/api/')) {
const apiKey = request.headers.get('x-api-key') const configuredApiKey = (process.env.API_KEY || '').trim()
if (sessionToken || (apiKey && safeCompare(apiKey, process.env.API_KEY || ''))) { const apiKey = extractApiKeyFromRequest(request)
const hasValidApiKey = Boolean(configuredApiKey && apiKey && safeCompare(apiKey, configuredApiKey))
if (sessionToken || hasValidApiKey) {
return applySecurityHeaders(NextResponse.next()) return applySecurityHeaders(NextResponse.next())
} }