惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
I
Intezer
F
Fortinet All Blogs
S
SegmentFault 最新的问题
罗磊的独立博客
V
Visual Studio Blog
V
V2EX
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
J
Java Code Geeks
美团技术团队
B
Blog
U
Unit 42
F
Full Disclosure
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Privacy International News Feed
G
Google Developers Blog
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
GbyAI
GbyAI
S
Schneier on Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 热门话题
Recorded Future
Recorded Future
D
Docker
博客园 - 聂微东
Project Zero
Project Zero
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
K
Kaspersky official blog
Martin Fowler
Martin Fowler
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
Lohrmann on Cybersecurity
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
Microsoft Security Blog
Microsoft Security Blog
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
V
Vulnerabilities – Threatpost
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
Hugging Face - Blog
Hugging Face - Blog
博客园_首页

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Testing macOS Notifications in Electron 42 During Local Development
Alex Truhniy · 2026-06-24 · via DEV Community

Electron migrated to UNNotification, and now your notifications silently fail unless the app is code-signed. Here's why — and how to fix it on your dev machine without packaging and signing on every run.


If you upgraded to Electron 42 and your macOS notifications suddenly stopped showing up, you're not doing anything wrong. The framework changed under your feet.

This is a hands-on guide. By the end you'll have:

  • A tiny Electron app that sends notifications and shows a live history of every notification and the lifecycle events it emitted (show, click, close, failed).
  • An understanding of why notifications fail with UNErrorDomain error 1.
  • A free, one-time local code-signing setup so notifications work during npm start — no packaging, no paid Apple Developer account.

The breaking change

From the Electron 42 release notes:

Behavior Changed: macOS notifications now use UNNotification API
Electron has migrated from the deprecated NSUserNotification API to the UNNotification API on macOS. The new API requires that an application be code-signed in order for notifications to be displayed. If an application is not code-signed, notifications will emit a failed event on the Notification object. (#47817)

Two consequences matter for everyday development:

  1. Code signing is now mandatory for a notification banner to appear on macOS.
  2. Failures are silent unless you listen for them. When the app isn't properly signed, the Notification object emits a failed event instead of throwing. If you don't subscribe to it, nothing happens and nothing tells you why.

During local development you typically run npm start, which launches the unsigned Electron.app from node_modules. So every notification fails — quietly.


A test harness: notifications + history

Let's build the smallest possible app that makes the behavior visible. The Notification API lives in the main process, so the renderer drives it over IPC, and the main process records a history of every attempt and its events.

main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow, Notification, ipcMain } = require('electron')
const path = require('node:path')

// In-memory log of every notification we've attempted, plus the lifecycle
// events each one emitted. On Electron 42+, macOS uses the UNNotification API
// which requires the app to be code-signed; unsigned builds emit a `failed`
// event instead of showing the banner. We record that here so it's visible.
const notificationHistory = []

let mainWindow = null

function pushHistoryEvent (id, type, detail) {
  const entry = notificationHistory.find((n) => n.id === id)
  if (!entry) return
  entry.events.push({ type, detail: detail ?? null, at: new Date().toISOString() })
  // Keep the renderer's history view in sync as events arrive.
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.webContents.send('notification-history-updated', notificationHistory)
  }
}

function showNotification (options = {}) {
  const id = `${Date.now()}-${notificationHistory.length}`
  const opts = {
    title: options.title || 'Electron 42 notification',
    body: options.body || 'Testing the UNNotification API on macOS.',
    silent: Boolean(options.silent)
  }

  const entry = {
    id,
    options: opts,
    supported: Notification.isSupported(),
    createdAt: new Date().toISOString(),
    events: []
  }
  notificationHistory.unshift(entry)

  if (!entry.supported) {
    pushHistoryEvent(id, 'unsupported', 'Notification.isSupported() returned false')
    return { id, supported: false }
  }

  const notification = new Notification(opts)

  notification.on('show', () => pushHistoryEvent(id, 'show'))
  notification.on('click', () => pushHistoryEvent(id, 'click'))
  notification.on('close', () => pushHistoryEvent(id, 'close'))
  // The key Electron 42 macOS behavior: unsigned apps can't display
  // notifications via UNNotification and emit `failed` with an error string.
  notification.on('failed', (_event, error) => pushHistoryEvent(id, 'failed', String(error)))

  notification.show()
  return { id, supported: true }
}

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.loadFile('index.html')
}

