Перейти к основному содержанию

Breach to Barrier: Strengthening Apps with the Sandbox

· 4 мин. прочитано

It’s been more than a week since CVE-2023-4863: Heap buffer overflow in WebP was made public, leading to a flurry of new releases of software rendering webp images: macOS, iOS, Chrome, Firefox, and various Linux distributions all received updates. This followed investigations by Citizen Lab, discovering that an iPhone used by a “Washington DC-based civil society organization” was under attack using a zero-click exploit within iMessage.

Electron, too, spun into action and released new versions the same day: If your app renders any user-provided content, you should update your version of Electron - v27.0.0-beta.2, v26.2.1, v25.8.1, v24.8.3, and v22.3.24 all contain a fixed version of libwebp, the library responsible for rendering webp images.

Now that we are all freshly aware that an interaction as innocent as “rendering an image” is a potentially dangerous activity, we want to use this opportunity to remind everyone that Electron comes with a process sandbox that will limit the blast radius of the next big attack — whatever it may be.

The sandbox was available ever since Electron v1 and enabled by default in v20, but we know that many apps (especially those that have been around for a while) may have a sandbox: false somewhere in their code – or a nodeIntegration: true, which equally disables the sandbox when there is no explicit sandbox setting. That’s understandable: If you’ve been with us for a long time, you probably enjoyed the power of throwing a require("child_process") or require("fs") into the same code that runs your HTML/CSS.

Before we talk about how you migrate to the sandbox, let’s first discuss why you want it.

The sandbox puts a hard cage around all renderer processes, ensuring that no matter what happens inside, code is executed inside a restricted environment. As a concept, it's a lot older than Chromium, and provided as a feature by all major operating systems. Electron's and Chromium's sandbox build on top of these system features. Even if you never display user-generated content, you should consider the possibility that your renderer might get compromised: Scenarios as sophisticated as supply chain attacks and as simple as little bugs can lead to your renderer doing things you didn't fully intend for it to do.

The sandbox makes that scenario a lot less scary: A process inside gets to freely use CPU cycles and memory — that’s it. Processes cannot write to disk or display their own windows. In the case of our libwep bug, the sandbox makes sure that an attacker cannot install or run malware. In fact, in the case of the original Pegasus attack on the employee’s iPhone, the attack specifically targeted a non-sandboxed image process to gain access to the phone, first breaking out of the boundaries of the normally sandboxed iMessage. When a CVE like the one in this example is announced, you still have to upgrade your Electron apps to a secure version — but in the meantime, the amount of damage an attacker can do is limited dramatically.

Migrating a vanilla Electron application from sandbox: false to sandbox: true is an undertaking. I know, because even though I have personally written the first draft of the Electron Security Guidelines, I have not managed to migrate one of my own apps to use it. That changed this weekend, and I recommend that you change it, too.

Don’t be scared by the number of line changes, most of it is in package-lock.json

There are two things you need to tackle:

  1. If you’re using Node.js code in either preload scripts or the actual WebContents, you need to move all that Node.js interaction to the main process (or, if you are fancy, a utility process). Given how powerful renderers have become, chances are high that the vast majority of your code doesn’t really need refactoring.

    Consult our documentation on Inter-Process Communication. In my case, I moved a lot of code and wrapped it in ipcRenderer.invoke() and ipcMain.handle(), but the process was straightforward and quickly done. Be a little mindful of your APIs here - if you build an API called executeCodeAsRoot(code), the sandbox won't protect your users much.

  2. Since enabling the sandbox disables Node.js integration in your preload scripts, you can no longer use require("../my-script"). In other words, your preload script needs to be a single file.

    There are multiple ways to do that: Webpack, esbuild, parcel, and rollup will all get the job done. I used Electron Forge’s excellent Webpack plugin, users of the equally popular electron-builder can use electron-webpack.

All in all, the entire process took me around four days — and that includes a lot of scratching my head at how to wrangle Webpack’s massive power, since I decided to use the opportunity to refactor my code in plenty of other ways, too.

Electron 26.0.0

· 2 мин. прочитано

Electron 26.0.0 вышел! Он включает обновления Chromium 116.0.5845.62, V8 11.2 и Node.js 18.16.1. Read below for more details!


Команда Electron рада объявить о выпуске Electron 26.0.0! You can install it with npm via npm install electron@latest or download it from our releases website. Continue reading for details about this release.

If you have any feedback, please share it with us on Twitter, or join our community Discord! Bugs and feature requests can be reported in Electron's issue tracker.

Notable Changes

Stack Changes

Критические изменения

Устарело: webContents.getPrinters

Метод webContents.getPrinters устарел. Используйте вместо него webContents.getPrintersAsync.

const w = new BrowserWindow({ show: false });

// Устарел
console.log(w.webContents.getPrinters());
// Замените на
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers);
});

Устарело: systemPreferences.{get,set}AppLevelAppearance и systemPreferences.appLevelAppearance

Методы systemPreferences.getAppLevelAppearance и systemPreferences.setAppLevelAppearance устарели, так же как и свойство systemPreferences.appLevelAppearance. Вместо этого используйте модуль nativeTheme.

// Устарело
systemPreferences.getAppLevelAppearance();
// Замените на
nativeTheme.shouldUseDarkColors;

// Устарело
systemPreferences.appLevelAppearance;
// Замените на
nativeTheme.shouldUseDarkColors;

// Устарело
systemPreferences.setAppLevelAppearance('dark');
// Замените на
nativeTheme.themeSource = 'dark';

Устарело: значение alternate-selected-control-text для systemPreferences.getColor

Значение alternate-selected-control-text для systemPreferences.getColor устарело. Вместо него используйте selected-content-background.

