alarms.ts

1.9 KB · raw

1import { ensureSettingsLoaded, getSettings, lock } from "./vault";23const AUTO_LOCK_ALARM = "autolock";4const DEFAULT_AUTO_LOCK_MINUTES = 5;5const MIN_IDLE_SECONDS = 15;67function resolveAutoLockMinutes(): number {8  const setting = getSettings().autoLockMinutes;9  if (typeof setting !== "number") return DEFAULT_AUTO_LOCK_MINUTES;10  return setting; // 0 = never11}1213export function touchAutoLock(): void {14  chrome.alarms.clear(AUTO_LOCK_ALARM);15  const minutes = resolveAutoLockMinutes();16  if (minutes <= 0) return; // "never"17  chrome.alarms.create(AUTO_LOCK_ALARM, { delayInMinutes: minutes });18}1920export function clearAutoLock(): void {21  chrome.alarms.clear(AUTO_LOCK_ALARM);22}2324export async function setupAutoLock(): Promise<void> {25  await ensureSettingsLoaded();26  if (!chrome.idle?.setDetectionInterval) return;27  const minutes = resolveAutoLockMinutes();28  const seconds = minutes > 0 ? Math.max(MIN_IDLE_SECONDS, minutes * 60) : MIN_IDLE_SECONDS;29  chrome.idle.setDetectionInterval(seconds);30}3132function broadcastLocked(): void {33  // Reach the popup (and any other extension UI context) via runtime.34  chrome.runtime.sendMessage({ type: "VAULT_LOCKED" }).catch(() => {});35  // Reach content scripts via tabs. Tabs without Peach content scripts36  // loaded will reject the sendMessage; ignore those.37  try {38    chrome.tabs.query({}, (tabs) => {39      for (const tab of tabs) {40        if (tab.id === undefined) continue;41        chrome.tabs.sendMessage(tab.id, { type: "VAULT_LOCKED" }).catch(() => {});42      }43    });44  } catch {45    // tabs permission may not be available in all contexts46  }47}4849chrome.alarms.onAlarm.addListener((alarm) => {50  if (alarm.name === AUTO_LOCK_ALARM) {51    lock();52    broadcastLocked();53  }54});5556if (chrome.idle?.onStateChanged) {57  chrome.idle.onStateChanged.addListener((state) => {58    if (resolveAutoLockMinutes() <= 0) return;59    if (state === "idle" || state === "locked") {60      lock();61      broadcastLocked();62    }63  });64}