app.whenReady().then(() => {
  // IPC: send a notification and report whether it was supported.
  ipcMain.handle('show-notification', (_event, options) => showNotification(options))
  // IPC: hand the full attempt-and-event log back to the renderer.
  ipcMain.handle('get-notification-history', () => notificationHistory)

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

A note on the word history: Electron does not expose the macOS Notification Center's system-wide history. What we track here is the app's own log of attempts and their events — which is exactly what you need to debug the signing problem, because the failed event shows up right in the list.

preload.js

The renderer has no direct access to the Notification module, so we expose a small, safe bridge over contextBridge:

const { contextBridge, ipcRenderer } = require('electron')

// Expose a minimal, safe notification API to the renderer. The Notification
// module lives in the main process, so the renderer drives it over IPC.
contextBridge.exposeInMainWorld('notifications', {
  show: (options) => ipcRenderer.invoke('show-notification', options),
  getHistory: () => ipcRenderer.invoke('get-notification-history'),
  onHistoryUpdated: (callback) =>
    ipcRenderer.on('notification-history-updated', (_event, history) => callback(history))
})

index.html

A simple form plus a history list:

<section id="notification-tester">
  <h2>Notification tester</h2>
  <label>Title <input id="notif-title" type="text" value="Electron 42 notification"></label>
  <label>Body <input id="notif-body" type="text" value="Testing the UNNotification API on macOS."></label>
  <label><input id="notif-silent" type="checkbox"> Silent</label>
  <button id="send-notification" type="button">Send notification</button>

  <h3>History</h3>
  <ul id="notification-history"></ul>
</section>
<script src="./renderer.js"></script>

renderer.js

Wire the button and render the history, updating live as events arrive:

const historyList = document.getElementById('notification-history')

function renderHistory (history) {
  if (!history || history.length === 0) {
    historyList.innerHTML = '<li class="empty">No notifications sent yet.</li>'
    return
  }

  historyList.innerHTML = ''
  for (const entry of history) {
    const item = document.createElement('li')

    const title = document.createElement('div')
    title.className = 'notif-title'
    title.textContent = entry.options.title
    item.appendChild(title)

    const meta = document.createElement('div')
    meta.className = 'notif-meta'
    const events = entry.events.length
      ? entry.events.map((e) => (e.detail ? `${e.type} (${e.detail})` : e.type)).join('')
      : 'no events yet'
    meta.textContent = `supported: ${entry.supported} · ${events}`
    item.appendChild(meta)

    historyList.appendChild(item)
  }
}

async function refreshHistory () {
  renderHistory(await window.notifications.getHistory())
}

document.getElementById('send-notification').addEventListener('click', async () => {
  await window.notifications.show({
    title: document.getElementById('notif-title').value,
    body: document.getElementById('notif-body').value,
    silent: document.getElementById('notif-silent').checked
  })
  refreshHistory()
})

// Live updates as the main process records show/click/close/failed events.
window.notifications.onHistoryUpdated(renderHistory)

document.addEventListener('DOMContentLoaded', refreshHistory)


Reproducing the failure

Run the unsigned dev app:

npm start

Click Send notification. No banner appears, and the history shows something like:

Electron 42 notification
supported: true · failed (The operation couldn't be completed. (UNErrorDomain error 1.))

Notice supported: true. Notification.isSupported() returns true because the API is available — but the actual display fails. That's the whole trap: support and delivery are now two different things.

UNErrorDomain error 1 is UNErrorCodeNotificationsNotAllowed. The UNNotification API refused to display the notification because the running app isn't code-signed.


Why ad-hoc signing isn't enough

You might reach for the quickest fix:

codesign --force --deep --sign - node_modules/electron/dist/Electron.app

If you inspect the bundle Electron ships with, you'll see it already carries a signature:

codesign -dv node_modules/electron/dist/Electron.app
# ... flags=0x20002(adhoc,linker-signed) ...

That linker-signed flag is the catch. It's an automatic signature the linker applies — UNNotification does not accept it. A real ad-hoc signature (codesign --sign -) drops the linker-signed flag:

codesign -dv node_modules/electron/dist/Electron.app
# ... flags=0x2(adhoc) ...

This does make notifications work. But ad-hoc signing has a serious drawback for daily development, which leads to the next problem.


The Keychain prompt: why a stable identity matters

After re-signing, the next launch pops up a dialog:

Electron wants to use your confidential information stored in "Electron Safe Storage" in your keychain.

This isn't from our notification code. Under the hood, Electron is Chromium, and Chromium stores an encryption key (for cookies and the safeStorage API) in the macOS Keychain under "Electron Safe Storage". Access to a Keychain item is gated by the app's code signature. When you re-sign the app, macOS sees a different identity and asks for permission again.

Here's the trap with ad-hoc signatures: they have no stable identity. Every codesign --sign - produces a new cdhash. So even if you click Always Allow, the next re-sign (say, after npm install) invalidates the Keychain ACL and the prompt returns.

The fix is to sign with a stable identity — a real certificate. Then Always Allow sticks forever, and notifications keep working across reinstalls.

You don't need a paid Apple Developer account for this. A free, self-signed code-signing certificate is enough for local development.


The fix: a free self-signed code-signing certificate

Option A — Keychain Access (GUI)

  1. Open Keychain Access.
  2. Menu: Keychain Access → Certificate Assistant → Create a Certificate…
  3. Name: Electron Dev. Identity Type: Self-Signed Root. Certificate Type: Code Signing.
  4. Create it. It lands in your login keychain, ready to use.

Option B — Command line

If you prefer to script it, generate the key and certificate with OpenSSL, import it, and trust it for code signing:

# 1. Generate a self-signed code-signing certificate
cat > /tmp/electron-dev-cert.conf <<'EOF'
[ req ]
distinguished_name = dn
x509_extensions = ext
prompt = no
[ dn ]
CN = Electron Dev
[ ext ]
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, codeSigning
basicConstraints = critical, CA:false
EOF

openssl req -x509 -newkey rsa:2048 \
  -keyout /tmp/electron-dev-key.pem -out /tmp/electron-dev-cert.pem \
  -days 3650 -nodes -config /tmp/electron-dev-cert.conf

# 2. Bundle into a .p12. Use legacy algorithms + a non-empty password,
#    otherwise macOS `security` fails with "MAC verification failed".
openssl pkcs12 -export -legacy -macalg sha1 \
  -inkey /tmp/electron-dev-key.pem -in /tmp/electron-dev-cert.pem \
  -out /tmp/electron-dev.p12 -passout pass:electron -name "Electron Dev"

# 3. Import into the login keychain, allowing codesign to use the key
security import /tmp/electron-dev.p12 \
  -k ~/Library/Keychains/login.keychain-db \
  -P "electron" -T /usr/bin/codesign

# 4. Trust the certificate for code signing
#    (macOS will prompt for your login password — approve it)
security add-trusted-cert -r trustRoot -p codeSign \
  -k ~/Library/Keychains/login.keychain-db /tmp/electron-dev-cert.pem

# 5. Clean up the private key material on disk — it lives safely in the keychain now
rm -f /tmp/electron-dev-key.pem /tmp/electron-dev.p12 \
      /tmp/electron-dev-cert.pem /tmp/electron-dev-cert.conf

⚠️ Two gotchas the recipe above already handles:

  • Empty p12 passwords fail to import on recent macOS. Use a non-empty -passout/-P pair.
  • OpenSSL 3 defaults are incompatible with the macOS security tool. Add -legacy -macalg sha1 when exporting the p12, or you'll hit MAC verification failed during PKCS12 import (wrong password?).

Verify the identity is now valid:

security find-identity -v -p codesigning
#   1) 7495...CB11 "Electron Dev"


Sign the dev binary and automate it

Sign the Electron.app that npm start actually runs:

codesign --force --deep --sign "Electron Dev" node_modules/electron/dist/Electron.app

Confirm the result — note Authority=Electron Dev and flags=0x0(none) (no more linker-signed):

codesign -dvv node_modules/electron/dist/Electron.app
# Authority=Electron Dev
# flags=0x0(none)

The signature is lost every time Electron is reinstalled, so wire it into package.json so it re-applies automatically:

{
  "scripts": {
    "start": "electron .",
    "sign:dev": "codesign --force --deep --sign \"Electron Dev\" node_modules/electron/dist/Electron.app",
    "postinstall": "node -e \"process.platform==='darwin' && require('child_process').execSync('npm run sign:dev', {stdio: 'inherit'})\""
  }
}

  • npm run sign:dev — re-sign on demand.
  • postinstall — re-sign automatically after every npm install, and only on macOS (it's a no-op elsewhere, so it won't break Linux/Windows teammates).

Verify

npm start

Click Send notification. This time:

  • A notification banner appears.
  • The history shows supported: true · show (and click / close as you interact).

The Keychain prompt appears once more (because the signature changed from the previous run). Click Always Allow — and because the Electron Dev identity is now stable, it's remembered for good, surviving future npm install and npm run sign:dev runs.

You can find the complete code on GitHub.

Good luck and have fun!