// Устарело
systemPreferences.getColor('alternate-selected-control-text');
// Замените на
systemPreferences.getColor('selected-content-background');

New Features

  • Добавлены safeStorage.setUsePlainTextEncryption и safeStorage.getSelectedStorageBackend api. #39107
  • Добавлены safeStorage.setUsePlainTextEncryption и safeStorage.getSelectedStorageBackend api. #39155
  • Добавлено senderIsMainFrame для сообщений, отправленных с помощью ipcRenderer.sendTo(). #39206
  • Добавлена поддержка пометки о том, что Меню вызвано нажатием на клавиатуру. #38954

Окончание поддержки версии 23.x.y

Поддержка Electron 23.x.y подошла к концу в соответствии с политикой поддержки. Developers and applications are encouraged to upgrade to a newer version of Electron.

E26 (Aug'23)E27 (Oct'23)E28 (Янв'24)
26.x.y27.x.y28.x.y
25.x.y26.x.y27.x.y
24.x.y25.x.y26.x.y
22.x.y

Что дальше

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8.

You can find Electron's public timeline here.

More information about future changes can be found on the Planned Breaking Changes page.

Electron 25.0.0

· 5 ��ин. прочитано

Electron 25.0.0 вышел! Он включает обновления Chromium 114, V8 11.4 и Node.js 18.15.0. Read below for more details!


Команда Electron рада объявить о выпуске Electron 25.0.0! You can install it with npm via npm install electron@latest or download it from our releases website. Continue reading for details about this release.

If you have any feedback, please share it with us on Twitter, or join our community Discord! Bugs and feature requests can be reported in Electron's issue tracker.

Notable Changes

Highlights

  • Implemented net.fetch within Electron's net module, using Chromium's networking stack. This differs from Node's fetch(), which uses Node.js' HTTP stack. See #36733 and #36606.
  • Added protocol.handle, which replaces and deprecates protocol.{register,intercept}{String,Buffer,Stream,Http,File}Protocol. #36674
  • Extended support for Electron 22, in order to match Chromium and Microsoft's Windows 7/8/8.1 deprecation plan. See additional details at the end of this blog post.

Stack Changes

Критические изменения

Obsoleto: protocol.{register,intercept}{Buffer,String,Stream,File,Http}Protocol

The protocol.register*Protocol and protocol.intercept*Protocol methods have been replaced with protocol.handle.

The new method can either register a new protocol or intercept an existing protocol, and responses can be of any type.

// Deprecated in Electron 25
protocol.registerBufferProtocol('some-protocol', () => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') });
});

// Replace with
protocol.handle('some-protocol', () => {
return new Response(
Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream.
{ headers: { 'content-type': 'text/html' } }
);
});
// Deprecated in Electron 25
protocol.registerHttpProtocol('some-protocol', () => {
callback({ url: 'https://electronjs.org' });
});

// Replace with
protocol.handle('some-protocol', () => {
return net.fetch('https://electronjs.org');
});
// Deprecated in Electron 25
protocol.registerFileProtocol('some-protocol', () => {
callback({ filePath: '/path/to/my/file' });
});

// Replace with
protocol.handle('some-protocol', () => {
return net.fetch('file:///path/to/my/file');
});

Obsoleto: BrowserWindow.setTrafficLightPosition(position)

BrowserWindow.setTrafficLightPosition(position) has been deprecated, the BrowserWindow.setWindowButtonPosition(position) API should be used instead which accepts null instead of { x: 0, y: 0 } to reset the position to system default.

// Deprecated in Electron 25
win.setTrafficLightPosition({ x: 10, y: 10 });
win.setTrafficLightPosition({ x: 0, y: 0 });

// Replace with
win.setWindowButtonPosition({ x: 10, y: 10 });
win.setWindowButtonPosition(null);

Obsoleto: BrowserWindow.getTrafficLightPosition()

BrowserWindow.getTrafficLightPosition() has been deprecated, the BrowserWindow.getWindowButtonPosition() API should be used instead which returns null instead of { x: 0, y: 0 } when there is no custom position.

// Deprecated in Electron 25
const pos = win.getTrafficLightPosition();
if (pos.x === 0 && pos.y === 0) {
// No custom position.
}

// Replace with
const ret = win.getWindowButtonPosition();
if (ret === null) {
// No custom position.
}

New Features

  • Added net.fetch(). #36733
    • net.fetch supports requests to file: URLs and custom protocols registered with protocol.register*Protocol. #36606
  • Added BrowserWindow.set/getWindowButtonPosition APIs. #37094
  • Added protocol.handle, replacing and deprecating protocol.{register,intercept}{String,Buffer,Stream,Http,File}Protocol. #36674
  • Added a will-frame-navigate event to webContents and the <webview> tag, which fires whenever any frame within the frame hierarchy attempts to navigate. #34418
  • Added initiator information to navigator events. This information allows distinguishing window.open from a parent frame causing a navigation, as opposed to a child-initiated navigation. #37085
  • Added net.resolveHost that resolves hosts using defaultSession object. #38152
  • Added new 'did-resign-active' event to app. #38018
  • Added several standard page size options to webContents.print(). #37159
  • Added the enableLocalEcho flag to the session handler ses.setDisplayMediaRequestHandler() callback for allowing remote audio input to be echoed in the local output stream when audio is a WebFrameMain. #37315
  • Added thermal management information to powerMonitor. #38028
  • Allows an absolute path to be passed to the session.fromPath() API. #37604
  • Exposes the audio-state-changed event on webContents. #37366

22.x.y Continued Support

