alarms.ts

2.1 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  if (!chrome.alarms?.clear || !chrome.alarms?.create) return;15  chrome.alarms.clear(AUTO_LOCK_ALARM);16  const minutes = resolveAutoLockMinutes();17  if (minutes <= 0) return; // "never"18  chrome.alarms.create(AUTO_LOCK_ALARM, { delayInMinutes: minutes });19}2021export function clearAutoLock(): void {22  if (!chrome.alarms?.clear) return;23  chrome.alarms.clear(AUTO_LOCK_ALARM);24}2526export async function setupAutoLock(): Promise<void> {27  await ensureSettingsLoaded();28  if (!chrome.idle?.setDetectionInterval) return;29  const minutes = resolveAutoLockMinutes();30  const seconds = minutes > 0 ? Math.max(MIN_IDLE_SECONDS, minutes * 60) : MIN_IDLE_SECONDS;31  chrome.idle.setDetectionInterval(seconds);32}3334function broadcastLocked(): void {35  // Reach the popup (and any other extension UI context) via runtime.36  chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => {});37  // Reach content scripts via tabs. Tabs without Peach content scripts38  // loaded will reject the sendMessage; ignore those.39  try {40    chrome.tabs.query({}, (tabs) => {41      for (const tab of tabs) {42        if (tab.id === undefined) continue;43        chrome.tabs.sendMessage(tab.id, { type: "VAULT_LOCKED" }).catch(() => {});44      }45    });46  } catch {47    // tabs permission may not be available in all contexts48  }49}5051if (chrome.alarms?.onAlarm?.addListener) {52  chrome.alarms.onAlarm.addListener((alarm) => {53    if (alarm.name === AUTO_LOCK_ALARM) {54      lock();55      broadcastLocked();56    }57  });58}5960if (chrome.idle?.onStateChanged) {61  chrome.idle.onStateChanged.addListener((state) => {62    if (resolveAutoLockMinutes() <= 0) return;63    if (state === "idle" || state === "locked") {64      lock();65      broadcastLocked();66    }67  });68}