privacy-timeguard
v1.0.1
Published
Prevent accidental API calls outside allowed time windows (office hours, maintenance windows, etc.)
Maintainers
Readme
🕐 privacy-timeguard
Prevent accidental API calls outside allowed time windows
A tiny, zero-dependency library to guard your API calls, cron jobs, and critical operations against running outside designated time windows. Perfect for preventing production incidents during off-hours, enforcing maintenance windows, or implementing time-based feature flags.
🎯 Problem it Solves
Ever had these happen?
- ❌ Production API calls triggering at 3 AM when support is offline
- ❌ Batch jobs running during peak hours, slowing down your app
- ❌ Automated deployments running outside your maintenance window
- ❌ Critical operations executing when your team isn't available
privacy-timeguard gives you a simple way to prevent these scenarios with timezone-aware time window checks.
📦 Installation
npm install privacy-timeguardyarn add privacy-timeguardpnpm add privacy-timeguard✨ Quick Start
Example 1: Simple Office Hours Check
import { isAllowedNow } from "privacy-timeguard";
const canProceed = isAllowedNow({
timezone: "Asia/Kolkata",
allowed: [{ start: "09:00", end: "18:00" }],
});
if (canProceed) {
// ✅ Make API call
await sendCriticalEmail();
} else {
// ⛔ Block or defer
console.log("Outside business hours. Deferring operation.");
}Example 2: Detailed Check with Reason
import { checkTime } from "privacy-timeguard";
const result = checkTime({
timezone: "America/New_York",
allowed: [
{ start: "09:00", end: "12:00" },
{ start: "14:00", end: "18:00" },
],
});
if (!result.allowed) {
console.warn(`❌ ${result.reason}`);
console.log(`Current time: ${result.currentTime} in ${result.timezone}`);
console.log(
`Next window: ${result.nextWindow?.start} - ${result.nextWindow?.end}`
);
}Example 3: Overnight Maintenance Window
import { isAllowedNow } from "privacy-timeguard";
// Allow operations from 10 PM to 6 AM (overnight window)
const inMaintenanceWindow = isAllowedNow({
timezone: "UTC",
allowed: [{ start: "22:00", end: "06:00" }],
});
if (inMaintenanceWindow) {
await runDatabaseMigration();
}🔧 API Reference
isAllowedNow(config: TimeGuardConfig): boolean
Simple boolean check if current time is allowed.
Parameters:
config.timezone(string): IANA timezone (e.g.,"Asia/Kolkata","America/New_York")config.allowed(TimeWindow[]): Array of allowed time windowsconfig.currentDate(Date, optional): Custom date for testing (defaults tonew Date())
Returns: boolean - true if allowed, false otherwise
checkTime(config: TimeGuardConfig): TimeCheckResult
Detailed check with reason and metadata.
Returns:
{
allowed: boolean; // Whether time is allowed
reason: string; // Human-readable reason
timezone: string; // Timezone used
currentTime: string; // Current time in HH:MM format
nextWindow?: TimeWindow; // Next allowed window (if blocked)
}Types
interface TimeWindow {
start: string; // HH:MM format (24-hour)
end: string; // HH:MM format (24-hour)
}
interface TimeGuardConfig {
timezone: string; // IANA timezone
allowed: TimeWindow[]; // Allowed time windows
currentDate?: Date; // Optional: for testing
}🌍 Timezone Support
Uses native Intl.DateTimeFormat for timezone handling. Supports all IANA timezones:
Asia/Kolkata(IST)America/New_York(EST/EDT)Europe/London(GMT/BST)UTC- And 400+ more...
⚡ Features
- ✅ Zero dependencies - Uses native JS APIs
- ✅ Tree-shakeable - Only import what you need
- ✅ TypeScript first - Full type safety
- ✅ Tiny - < 2KB gzipped
- ✅ Overnight ranges - Handles
22:00-06:00correctly - ✅ Multiple windows - Support multiple time ranges per day
- ✅ Timezone aware - Accurate time checks across timezones
🧪 Use Cases
1. API Rate Limiting / Time-based Access Control
app.post("/api/heavy-operation", (req, res) => {
if (
!isAllowedNow({
timezone: "UTC",
allowed: [{ start: "09:00", end: "17:00" }],
})
) {
return res.status(429).json({
error: "Service only available during business hours",
});
}
// Process request
});2. Cron Job Guards
cron.schedule("*/15 * * * *", () => {
if (
!isAllowedNow({
timezone: "America/New_York",
allowed: [{ start: "00:00", end: "06:00" }],
})
) {
console.log("Skipping backup - outside maintenance window");
return;
}
runBackupJob();
});3. Feature Flags (Time-based)
const showNewFeature = isAllowedNow({
timezone: "Asia/Tokyo",
allowed: [{ start: "10:00", end: "16:00" }],
});
if (showNewFeature) {
renderNewUI();
} else {
renderOldUI();
}🛠️ Development
# Install dependencies
npm install
# Run tests
npm test
# Build library
npm run build
# Watch mode for development
npm run test:watch🗺️ Roadmap
- [ ] Add day-of-week filtering (e.g., "Mon-Fri only")
- [ ] Support for holiday exclusions
- [ ] Recurring weekly schedules
- [ ] Duration-based windows ("next 2 hours")
- [ ] Express/Fastify middleware
- [ ] CLI tool for testing time windows
🤝 Contributing
Contributions welcome! Please open an issue or PR.
📄 License
MIT © Pratik Naik
💡 Why This Library Exists
Most time-based controls require heavy dependencies (moment-timezone, date-fns, cron libraries). This library provides a focused, lightweight solution using native browser/Node.js APIs for the 80% use case: simple time window validation.
Perfect for:
- Small projects that don't want heavy dependencies
- Lambda functions where bundle size matters
- Teams wanting explicit time-based controls without complex scheduling libraries
📚 Related Projects
Made with ❤️ by Pratik Naik, developer who cares about operational safety and building tools that prevent 3 AM production incidents