As noted in Farewell, Windows 7/8/8.1, Electron 22's (Chromium 108) planned end of life date will be extended from May 30, 2023 to October 10, 2023. The Electron team will continue to backport any security fixes that are part of this program to Electron 22 until October 10, 2023. The October support date follows the extended support dates from both Chromium and Microsoft. On October 11, the Electron team will drop support back to the latest three stable major versions, which will no longer support Windows 7/8/8.1.

E25 (May'23)E26 (Aug'23)E27 (Oct'23)
25.x.y26.x.y27.x.y
24.x.y25.x.y26.x.y
23.x.y24.x.y25.x.y
22.x.y22.x.y--

Что дальше

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8.

You can find Electron's public timeline here.

More information about future changes can be found on the Planned Breaking Changes page.

Electron 24.0.0

· 4 мин. прочитано

Electron 24.0.0 вышел! Он включает обновления Chromium 112.0.5615.49, V8 11.2 и Node.js 18.14.0. Read below for more details!


Команда Electron рада объявить о выпуске Electron 24.0.0! You can install it with npm via npm install electron@latest or download it from our releases website. Continue reading for details about this release.

If you have any feedback, please share it with us on Twitter, or join our community Discord! Bugs and feature requests can be reported in Electron's issue tracker.

Notable Changes

Stack Changes

Критические изменения

Изменения в API: nativeImage.createThumbnailFromPath(path, size)

The maxSize parameter has been changed to size to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than maxSize, and macOS would always set the size to maxSize. Behavior is now the same across platforms.

// a 128x128 image.
const imagePath = path.join('path', 'to', 'capybara.png');

// Scaling up a smaller image.
const upSize = { width: 256, height: 256 };
nativeImage.createThumbnailFromPath(imagePath, upSize).then((result) => {
console.log(result.getSize()); // { width: 256, height: 256 }
});

// Scaling down a larger image.
const downSize = { width: 64, height: 64 };
nativeImage.createThumbnailFromPath(imagePath, downSize).then((result) => {
console.log(result.getSize()); // { width: 64, height: 64 }
});

New Features

  • Added the ability to filter HttpOnly cookies with cookies.get(). #37365
  • Added logUsage to shell.openExternal() options, which allows passing the SEE_MASK_FLAG_LOG_USAGE flag to ShellExecuteEx on Windows. The SEE_MASK_FLAG_LOG_USAGE flag indicates a user initiated launch that enables tracking of frequently used programs and other behaviors. #37291
  • Added types to the webRequest filter, adding the ability to filter the requests you listen to.#37427
  • Added a new devtools-open-url event to webContents to allow developers to open new windows with them. #36774
  • Added several standard page size options to webContents.print(). #37265
  • Added the enableLocalEcho flag to the session handler ses.setDisplayMediaRequestHandler() callback for allowing remote audio input to be echoed in the local output stream when audio is a WebFrameMain. #37528
  • Allow an application-specific username to be passed to inAppPurchase.purchaseProduct(). #35902
  • Exposed window.invalidateShadow() to clear residual visual artifacts on macOS. #32452
  • Whole-program optimization is now enabled by default in electron node headers config file, allowing the compiler to perform opimizations with information from all modules in a program as opposed to a per-module (compiland) basis. #36937
  • SystemPreferences::CanPromptTouchID (macOS) now supports Apple Watch. #36935

End of Support for 21.x.y

Electron 21.x.y has reached end-of-support as per the project's support policy. Developers and applications are encouraged to upgrade to a newer version of Electron.

As noted in Farewell, Windows 7/8/8.1, Electron 22's (Chromium 108) planned end of life date will be extended from May 30, 2023 to October 10, 2023. The Electron team will continue to backport any security fixes that are part of this program to Electron 22 until October 10, 2023.

E24 (Apr'23)E25 (May'23)E26 (Aug'23)
24.x.y25.x.y26.x.y
23.x.y24.x.y25.x.y
22.x.y23.x.y24.x.y
--22.x.y22.x.y

Что дальше

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8.

You can find Electron's public timeline here.

More information about future changes can be found on the Planned Breaking Changes page.

10 лет с Electron 🎉

· 9 мин. прочитано

Первый коммит в репозитории electron/electron был совершен 13 марта 2013 года1.

Первый коммит на electron/electron от @aroben

После 10 лет и 27,147 коммитов от 1,192 различных участников, на сегодняшний день Electron стал одним из самых популярных фреймворков для создания настольных приложений. Этот этап - идеальная возможность отметить, посмотреть на наше приключение и поделиться тем, что мы выучили на этом пути.

Мы бы не были тут сегодня без всех тех, кто посвятил свои время и усилия, чтобы внести свой вклад в проект. Хотя коммиты исходного кода всегда являются самой видимой частью, мы также должны быть признательны усилиям тех людей, что сообщают об ошибках, поддерживают пользовательские модули, предоставляют документацию и переводы, а также участвуют в сообществе Electron в киберпространстве. Каждый вклад неоценим для нас, разработчиков.

Перед тем, как мы продолжим, хотим сказать: спасибо. ❤️

Как мы сюда попали?

Atom Shell был разработан как основа Atom editor для GitHub'а, который вступил в открытую бету в апреле 2014 года. Он был разработан с нуля в качестве альтернативы веб-платформам, доступным в то время (node-webkit и Chromium Embedded Framework). У него была главная черта: встроенный Node.js и Chromium для обеспечения высокой производительности веб-технологий.

В течение года Atom Shell начал приобретать огромный рост как в возможностях, так и в популярности. Большие компании, стартапы и отдельные разработчики начали создавать приложения с этой технологией (некоторые ранние версии, включая Slack, GitKraken и WebTorrent) и проект был вскоре переименован в Electron.

С тех пор и появился Electron, и никогда не останавливался. Вот, к примеру, наш недельный счетчик количества загрузок, любезно представленная npmtrends.com:

Недельный график загрузок Electron

Первая версия Electron была выпущена в 2016 году и обещала увеличение стабильности API, улучшенные документацию и инструменты. Вторая версия Electron была выпущена в 2018 году и предоставляла семантический учет версий, делая учет циклов выпуска версий Electron для разработчиков легче.

К шестой версии Electron, мы перешли к 12-ти недельному циклу выпуска больших обновлений, чтобы синхронизироваться с Chromium. Это решение поменяло и отношение к проекту, возводя "наличие последней версии Chromium" вместо "лучше бы был" в приоритет. Это уменьшило количество технологических задержек между обновлениями, облегчая для нас хранение Electron обновленным и безопасным.

С тех времен, мы были трудоголиками, выпуская новую версию Electron в тот же день, как и Chromium. К моменту, когда Chromium уменьшил время между выпусками до 4 недель в 2021, мы лишь пожали плечами и увеличили наш цикл обновлений до 8 недель соответственно.

Теперь мы на Electron v23 (счет продолжается) и до сих пор преданны созданию лучшей среды создания настольных предложений для различных платформ. Даже учитывая бум создания JavaScript инструментов для разработчиков в последние годы, Electron остался стабильным, протестированным в боях украшением структуры для настольных приложений. Приложения Electron на сегодняшний день являются повсеместными: вы можете программировать с помощью Visual Studio Code, проектировать дизайн с Figma, общаться со Slack и делать заметки с Notion (среди многих других вариантов). Мы невероятно гордимся этим достижением и благодарны каждому, кто сделал это возможным.

Чему мы научились на этом пути?

Путь к отметке десяти лет был долгий и извилистый. Вот несколько ключевых вещей, которые помогли нам поддерживать стабильность огромного проекта с открытым исходным кодом.

Масштабирование распределенных решений с помощью модели управления

Одной из сложных задач, которую нам пришлось преодолеть, стала разработка направления проекта, как только Electron впервые получил огромную популярность. Как мы справляемся с организацией команды, составляющей несколько десятков инженеров, распределенных между компаниями, странами и временными зонами?

В первые дни, группа, поддерживающая Electron, опиралась на неформальную координацию, что было быстро и легко для небольших проектов, но не могло расширять сотрудничество. В 2019 году, мы перешли на модель управления, в котором различные рабочие группы имели формальные сферы ответственности. Это было полезно в упрощении процессов и присвоении частей работы к определенным людям, поддерживающим проект. За что отвечают Working Group (WG) на сегодняшний день?

  • Выпуском версий Electron (Releases WG)
  • Обновлением Chromium и Node.js (Upgrades WG)
  • Управлением публичным дизайном API (API WG)
  • Поддержка защиты Electron (Security WG)
  • Поддержка вебсайта, документации и инструментария (Ecosystem WG)
  • Общественная и корпоративная связь (Outreach WG)
  • Модерация сообщества (Community & Safety WG)
  • Поддержка нашей инфраструктуры, инструментов поддержки и облачных сервисов (Infrastructure WG)

Примерно в то же время, как мы сменили модель управления, мы также поменяли владельца с GitHub'а на OpenJS Foundation. Хоть и первоначальная основная команда по-прежнему работает в Microsoft сегодня, они являются лишь частью более крупной группы сотрудников, которые формируют управление Electron. 2

Хотя эта модель и не является идеальной, она хорошо поработала во время глобальной пандемии и текущих макроэкономических потрясений. Заходя наперед, мы планируем пересмотреть управленческий устав, чтобы он повел нас вперед ко второму десятилетию Electron.

информация

Если вы хотите узнать больше, посмотрите репозиторий electron/governance!

Сообщество

Вклад сообщества в открытый исходный код огромно, особенно когда наша команда по связи с сообществом составляет десятки инженеров с припиской "менеджер сообщества". Тем не менее, быть огромным проектом с открытым исходным кодом означает наличие огромного числа пользователей, и использование их энергии построения пользовательской экосистемы Electron является важнейшей составляющей поддержки здоровья проекта.

Что мы делаем для развития поддержки связи с сообществом?

Создание виртуальных сообществ

  • В 2020 году мы запустили наш Discord сервер. Ранее у нас был раздел на форуме Atom, однако мы решили использовать более неформальную платформу для ведения дискуссий между людьми, поддерживающими проект и разработчиками Electron, а также для общей информационной помощи в исправлении ошибок.
  • В 2021 году мы создали пользовательскую группу Electron China с помощью @BlackHole1. Эта группа играла важную роль в развитии Electron для пользователей из китайской быстрорастущей технологической сцены, предоставляя им место для обмена идеями и обсуждения Electron за пределами англоговорящего сообщества. Мы также хотели бы поблагодарить cnpm за работу и поддержку ночных обновлений Electron в китайском зеркале для npm.

Участие в известных и открытых мероприятиях

  • Мы празднуем Hacktoberfest каждый год, начиная с 2019. Hacktoberfest это ежегодное мероприятие, посвященное проектам с открытым исходным кодом, организованное DigitalOcean, и мы получаем десятки энтузиастов каждый год, жаждущих оставить свой след на ПО с открытым исходным кодом.
  • В 2020 году мы участвовали в первой части Google Season of Docs, где мы работали вместе с @bandantonio, чтобы переработать учебный процесс Electron для новых пользователей.
  • В 2022 году мы начали обучать студентов Google Summer of Code в первый раз. @aryanshridhar провела невероятную работу, чтобы переработать основную версию Electron Fiddle, а именно: переработать загрузочную логику и перенести ее сборщик на webpack.

Автоматизация производства!

Сегодня, команда управления Electron составляет около 30 активных разработчиков. Меньше чем половина из нас работают над проектом полный рабочий день, а это значит, что у нас впереди еще много работы. Что мы делаем для поддержки быстрой работоспособности? Наш девиз заключается в том, что компьютеры - вещь дешевая, а человеческое время - вещь дорогая. Ну как типичные инженеры, мы разработали автоматический инструментарий поддержки для облегчения нашей жизни.

Not Goma

Ядро кода Electron - это код на C++, от чего время сборки всегда играл ограничивающий фактор в том, насколько быстро мы могли исправлять ошибки и добавлять новые возможности. В 2020 году мы запустили Not Goma, особый, направленный на язык Electron, бэкенд для распределенного компилятора Goma от Google. Not Goma обрабатывает заявки от авторизированных пользовательских машин, и распределяет процесс между сотнями ядер в бэкенде. Она также сохраняет результат компиляции для того, чтобы другому человеку, который компилирует те же файлы, надо было только загрузить предварительно скомпилированный результат.

С момента запуска Not Goma, время компиляции для поддержки сократилась с масштаба часов до масштабов минут. Стабильное интернет-соединение стало минимальным требованием для разработчиков, чтобы компилировать Electron!

информация

Если вы участник проекта с открытым исходным кодом, вы также можете попробовать доступный только для просмотра кэш Not Goma, который доступен по умолчанию с Electron Build Tools.

Фактор Непрерывной Аутентификации

Continuous Factor Authentication (CFA) является автоматизированным слоем вокруг Двухфакторной Аутентификационной (2FA) системы npm, которую мы комбинируем с семантическим обновлением для управления безопасностью и автоматическим выпуском обновлений различных пакетов npm для @electron/.

Хоть семантический выпуск версий уже автоматизирует процесс публикации npm пакетов, он требует выключения двухфакторной аутентификации или секретный токен, который обходит это ограничение.

Мы создали CFA для предоставления одноразового пароля на основе времени (TOTP) для npm 2FA с целью произвольной работы Cl, что позволяет нам использовать автоматический семантический выпуск, сохраняя при этом дополнительный слой безопасности в виде двухфакторной аутентификации.

Мы используем CFA в интеграции с фронтендом Slack, что позволяет разработчикам проверять публикацию пакетов с любого устройства, в котором есть Slack до тех пор, пока у них есть свой генератор TOTP.

информация

Если вы хотите попробовать CFA в ваших проектах, смотрите репозиторий на GitHub или документацию! Если вы используете CircleCL как ваш Cl провайдер, мы имеем также удобный npm orb чтобы быстро построить проект с CFA.

Sheriff

Sheriff это инструмент с открытым исходным кодом, который мы написали для автоматизации управления правами доступа в GitHub, Slack и Google Workspace.

Ключевая особенность Sheriff - управление правами доступа является прозрачным процессом. Он использует один конфигурационный файл YAML, который определяет права на все платформы, перечисленные выше. С Sheriff, получение статуса соавтора в репозитории или создание нового списка рассылок становится таким же легким, как и получение одобрения и слияния PR.

У Sheriff также есть журнал аудита, который отправляет сообщение в Slack, предупреждая администраторов о подозрительной активности внутри организации Electron.

...и всех наших ботов на GitHub

GitHub это платформа с богатым количеством расширений API и их собственной автоматической структурой для создания приложений под названием Probot. Чтобы помочь нам сфокусироваться на более творческих частях нашей работы, мы создали набор маленьких ботов, которые выполняют за нас нашу грязную работу. Вот несколько примеров:

  • Sudowoodo автоматизирует процесс выпуска Electron с начала и до конца, от отказа от определенных сборок и до загрузки финальных ресурсов в GitHub и npm.
  • Trop автоматизирует бэкпортинг Electron, пытаясь выбрать только лучшие изменения веток предыдущих обновлений, основанные на метках GitHub PR.
  • Roller автоматизирует ротационные обновления дополнений для Chromium и Node.js, которые требуются в Electron.
  • Cation это бот для проверки статуса electron/electron PR.

В целом, наша маленькая семейка ботов дала нам огромное ускорение производительности разработчиков!

What’s next?

Вступая в наше второе десятилетие, вы можете спросить: "А что дальше будет с Electron?"

Мы будем синхронизироваться с выпуском изменений Chromium, выпуская большие обновления для Electron каждые 8 недель, держа его обновленной и выбирая только лучшее из веб-платформ и Node.js, пока поддерживаем стабильность и безопасность приложений для предприятий.

Мы сообщаем о предстоящих инициативах, как только они обретут конкретные очертания. Если вы хотите быть в курсе будущих обновлений и общих обновлений проекта, вы можете читать нас в нашем блоке, а также подписаться на нас в социальных сетях (Twitter и Mastodon)!

Footnotes

  1. Это на самом деле первый коммит из electron-archive/brightray project, который был поглощён Electron в 2017 году, его git история была объединена. Но кто подсчитывает? Это наше день рождения, так что мы устанавливаем правила!

  2. Вопреки распространенному мнению, Electron больше не принадлежит GitHub или Microsoft и в настоящее время является частью Open Js Foundation.

Electron 23.0.0

· 3 мин. прочитано

Electron 23.0.0 вышел! Он включает обновления Chromium 110, V8 11.0 и Node.js 18.12.1. Additionally, support for Windows 7/8/8.1 has been dropped. Read below for more details!


Команда Electron рада объявить о выпуске Electron 23.0.0! You can install it with npm via npm install electron@latest or download it from our releases website. Continue reading for details about this release.

If you have any feedback, please share it with us on Twitter, or join our community Discord! Bugs and feature requests can be reported in Electron's issue tracker.

Notable Changes

Stack Changes

New Features

  • Added label property to Display objects. #36933
  • Added an app.getPreferredSystemLanguages() API to return the user's system languages. #36035
  • Added support for the WebUSB API. #36289
  • Added support for SerialPort.forget() as well as a new event serial-port-revoked emitted on Session objects when a given origin is revoked. #35310
  • Added new win.setHiddenInMissionControl API to allow developers to opt out of Mission Control on macOS. #36092

Dropping Windows 7/8/8.1 Support

Electron 23 no longer supports Windows 7/8/8.1. Electron follows the planned Chromium deprecation policy, which will deprecate Windows 7/8/8.1 , as well as Windows Server 2012 and 2012 R2 support in Chromium 109 (read more here).

Критические изменения в API

Below are breaking changes introduced in Electron 23. You can read more about these changes and future changes on the Planned Breaking Changes page.

Removed: BrowserWindow scroll-touch-* events

The deprecated scroll-touch-begin, scroll-touch-end and scroll-touch-edge events on BrowserWindow have been removed. Instead, use the newly available input-event event on WebContents.

// Removed in Electron 23.0
-win.on('scroll-touch-begin', scrollTouchBegin)
-win.on('scroll-touch-edge', scrollTouchEdge)
-win.on('scroll-touch-end', scrollTouchEnd)

// Replace with
+win.webContents.on('input-event', (_, event) => {
+ if (event.type === 'gestureScrollBegin') {
+ scrollTouchBegin()
+ } else if (event.type === 'gestureScrollUpdate') +{
+ scrollTouchEdge()
+ } else if (event.type === 'gestureScrollEnd') {
+ scrollTouchEnd()
+ }
+})

End of Support for 20.x.y

Electron 20.x.y has reached end-of-support as per the project's support policy. Developers and applications are encouraged to upgrade to a newer version of Electron.

E22 (Nov'22)E23 (Feb'23)E24 (Apr'23)E25 (May'23)E26 (Aug'23)
22.x.y23.x.y24.x.y25.x.y26.x.y
21.x.y22.x.y23.x.y24.x.y25.x.y
20.x.y21.x.y22.x.y23.x.y24.x.y

Что дальше

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8.

You can find Electron's public timeline here.

More information about future changes can be found on the Planned Breaking Changes page.

Electron 22.0.0

· 5 мин. прочитано

Electron 22.0.0 вышел! It includes a new utility process API, updates for Windows 7/8/8.1 support, and upgrades to Chromium 108, V8 10.8, and Node.js 16.17.1. Read below for more details!


Команда Electron рада объявить о выпуске Electron 22.0.0! You can install it with npm via npm install electron@latest or download it from our releases website. Continue reading for details about this release.

If you have any feedback, please share it with us on Twitter, or join our community Discord! Bugs and feature requests can be reported in Electron's issue tracker.

Notable Changes

Stack Changes

Highlighted Features

UtilityProcess API #36089

The new UtilityProcess main process module allows the creation of a lightweight Chromium child process with only Node.js integration while also allowing communication with a sandboxed renderer using MessageChannel. The API was designed based on Node.js child_process.fork to allow for easier transition, with one primary difference being that the entry point modulePath must be from within the packaged application to allow only for trusted scripts to be loaded. Additionally the module prevents establishing communication channels with renderers by default, upholding the contract in which the main process is the only trusted process in the application.

You can read more about the new UtilityProcess API in our docs here.

Windows 7/8/8.1 Support Update

информация

2023/02/16: An update on Windows Server 2012 support

Last month, Google announced that Chrome 109 would continue to receive critical security fixes for Windows Server 2012 and Windows Server 2012 R2 until October 10, 2023. In accordance, Electron 22's (Chromium 108) planned end of life date will be extended from May 30, 2023 to October 10, 2023. The Electron team will continue to backport any security fixes that are part of this program to Electron 22 until October 10, 2023.

Note that we will not make additional security fixes for Windows 7/8/8.1. Also, Electron 23 (Chromium 110) will only function on Windows 10 and above as previously announced.

Electron 22 will be the last Electron major version to support Windows 7/8/8.1. Electron follows the planned Chromium deprecation policy, which will deprecate Windows 7/8/8.1 support in Chromium 109 (read more here).

Windows 7/8/8.1 will not be supported in Electron 23 and later major releases.

Additional Highlighted Changes

  • Added support for Web Bluetooth pin pairing on Linux and Windows. #35416
  • Added LoadBrowserProcessSpecificV8Snapshot as a new fuse that will let the main/browser process load its v8 snapshot from a file at browser_v8_context_snapshot.bin. Any other process will use the same path as is used today. #35266
  • Added WebContents.opener to access window opener and webContents.fromFrame(frame) to get the WebContents corresponding to a WebFrameMain instance. #35140
  • Added support for navigator.mediaDevices.getDisplayMedia via a new session handler, ses.setDisplayMediaRequestHandler. #30702

Критические изменения в API

Below are breaking changes introduced in Electron 22. You can read more about these changes and future changes on the Planned Breaking Changes page.

Obsoleto: webContents.incrementCapturerCount(stayHidden, stayAwake)

webContents.incrementCapturerCount(stayHidden, stayAwake) has been deprecated. It is now automatically handled by webContents.capturePage when a page capture completes.

const w = new BrowserWindow({ show: false })

- w.webContents.incrementCapturerCount()
- w.capturePage().then(image => {
- console.log(image.toDataURL())
- w.webContents.decrementCapturerCount()
- })

+ w.capturePage().then(image => {
+ console.log(image.toDataURL())
+ })

Obsoleto: webContents.decrementCapturerCount(stayHidden, stayAwake)

webContents.decrementCapturerCount(stayHidden, stayAwake) has been deprecated. It is now automatically handled by webContents.capturePage when a page capture completes.

const w = new BrowserWindow({ show: false })

- w.webContents.incrementCapturerCount()
- w.capturePage().then(image => {
- console.log(image.toDataURL())
- w.webContents.decrementCapturerCount()
- })

+ w.capturePage().then(image => {
+ console.log(image.toDataURL())
+ })

Removed: WebContents new-window event

The new-window event of WebContents has been removed. Заменяется на webContents.setWindowOpenHandler().

- webContents.on('new-window', (event) => {
- event.preventDefault()
- })

+ webContents.setWindowOpenHandler((details) => {
+ return { action: 'deny' }
+ })

Deprecated: BrowserWindow scroll-touch-* events

The scroll-touch-begin, scroll-touch-end and scroll-touch-edge events on BrowserWindow are deprecated. Instead, use the newly available input-event event on WebContents.

// Deprecated
- win.on('scroll-touch-begin', scrollTouchBegin)
- win.on('scroll-touch-edge', scrollTouchEdge)
- win.on('scroll-touch-end', scrollTouchEnd)

// Replace with
+ win.webContents.on('input-event', (_, event) => {
+ if (event.type === 'gestureScrollBegin') {
+ scrollTouchBegin()
+ } else if (event.type === 'gestureScrollUpdate') {
+ scrollTouchEdge()
+ } else if (event.type === 'gestureScrollEnd') {
+ scrollTouchEnd()
+ }
+ })

End of Support for 19.x.y

Electron 19.x.y has reached end-of-support as per the project's support policy. Developers and applications are encouraged to upgrade to a newer version of Electron.

E19 (May'22)E20 (Aug'22)E21 (Sep'22)E22 (Nov'22)E23 (Jan'23)
19.x.y20.x.y21.x.y22.x.y23.x.y
18.x.y19.x.y20.x.y21.x.y22.x.y
17.x.y18.x.y19.x.y20.x.y21.x.y

Что дальше

The Electron project will pause for the the month of December 2022, and return in January 2023. More information can be found in the December shutdown blog post.

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8.

You can find Electron's public timeline here.

More information about future changes can be found on the Planned Breaking Changes page.

Farewell, Windows 7/8/8.1

· 3 мин. прочитано

Electron will end support of Windows 7, Windows 8 and Windows 8.1 beginning in Electron 23.


In line with Chromium’s deprecation policy, Electron will end support of Windows 7, Windows 8 and Windows 8.1 beginning in Electron 23. This matches Microsoft's end of support for Windows 7 ESU and Windows 8.1 extended on January 10th, 2023.

Electron 22 will be the last Electron major version to support Windows versions older than 10. Windows 7/8/8.1 will not be supported in Electron 23 and later major releases. Older versions of Electron will continue to function on Windows 7, and we will continue to release patches for Electron the 22.x series until May 30 2023, when Electron will end support for 22.x (according to our support timeline).

Why deprecate?

Electron follows the planned Chromium deprecation policy, which will deprecate support in Chromium 109 (read more about Chromium's timeline here). Electron 23 will contain Chromium 110, which won’t support older versions of Windows.

Electron 22, which contains Chromium 108, will thus be the last supported version.

Deprecation timeline

The following is our planned deprecation timeline:

  • December 2022: The Electron team is entering a quiet period for the holidays
  • January 2023: Windows 7 & 8 related issues are accepted for all supported release branches.
  • February 7 2023: Electron 23 is released.
  • February 8 2023 - May 29 2023: Electron will continue to accept fixes for supported lines older than Electron 23.
  • May 30 2023: Electron 22 reaches the end of its support cycle.

What this means for developers:

  • The Electron team will accept issues and fixes related to Windows 7/8/8.1 for stable supported lines, until each line reaches the end of its support cycle.
    • This specifically applies to Electron 22, Electron 21 and Electron 20.
  • New issues related to Windows 7/8/8.1 will be accepted for Electron versions older than Electron 23.
    • New issues will not be accepted for any newer release lines.
  • Once Electron 22 has reached the end of its support cycle, all existing issues related to Windows 7/8/8.1 will be closed.
информация

2023/02/16: An update on Windows Server 2012 support

Last month, Google announced that Chrome 109 would continue to receive critical security fixes for Windows Server 2012 and Windows Server 2012 R2 until October 10, 2023. In accordance, Electron 22's (Chromium 108) planned end of life date will be extended from May 30, 2023 to October 10, 2023. The Electron team will continue to backport any security fixes that are part of this program to Electron 22 until October 10, 2023.

Note that we will not make additional security fixes for Windows 7/8/8.1. Also, Electron 23 (Chromium 110) will only function on Windows 10 and above as previously announced.

What's next

Please feel free to write to us at info@electronjs.org if you have any questions or concerns. You can also find community support in our official Electron Discord.

A Quiet Place Part II (Dec'22)

· Одна мин. чтения

The Electron project will pause for the month of December 2022, then return to full speed in January 2023.

via GIPHY


What will be the same in December

  1. Zero-day and other major security-related releases will be published as necessary. Security incidents should be reported via SECURITY.md.
  2. Code of Conduct reports and moderation will continue.

What will be different in December

  1. No new Stable releases in December. No Nightly and Alpha releases for the last two weeks of December.
  2. With few exceptions, no pull request reviews or merges.
  3. No issue tracker updates on any repositories.
  4. No Discord debugging help from maintainers.
  5. No social media content updates.

Why is this happening?

With the success of December Quiet Month 2021, we wanted to bring it back for 2022. December continues to be a quiet month for most companies, so we want to give our maintainers a chance to recharge. Everyone is looking forward to 2023, and we expect good things to come! We encourage other projects to consider similar measures.

Представляем Electron Forge 6

· 6 мин. прочитано

Мы рады сообщить, что вышел Electron Forge v6.0.0! This release marks the first major release of Forge since 2018 and moves the project from electron-userland into the main electron organization on Github.

Продолжайте чтение, чтобы узнать о новинках и как ваше приложение может внедрить Electron Forge!

Что такое Electron Forge?

Electron Forge is a tool for packaging and distributing Electron applications. It unifies Electron's build tooling ecosystem into a single extensible interface so that anyone can jump right into making Electron apps.

Highlight features include:

  • 📦 Application packaging and code signing
  • 🚚 Customizable installers on Windows, macOS, and Linux (DMG, deb, MSI, PKG, AppX, etc.)
  • ☁️ Automated publishing flow for cloud providers (GitHub, S3, Bitbucket, etc.)
  • ⚡️ Easy-to-use boilerplate templates for webpack and TypeScript
  • ⚙️ Native Node.js module support
  • 🔌 Extensible JavaScript plugin API
Дальнейшее изучение

Visit the Why Electron Forge explainer document to learn more about Forge's philosophy and architecture.

What's new in v6?

Completely rewritten

From v1 to v5, Electron Forge was based on the now-discontinued electron-compile project. Forge 6 is a complete rewrite of the project with a new modular architecture that can be extended to meet any Electron application's needs.

In the past few years, Forge v6.0.0-beta has achieved feature parity with v5 and code churn has slowed down dramatically, making the tool ready for general adoption.

Don't install the wrong package

For versions 5 and below, Electron Forge was published to the electron-forge package on npm. Starting with the v6 rewrite, Forge is instead structured as a monorepo project with many smaller projects.

Officially supported

Historically, Electron maintainers have been unopinionated about build tooling, leaving the task to various community packages. However, with Electron maturing as a project, it has become harder for new Electron developers to understand which tools they need to build and distribute their apps.

To help guide Electron developers in the distribution process, we have have decided to make Forge the official batteries-included build pipeline for Electron.

Over the past year, we have been slowly integrating Forge into the official Electron documentation, and we have recently moved Forge over from its old home in electron-userland/electron-forge to the electron/forge repo. Now, we are finally ready to release Electron Forge to a general audience!

Начало работы

Initializing a new Forge project

Scaffolding a new Electron Forge project can be done using the create-electron-app CLI script.

yarn create electron-app my-app --template=webpack
cd my-app
yarn start

The script will create an Electron project in the my-app folder with completely JavaScript bundling and a preconfigured build pipeline.

For more info, see the Getting Started guide in the Forge docs.

First-class webpack support

The above snippet uses Forge's Webpack Template, which we recommend as a starting point for new Electron projects. This template is built around the @electron-forge/plugin-webpack plugin, which integrates webpack with Electron Forge in a few ways, including:

  • enhancing local dev flow with webpack-dev-server, including support for HMR in the renderer;
  • handling build logic for webpack bundles before application packaging; and
  • adding support for Native Node modules in the webpack bundling process.

Если вам нужна поддержка TypeScript, попробуйте вместо этого использовать Webpack + TypeScript Template.

Importing an existing project

The Electron Forge CLI also contains an import command for existing Electron projects.

cd my-app
yarn add --dev @electron-forge/cli
yarn electron-forge import

When you use the import command, Electron Forge will add a few core dependencies and create a new forge.config.js configuration. If you have any existing build tooling (e.g. Electron Packager, Electron Builder, or Forge 5), it will try to migrate as many settings as possible. Some of your existing configuration may need to be migrated manually.

Manual migration details can be found in the Forge import documentation. If you need help, please stop by our Discord server!

Why switch to Forge?

If you already have tooling for packaging and publishing your Electron app, the benefits associated with adopting Electron Forge can still outweigh the initial switching cost.

We believe there are two main benefits to using Forge:

  1. Forge receives new features for application building as soon as they are supported in Electron. In this case, you won't need to wire in new tooling support yourself, or wait for that support to be eventually implemented by other packages before upgrading. For recent examples, see macOS universal binaries and ASAR integrity checking.

  2. Forge's multi-package architecture makes it easy to understand and extend. Since Forge is made up of many smaller packages with clear responsibilities, it is easier to follow code flow. In addition, Forge's extensible API design means that you can write your own additional build logic separate from the provided configuration options for advanced use cases. For more details on writing custom Forge plugins, makers, and publishers, see the Extending Electron Forge section of the docs.

Важные изменения

Forge 6 has spent a long time in the beta phase, and its release cadence has gradually slowed down. However, we have accelerated development in the second half of 2022 and used the last few releases to push some final breaking changes before the v6.0.0 stable release.

If you are an Electron Forge 6 beta user, see the v6.0.0 GitHub release notes for a list of breaking changes made in recent betas (>=6.0.0-beta.65).

A complete list of changes and commits can be found in the repo's CHANGELOG.md.

Submit your feedback!

Tell us what you need! The Electron Forge team is always looking to build the project to better suit its users.

You can help us improve Electron Forge by submitting feature requests, posting issues, or just letting us know your feedback! You can also join us in the official Electron Discord server, where there is a dedicated channel for Electron Forge discussion.

If you want to give any feedback on the Forge docs at https://electronforge.io, we have a GitBook instance synced to the electron-forge/electron-forge-docs repo.