Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36c76c6934 | ||
|
|
e10a95d4df | ||
|
|
0fceb1ebbf | ||
|
|
07aa70b379 |
@@ -1,5 +1,23 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"application": {
|
||||
"downloads": [
|
||||
{
|
||||
"id": "macos-arm64",
|
||||
"platform": "macOS",
|
||||
"architecture": "Apple Silicon",
|
||||
"kind": "direct",
|
||||
"url": "https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg",
|
||||
"badge": {
|
||||
"path": "docs/assets/download-macos.png",
|
||||
"sha256": "687db572c2d1a5fc42684a8c94ec1c4df960c6369616ff0ca10990b553008ae8",
|
||||
"width": 180
|
||||
}
|
||||
}
|
||||
],
|
||||
"releases_url": "https://github.com/zarubinvibe/iriz/releases/latest",
|
||||
"checksums_url": "https://github.com/zarubinvibe/iriz/releases/latest/download/SHA256SUMS.txt"
|
||||
},
|
||||
"owner": "zarubinvibe",
|
||||
"slug": "iriz",
|
||||
"license_badge": "MIT",
|
||||
@@ -14,7 +32,21 @@
|
||||
"en": {
|
||||
"title": "iriz",
|
||||
"name": "iriz",
|
||||
"tagline": "Speak out loud and the text appears. Speech recognition runs on your Mac; sending text to an agent is a separate choice.\n\n[](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)\n\nApple Silicon · macOS 14+ · Model download: about 500 MB\n\n[Install & first dictation](docs/DOWNLOAD.md) · [Release notes](https://github.com/zarubinvibe/iriz/releases/latest)\n\nSelf-signed; not notarized by Apple. Intel is not supported by this download.",
|
||||
"tagline": "Speak out loud and the text appears. Speech recognition runs on your Mac; sending text to an agent is a separate choice.",
|
||||
"application": {
|
||||
"downloads": {
|
||||
"macos-arm64": {
|
||||
"label": "Download for macOS",
|
||||
"requirements": "macOS 14+ · DMG"
|
||||
}
|
||||
},
|
||||
"setup": "At first launch, choose Download and install Parakeet to download the speech model (about 500 MB).",
|
||||
"security": "Self-signed; not notarized by Apple. Intel is not supported by this download.",
|
||||
"guide": {
|
||||
"label": "Install & first dictation",
|
||||
"url": "docs/DOWNLOAD.md"
|
||||
}
|
||||
},
|
||||
"hero_alt": "Iris in white marble with marble wings beside the classical column, a gold ribbon of voice landing in the groove of her tablet",
|
||||
"what": "This is a Mac app that types for you while you talk.\n\nHere is how it goes. You press one key, speak in your normal voice, press it again. The text lands where the cursor was: in an email, in a chat, in a search field. Nothing to switch to, no separate window.\n\nWhat sets it apart from similar apps is where the speech is decoded. Usually your voice travels to somebody's server, turns into text there and comes back. Here your Mac does the work, and the audio never leaves the machine.\n\n**Why «iriz».** Iris was the messenger of the Greek gods and the rainbow — a bridge between the sky and the ground. She does not invent the message, she carries it whole. The name reflects the job: carrying speech into text. Automatic recognition can still mishear words, so check the result.\n\n\n\nIt does more. It fixes a phrase typed in the wrong keyboard layout. Correct a word after pasting and the app offers to remember the replacement. Ordinary dictation can remove hesitations and repetitions.\n\nMeetings keep the original recognition text and the audio. The DOCX contains minutes first, then the full available transcript on a new page; the same folder includes JSON and a list of details to check. Filling decisions and action items through your selected agent requires separate consent to send the text. Unknown details stay explicit, and the result remains a draft. [Processing a meeting](docs/MEETINGS.md).\n\n\n\n\n",
|
||||
"why": "Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.\n\nOne thing gets in the way. Cloud dictation cleans speech better than anything local, but what you said leaves the machine: a client call, a draft, names and figures. For a doctor, a lawyer, a therapist, that trade never pays off.\n\nSo here your Mac does the decoding, and the app reaches the network only when you press the button.\n\n\n",
|
||||
@@ -116,7 +148,21 @@
|
||||
"ru": {
|
||||
"title": "iriz",
|
||||
"name": "iriz",
|
||||
"tagline": "Говори вслух, на экране появляется текст. Речь разбирает твой Мак. Передачу текста агенту ты разрешаешь отдельно.\n\n[](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)\n\nApple Silicon · macOS 14+ · Модель скачивается отдельно: около 500 МБ\n\n[Установка и первая диктовка](docs/DOWNLOAD.ru.md) · [Что изменилось](https://github.com/zarubinvibe/iriz/releases/latest)\n\nСамоподпись, без нотаризации Apple. Этот выпуск не поддерживает Intel.",
|
||||
"tagline": "Говори вслух, на экране появляется текст. Речь разбирает твой Мак. Передачу текста агенту ты разрешаешь отдельно.",
|
||||
"application": {
|
||||
"downloads": {
|
||||
"macos-arm64": {
|
||||
"label": "Скачать для macOS",
|
||||
"requirements": "macOS 14+ · DMG"
|
||||
}
|
||||
},
|
||||
"setup": "При первом запуске нажми «Скачать и установить Parakeet»: модель речи скачивается отдельно, около 500 МБ.",
|
||||
"security": "Самоподпись, без нотаризации Apple. Этот выпуск не поддерживает Intel.",
|
||||
"guide": {
|
||||
"label": "Установка и первая диктовка",
|
||||
"url": "docs/DOWNLOAD.ru.md"
|
||||
}
|
||||
},
|
||||
"hero_alt": "Ирида из белого мрамора с мраморными крыльями у классической колонны, золотая лента голоса ложится в борозду на табличке",
|
||||
"what": "Это программа для Мака, которая печатает за тебя, пока ты говоришь.\n\nРаботает так. Ты нажимаешь одну клавишу, говоришь обычным голосом, нажимаешь еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет.\n\nГлавное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает твой Мак, и звук с машины не уходит.\n\n**Почему «iriz».** Ирида у греков - вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Отсюда и задача программы: переносить речь в текст. Распознавание может ошибаться, поэтому результат нужно проверить.\n\n\n\nУмеет и другое. Чинит фразу, набранную не в той раскладке. Поправишь слово после вставки, и программа предложит запомнить замену. В обычной диктовке может убрать запинки и повторы.\n\nУ встреч другой порядок: исходная расшифровка не редактируется, звук сохраняется рядом. DOCX содержит сначала протокол, затем полную доступную расшифровку с новой страницы; рядом лежат JSON и список уточнений. Заполнение решений и поручений через выбранного агента требует отдельного согласия на передачу текста. Неизвестные сведения отмечаются явно, результат остается черновиком. [Как обработать встречу](docs/MEETINGS.md).\n\n\n\n\n",
|
||||
"why": "Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.\n\nМешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает сказанное: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем.\n\nПоэтому тут разбирает Мак, а в сеть программа ходит только по твоей кнопке.\n\n\n",
|
||||
@@ -218,7 +264,21 @@
|
||||
"zh": {
|
||||
"title": "iriz",
|
||||
"name": "iriz",
|
||||
"tagline": "你说出来,屏幕上就有字。语音识别在你的 Mac 上完成;向代理发送文本需要你另行同意。\n\n[](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)\n\nApple Silicon · macOS 14+ · 语音模型需另行下载,约 500 MB\n\n[安装与首次听写](docs/DOWNLOAD.zh.md) · [更新说明](https://github.com/zarubinvibe/iriz/releases/latest)\n\n应用使用自签名,尚未通过 Apple 公证。此下载不支持 Intel。",
|
||||
"tagline": "你说出来,屏幕上就有字。语音识别在你的 Mac 上完成;向代理发送文本需要你另行同意。",
|
||||
"application": {
|
||||
"downloads": {
|
||||
"macos-arm64": {
|
||||
"label": "下载 macOS 版",
|
||||
"requirements": "macOS 14+ · DMG"
|
||||
}
|
||||
},
|
||||
"setup": "首次启动时,选择下载并安装 Parakeet。语音模型需另行下载,约 500 MB。",
|
||||
"security": "应用使用自签名,尚未通过 Apple 公证。此下载不支持 Intel。",
|
||||
"guide": {
|
||||
"label": "安装与首次听写",
|
||||
"url": "docs/DOWNLOAD.zh.md"
|
||||
}
|
||||
},
|
||||
"hero_alt": "白色大理石的伊里斯长着大理石翅膀,站在古典石柱旁,金色的声音丝带落进石板上的凹槽里",
|
||||
"what": "这是一个 Mac 应用:你说话,它替你打字。\n\n用起来是这样。按一下键,用平常的声音说话,再按一下。文字会落在光标原来的位置:邮件里、聊天里、搜索框里。不用切换到别的地方,也没有单独的窗口。\n\n和同类应用最大的区别在于语音在哪里被解码。通常你的声音会被送到别人的服务器,在那里变成文字再回来。这里是你的 Mac 在计算,声音不会离开这台机器。\n\n**为什么叫「iriz」。** 伊里斯是希腊神话里众神的信使,也是彩虹——连接天与地的桥。她不编造消息,只把它完整地带到。这个名字对应的是把语音转成文字的工作。自动识别仍会听错词,结果需要你核查。\n\n\n\n它还会别的。它能修好用错键盘布局打出来的句子。粘贴之后你改了一个词,它会问要不要记住这个替换。普通口述可以去掉犹豫和重复。\n\n会议处理会保留原始识别文本和录音。DOCX 先放纪要,再另起一页放完整的可用转写;同一文件夹还包含 JSON 和待核实事项。通过所选代理填写决策和任务前,会单独征求发送文本的同意。未知信息会明确标注,结果仍是草稿。[会议处理说明](docs/MEETINGS.md)。\n\n\n\n\n",
|
||||
"why": "靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。\n\n只有一件事挡在前面。云端听写把口语整理得比任何本地方案都干净,可你说的内容也随之离开了这台机器:和客户的通话、文件草稿、人名和金额。对医生、律师、心理咨询师来说,这笔交换怎么算都不划算。\n\n所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。\n\n\n",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
name: App download
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'README.md'
|
||||
- 'README.ru.md'
|
||||
- 'README.zh.md'
|
||||
- '.github/family-page.json'
|
||||
- 'docs/assets/download-macos.png'
|
||||
- 'scripts/check_app_download*.mjs'
|
||||
- '.github/workflows/app-download.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: app-download
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
if: github.repository == 'zarubinvibe/iriz' && github.event.repository.visibility == 'public'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out the selected commit
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check download failure paths offline
|
||||
run: node scripts/check_app_download.mjs --selftest
|
||||
|
||||
- name: Verify the public application download anonymously
|
||||
run: node scripts/check_app_download.mjs
|
||||
@@ -0,0 +1,2 @@
|
||||
# Binary templates have tracked text/JSON companions; derived Markdown sidecars are ignored.
|
||||
*.docx
|
||||
@@ -13,6 +13,12 @@
|
||||
| кластеризация VBx | VBx | Apache-2.0 | `THIRD-PARTY/VBx-LICENSE` | через FluidAudio, разбор говорящих |
|
||||
| модели разделения голосов | FluidInference / Speaker Diarization CoreML, на основе Pyannote Community-1 | CC-BY-4.0 | [закреплённая карточка модели](https://huggingface.co/FluidInference/speaker-diarization-coreml/blob/1ed7a662fdc7109e36d822db793ee6eebdaf8594/README.md) · [лицензия](https://creativecommons.org/licenses/by/4.0/) | отдельная загрузка по кнопке, не внутри DMG |
|
||||
| шрифт шаблона протокола | PT Serif, ParaType | SIL Open Font License 1.1 | `Sources/IrizDictate/Resources/MeetingMinutes/fonts/OFL.txt` | файлы шрифтов и лицензия внутри ресурсного bundle |
|
||||
| кнопка скачивания для macOS | MonitorControl, `.github/macos_badge_noborder.png` | MIT проекта | `THIRD-PARTY/MonitorControl-LICENSE` | только README, не внутри приложения |
|
||||
|
||||
Кнопка `docs/assets/download-macos.png` скопирована без изменений из
|
||||
[MonitorControl](https://github.com/MonitorControl/MonitorControl/blob/2c2b7cea67e89db56c311c209ecc60dda6bbbd22/.github/macos_badge_noborder.png).
|
||||
SHA-256: `687db572c2d1a5fc42684a8c94ec1c4df960c6369616ff0ca10990b553008ae8`.
|
||||
Это ссылка на DMG проекта, не на App Store и не знак одобрения Apple.
|
||||
|
||||
Модели голосов закреплены на ревизии `1ed7a662fdc7109e36d822db793ee6eebdaf8594`;
|
||||
приложение проверяет исходные байты по размеру и SHA-256 и не изменяет веса.
|
||||
|
||||
@@ -2,14 +2,6 @@
|
||||
|
||||
Speak out loud and the text appears. Speech recognition runs on your Mac; sending text to an agent is a separate choice.
|
||||
|
||||
[](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
|
||||
|
||||
Apple Silicon · macOS 14+ · Model download: about 500 MB
|
||||
|
||||
[Install & first dictation](docs/DOWNLOAD.md) · [Release notes](https://github.com/zarubinvibe/iriz/releases/latest)
|
||||
|
||||
Self-signed; not notarized by Apple. Intel is not supported by this download.
|
||||
|
||||
[Русский](README.ru.md) · [中文](README.zh.md)
|
||||
|
||||
[](LICENSE) [](https://github.com/zarubinvibe/iriz/stargazers) [](https://github.com/zarubinvibe/iriz) [](https://github.com/zarubinvibe/athena#olympuz-family)
|
||||
@@ -41,6 +33,21 @@ Self-signed; not notarized by Apple. Intel is not supported by this download.
|
||||
- [Limits](#limits)
|
||||
- [Star And Contribute](#star-and-contribute)
|
||||
|
||||
<!-- application-downloads:start -->
|
||||
|
||||
<p align="center"><a href="https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg"><img src="docs/assets/download-macos.png" alt="Download for macOS" width="180"></a><br>
|
||||
<a href="https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg">Download for macOS</a> · Direct download</p>
|
||||
|
||||
<p align="center">macOS · Apple Silicon — macOS 14+ · DMG</p>
|
||||
|
||||
<p align="center">Setup: At first launch, choose Download and install Parakeet to download the speech model (about 500 MB).</p>
|
||||
|
||||
<p align="center">Security: Self-signed; not notarized by Apple. Intel is not supported by this download.</p>
|
||||
|
||||
<p align="center"><a href="docs/DOWNLOAD.md">Install & first dictation</a> · <a href="https://github.com/zarubinvibe/iriz/releases/latest">All releases</a> · <a href="https://github.com/zarubinvibe/iriz/releases/latest/download/SHA256SUMS.txt">Checksums</a></p>
|
||||
|
||||
<!-- application-downloads:end -->
|
||||
|
||||
<!-- beginner-readme:start -->
|
||||
|
||||
## What This Is
|
||||
@@ -214,7 +221,7 @@ Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOAR
|
||||
|
||||
Useful? Give iriz a star: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). It takes a second and it decides whether other people ever find the project.
|
||||
|
||||
Want to change something? The path is short: fork the repository, create a branch, commit your change, push the branch, then open a Pull Request. Do not push directly to `main`.
|
||||
Want to change something? The path is short: fork the repository, create a branch, commit your change, push the branch, then open a Pull Request. Do not push directly to `main`; the release gate rejects it.
|
||||
|
||||
Found a problem instead? Open an issue at [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) and say what you ran and what happened.
|
||||
|
||||
|
||||
+23
-16
@@ -2,14 +2,6 @@
|
||||
|
||||
Говори вслух, на экране появляется текст. Речь разбирает твой Мак. Передачу текста агенту ты разрешаешь отдельно.
|
||||
|
||||
[](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
|
||||
|
||||
Apple Silicon · macOS 14+ · Модель скачивается отдельно: около 500 МБ
|
||||
|
||||
[Установка и первая диктовка](docs/DOWNLOAD.ru.md) · [Что изменилось](https://github.com/zarubinvibe/iriz/releases/latest)
|
||||
|
||||
Самоподпись, без нотаризации Apple. Этот выпуск не поддерживает Intel.
|
||||
|
||||
[English](README.md) · [中文](README.zh.md)
|
||||
|
||||
[](LICENSE) [](https://github.com/zarubinvibe/iriz/stargazers) [](https://github.com/zarubinvibe/iriz) [](https://github.com/zarubinvibe/athena#olympuz-family)
|
||||
@@ -41,6 +33,21 @@ Apple Silicon · macOS 14+ · Модель скачивается отдельн
|
||||
- [Ограничения](#ограничения)
|
||||
- [Звезда и вклад](#звезда-и-вклад)
|
||||
|
||||
<!-- application-downloads:start -->
|
||||
|
||||
<p align="center"><a href="https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg"><img src="docs/assets/download-macos.png" alt="Скачать для macOS" width="180"></a><br>
|
||||
<a href="https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg">Скачать для macOS</a> · Прямая загрузка</p>
|
||||
|
||||
<p align="center">macOS · Apple Silicon — macOS 14+ · DMG</p>
|
||||
|
||||
<p align="center">Настройка: При первом запуске нажми «Скачать и установить Parakeet»: модель речи скачивается отдельно, около 500 МБ.</p>
|
||||
|
||||
<p align="center">Безопасность: Самоподпись, без нотаризации Apple. Этот выпуск не поддерживает Intel.</p>
|
||||
|
||||
<p align="center"><a href="docs/DOWNLOAD.ru.md">Установка и первая диктовка</a> · <a href="https://github.com/zarubinvibe/iriz/releases/latest">Все версии</a> · <a href="https://github.com/zarubinvibe/iriz/releases/latest/download/SHA256SUMS.txt">Контрольные суммы</a></p>
|
||||
|
||||
<!-- application-downloads:end -->
|
||||
|
||||
<!-- beginner-readme:start -->
|
||||
|
||||
## Что это
|
||||
@@ -160,7 +167,7 @@ claude # или пусти агента: он проведет
|
||||
|
||||
Нет Git? Скачай [ZIP с исходниками](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуй и запусти в нем тот же установщик. Или открой проект в Claude Code и запусти `/iriz-setup`: агент проведет установку по шагам и спросит перед изменениями.
|
||||
|
||||
Делаешь это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
|
||||
Делаете это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
|
||||
|
||||
**Что получится:** установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока ты не попросишь.
|
||||
|
||||
@@ -180,10 +187,10 @@ claude # или пусти агента: он проведет
|
||||
| Слово | Простое значение |
|
||||
|---|---|
|
||||
| Repository | Папка проекта, которую хранит и версионирует Git |
|
||||
| Terminal | Окно, куда ты вводишь команды |
|
||||
| Command | Одна инструкция, которую ты даешь компьютеру |
|
||||
| Terminal | Окно, куда вы вводите команды |
|
||||
| Command | Одна инструкция компьютеру |
|
||||
| Branch | Отдельная линия изменений, которая не трогает `main` |
|
||||
| Pull Request | Просьба проверить твое изменение и принять его |
|
||||
| Pull Request | Просьба проверить ваше изменение и принять его |
|
||||
| Neural Engine | Отдельный кусок процессора Apple под нейросети: держит распознавание быстрым и не греет машину |
|
||||
| Модель распознавания | Файлы весов, по которым звук превращается в буквы. Живет у тебя на диске, скачивается один раз |
|
||||
|
||||
@@ -212,11 +219,11 @@ claude # или пусти агента: он проведет
|
||||
|
||||
## Звезда и вклад
|
||||
|
||||
Пригодилось? Поставь iriz звезду: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). Это секунда, а от нее зависит, найдут ли проект другие люди.
|
||||
Пригодилось? Поставьте iriz звезду: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). Это секунда, а от нее зависит, найдут ли проект другие люди.
|
||||
|
||||
Хочешь что-то поправить? Путь короткий: сделай fork, заведи ветку, оформи commit, отправь push и открой Pull Request. Не отправляй push прямо в `main`.
|
||||
Хотите что-то поправить? Путь короткий: сделайте fork, заведите ветку, оформите commit, отправьте push и откройте Pull Request. Не отправляйте push прямо в `main`: релизный gate его отклонит.
|
||||
|
||||
Нашел ошибку? Заведи issue на [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) и напиши, что запускал и что получилось.
|
||||
Нашли ошибку? Заведите issue на [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) и напишите, что запускали и что получилось.
|
||||
|
||||
<!-- beginner-readme:end -->
|
||||
|
||||
@@ -233,7 +240,7 @@ claude # или пусти агента: он проведет
|
||||
| проект | Themiz | Многоагентный помощник по российским судебным делам с локальным OCR и советом из пяти юристов. | Ведет российские судебные дела многоагентно, с локальным хранением материалов. | [Репозиторий](https://github.com/zarubinvibe/themiz) · [ZIP](https://github.com/zarubinvibe/themiz/archive/refs/heads/main.zip) |
|
||||
| проект | Zeuz | Фабрика многоагентных workflow: собирает систему с правилами, гейтами, наблюдаемостью и replay. | Собирает многоагентный workflow с правилами, воротами, наблюдаемостью и повтором прогона. | [Репозиторий](https://github.com/zarubinvibe/zeuz) · [ZIP](https://github.com/zarubinvibe/zeuz/archive/refs/heads/main.zip) |
|
||||
| проект | Lynceuz | Собирает доказательства из открытого веба за ноль рублей и честно останавливается, когда безопасные пути кончились. | Собирает доказательства из открытого веба бесплатно и честно останавливается на границе. | [Репозиторий](https://github.com/zarubinvibe/lynceuz) · [ZIP](https://github.com/zarubinvibe/lynceuz/archive/refs/heads/main.zip) |
|
||||
| проект | Iriz | Диктовка в строке меню macOS: речь разбирается на твоем Маке, раскладка чинится сама, надиктовка превращается в готовое задание для агента. | Диктовка в строке меню macOS: речь разбирается на твоем Маке, раскладка чинится сама. | [Репозиторий](https://github.com/zarubinvibe/iriz) · [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip) |
|
||||
| проект | Iriz | Диктовка в строке меню macOS: речь разбирается на вашем Маке, раскладка чинится сама, надиктовка превращается в готовое задание для агента. | Диктовка в строке меню macOS: речь разбирается на вашем Маке, раскладка чинится сама. | [Репозиторий](https://github.com/zarubinvibe/iriz) · [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip) |
|
||||
| проект | Mantoz | Ставит идею перед пятьюстами людьми, которых не существует, и показывает, как ответила каждая группа. | Ставит идею перед сотнями сгенерированных людей до того, как ее увидят живые. | [Репозиторий](https://github.com/zarubinvibe/mantoz) · [ZIP](https://github.com/zarubinvibe/mantoz/archive/refs/heads/main.zip) |
|
||||
| проект | Koiz | Одна база уроков на все проекты. Каждый провал доводится до причины, и причина висит открытой, пока ее не закроет хук, ворота или тест. | Держит одну базу уроков на все проекты и требует механизм, а не обещание. | [Репозиторий](https://github.com/zarubinvibe/koiz) · [ZIP](https://github.com/zarubinvibe/koiz/archive/refs/heads/main.zip) |
|
||||
<!-- pantheon-family:end -->
|
||||
|
||||
+16
-9
@@ -2,14 +2,6 @@
|
||||
|
||||
你说出来,屏幕上就有字。语音识别在你的 Mac 上完成;向代理发送文本需要你另行同意。
|
||||
|
||||
[](https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg)
|
||||
|
||||
Apple Silicon · macOS 14+ · 语音模型需另行下载,约 500 MB
|
||||
|
||||
[安装与首次听写](docs/DOWNLOAD.zh.md) · [更新说明](https://github.com/zarubinvibe/iriz/releases/latest)
|
||||
|
||||
应用使用自签名,尚未通过 Apple 公证。此下载不支持 Intel。
|
||||
|
||||
[English](README.md) · [Русский](README.ru.md)
|
||||
|
||||
[](LICENSE) [](https://github.com/zarubinvibe/iriz/stargazers) [](https://github.com/zarubinvibe/iriz) [](https://github.com/zarubinvibe/athena#olympuz-family)
|
||||
@@ -41,6 +33,21 @@ Apple Silicon · macOS 14+ · 语音模型需另行下载,约 500 MB
|
||||
- [局限](#局限)
|
||||
- [点亮星标与参与](#点亮星标与参与)
|
||||
|
||||
<!-- application-downloads:start -->
|
||||
|
||||
<p align="center"><a href="https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg"><img src="docs/assets/download-macos.png" alt="下载 macOS 版" width="180"></a><br>
|
||||
<a href="https://github.com/zarubinvibe/iriz/releases/latest/download/iriz-macos-arm64.dmg">下载 macOS 版</a> · 直接下载</p>
|
||||
|
||||
<p align="center">macOS · Apple Silicon — macOS 14+ · DMG</p>
|
||||
|
||||
<p align="center">设置: 首次启动时,选择下载并安装 Parakeet。语音模型需另行下载,约 500 MB。</p>
|
||||
|
||||
<p align="center">安全: 应用使用自签名,尚未通过 Apple 公证。此下载不支持 Intel。</p>
|
||||
|
||||
<p align="center"><a href="docs/DOWNLOAD.zh.md">安装与首次听写</a> · <a href="https://github.com/zarubinvibe/iriz/releases/latest">所有版本</a> · <a href="https://github.com/zarubinvibe/iriz/releases/latest/download/SHA256SUMS.txt">校验和</a></p>
|
||||
|
||||
<!-- application-downloads:end -->
|
||||
|
||||
<!-- beginner-readme:start -->
|
||||
|
||||
## 这是什么
|
||||
@@ -214,7 +221,7 @@ claude # или пусти агента: он проведет
|
||||
|
||||
觉得有用?给 iriz 点亮星标:[https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz)。这只要一秒,却决定别人能不能找到这个项目。
|
||||
|
||||
想改点什么?流程很短:先 fork 仓库,建一个分支 branch,提交 commit,推送 push,然后开一个 Pull Request。请不要直接向 `main` 推送变更。
|
||||
想改点什么?流程很短:先 fork 仓库,建一个分支 branch,提交 commit,推送 push,然后开一个 Pull Request。请不要直接向 `main` 推送,发布闸门会拒绝。
|
||||
|
||||
发现问题?到 [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) 开一个 issue,写清楚你运行了什么、发生了什么。
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
0.2.2
|
||||
0.2.3
|
||||
|
||||
@@ -313,7 +313,14 @@ public final class DictationController {
|
||||
hotkeys.isRecordingActive = { [weak self] in self?.isRecording ?? false }
|
||||
hotkeys.canStartRecording = { [weak self] in
|
||||
guard let self else { return false }
|
||||
return self.startRefusal() == nil
|
||||
// Только предварительный допуск по состоянию. AX не вызывается
|
||||
// внутри event tap: полная проверка идёт в handlePress, до микрофона,
|
||||
// после dispatchHotkeyActions на главный актор.
|
||||
return dictationStartRefusal(modelReady: self.modelReady,
|
||||
isRecording: self.isRecording,
|
||||
isBusy: self.isBusy,
|
||||
secureInputActive: false,
|
||||
modelWarming: self.modelWarming) == nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +652,8 @@ public final class DictationController {
|
||||
isRecording: isRecording,
|
||||
isBusy: isBusy,
|
||||
secureInputActive: Permissions.isSecureInputActive,
|
||||
modelWarming: modelWarming)
|
||||
modelWarming: modelWarming,
|
||||
focusedInputProtected: Permissions.focusedInputProtection)
|
||||
}
|
||||
|
||||
/// Смена аудиоустройства посреди записи: крючок AudioCapture до этого
|
||||
|
||||
@@ -171,8 +171,8 @@ let dictationWarmUpWaitLimitSeconds: Double = 180
|
||||
|
||||
// MARK: - Отказ старта записи
|
||||
|
||||
/// Почему запись не стартует. `secureInputActive` — новый класс отказа:
|
||||
/// в поле пароля синтетический ⌘V не дойдёт всё равно, честнее сказать сразу.
|
||||
/// Почему запись не стартует. Защита относится к текущему полю, а не к
|
||||
/// наличию фонового процесса с защищённым вводом клавиатуры.
|
||||
enum DictationStartRefusal: String, Equatable {
|
||||
case secureInputActive
|
||||
case modelNotReady
|
||||
@@ -180,6 +180,12 @@ enum DictationStartRefusal: String, Equatable {
|
||||
case transcriptionInFlight
|
||||
}
|
||||
|
||||
/// Неизвестное поле при активной системной защите не считается обычным.
|
||||
func dictationInputIsProtected(secureInputActive: Bool,
|
||||
focusedInputProtected: Bool?) -> Bool {
|
||||
focusedInputProtected ?? secureInputActive
|
||||
}
|
||||
|
||||
/// Отказать ли старту.
|
||||
///
|
||||
/// `modelWarming` отделяет «модель ещё грузится» от «модели нет». Разница
|
||||
@@ -195,8 +201,12 @@ func dictationStartRefusal(modelReady: Bool,
|
||||
isRecording: Bool,
|
||||
isBusy: Bool,
|
||||
secureInputActive: Bool,
|
||||
modelWarming: Bool = false) -> DictationStartRefusal? {
|
||||
if secureInputActive { return .secureInputActive }
|
||||
modelWarming: Bool = false,
|
||||
focusedInputProtected: Bool? = nil) -> DictationStartRefusal? {
|
||||
if dictationInputIsProtected(secureInputActive: secureInputActive,
|
||||
focusedInputProtected: focusedInputProtected) {
|
||||
return .secureInputActive
|
||||
}
|
||||
if !modelReady, !modelWarming { return .modelNotReady }
|
||||
if isRecording { return .alreadyRecording }
|
||||
if isBusy { return .transcriptionInFlight }
|
||||
|
||||
@@ -98,12 +98,17 @@ func dictationLearningReadFocusedText() -> (text: String, pid: pid_t)? {
|
||||
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
|
||||
let pid = app.processIdentifier
|
||||
let axApp = AXUIElementCreateApplication(pid)
|
||||
AXUIElementSetMessagingTimeout(axApp, 0.15)
|
||||
|
||||
var focusedRaw: AnyObject?
|
||||
guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString,
|
||||
&focusedRaw) == .success,
|
||||
let focused = focusedRaw else { return nil }
|
||||
let focused = focusedRaw,
|
||||
CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil }
|
||||
let element = focused as! AXUIElement
|
||||
// Проверяем именно этот элемент до AXValue. Неизвестное состояние —
|
||||
// тоже отказ: для обучения читать потенциально защищённый текст незачем.
|
||||
guard Permissions.inputProtection(of: element) == false else { return nil }
|
||||
|
||||
var roleRaw: AnyObject?
|
||||
AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &roleRaw)
|
||||
|
||||
@@ -160,7 +160,8 @@ struct HotkeyTransitionState {
|
||||
|
||||
/// `canStartRecording` mirrors the app-side guard on handlePress
|
||||
/// (ready, not recording, not busy, not terminating). Toggle mode
|
||||
/// consults it before claiming either recording route.
|
||||
/// consults it only before claiming a recording route. Ordinary keyboard
|
||||
/// events must not trigger the app's potentially expensive AX query.
|
||||
mutating func transition(
|
||||
for event: HotkeyEventSnapshot,
|
||||
hotkey: HotkeyChoice,
|
||||
@@ -177,7 +178,7 @@ struct HotkeyTransitionState {
|
||||
translationHotkeyEnabled: Bool = false,
|
||||
triggerMode: TriggerMode,
|
||||
isRecording: Bool,
|
||||
canStartRecording: Bool = true
|
||||
canStartRecording: @autoclosure () -> Bool = true
|
||||
) -> HotkeyTransitionResult {
|
||||
if event.keycode == ESCAPE_KEYCODE {
|
||||
return transitionEscape(for: event, isRecording: isRecording)
|
||||
@@ -278,7 +279,7 @@ struct HotkeyTransitionState {
|
||||
// in toggle mode because the state machine gates it here.
|
||||
guard !isRecording,
|
||||
activeRecordingRoute == nil,
|
||||
canStartRecording else {
|
||||
canStartRecording() else {
|
||||
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
|
||||
actions: [.rejectedBusyPress])
|
||||
}
|
||||
@@ -291,7 +292,7 @@ struct HotkeyTransitionState {
|
||||
private mutating func transitionPromptShortcut(
|
||||
for event: HotkeyEventSnapshot,
|
||||
isRecording: Bool,
|
||||
canStartRecording: Bool,
|
||||
canStartRecording: () -> Bool,
|
||||
promptHotkey: HotkeyChoice,
|
||||
triggerMode: TriggerMode
|
||||
) -> HotkeyTransitionResult? {
|
||||
@@ -338,7 +339,7 @@ struct HotkeyTransitionState {
|
||||
}
|
||||
guard !isRecording,
|
||||
activeRecordingRoute == nil,
|
||||
canStartRecording else {
|
||||
canStartRecording() else {
|
||||
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
|
||||
actions: [.rejectedBusyPress])
|
||||
}
|
||||
@@ -352,7 +353,7 @@ struct HotkeyTransitionState {
|
||||
private mutating func transitionTranslationShortcut(
|
||||
for event: HotkeyEventSnapshot,
|
||||
isRecording: Bool,
|
||||
canStartRecording: Bool,
|
||||
canStartRecording: () -> Bool,
|
||||
translationHotkey: HotkeyChoice,
|
||||
triggerMode: TriggerMode
|
||||
) -> HotkeyTransitionResult? {
|
||||
@@ -399,7 +400,7 @@ struct HotkeyTransitionState {
|
||||
}
|
||||
guard !isRecording,
|
||||
activeRecordingRoute == nil,
|
||||
canStartRecording else {
|
||||
canStartRecording() else {
|
||||
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
|
||||
actions: [.rejectedBusyPress])
|
||||
}
|
||||
|
||||
@@ -26,14 +26,57 @@ enum Permissions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Активен ли защищённый ввод — поле пароля, Secure Keyboard Entry в
|
||||
/// терминале. Тот же системный вызов, что у AutoSwitchPolicy в IrizInput
|
||||
/// (тянуть IrizInput в IrizDictate не за чем — API системное).
|
||||
///
|
||||
/// Для диктовки это честный класс провала вставки: в защищённое поле
|
||||
/// синтетический ⌘V не дойдёт всё равно, а сырьё уже легло бы на диск.
|
||||
/// Глобальная защита клавиатурных событий: её может держать фоновый
|
||||
/// процесс. Сама по себе она не описывает поле в фокусе и не запрещает микрофон.
|
||||
static var isSecureInputActive: Bool { IsSecureEventInputEnabled() }
|
||||
|
||||
static var isDictationInputProtected: Bool {
|
||||
dictationInputIsProtected(secureInputActive: isSecureInputActive,
|
||||
focusedInputProtected: focusedInputProtection)
|
||||
}
|
||||
|
||||
/// Только метаданные текущего элемента; содержимое поля не запрашивается.
|
||||
/// Неизвестное состояние сохраняется как nil для осторожного fallback.
|
||||
static var focusedInputProtection: Bool? {
|
||||
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
|
||||
let axApp = AXUIElementCreateApplication(app.processIdentifier)
|
||||
AXUIElementSetMessagingTimeout(axApp, 0.15)
|
||||
var focused: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString,
|
||||
&focused) == .success,
|
||||
let focused, CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil }
|
||||
return inputProtection(of: focused as! AXUIElement)
|
||||
}
|
||||
|
||||
static func inputProtection(of element: AXUIElement) -> Bool? {
|
||||
AXUIElementSetMessagingTimeout(element, 0.15)
|
||||
return inputProtection { attribute in
|
||||
var value: CFTypeRef?
|
||||
let error = AXUIElementCopyAttributeValue(element, attribute, &value)
|
||||
return (error, value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Тот же путь чтения в продукте и в пробе: проба не касается чужого окна.
|
||||
static func inputProtection(readAttribute: (CFString) -> (AXError, CFTypeRef?)) -> Bool? {
|
||||
let (roleError, roleValue) = readAttribute(kAXRoleAttribute as CFString)
|
||||
let (subroleError, subroleValue) = readAttribute(kAXSubroleAttribute as CFString)
|
||||
if subroleError == .success, subroleValue as? String == kAXSecureTextFieldSubrole { return true }
|
||||
let (protectedError, protectedValue) = readAttribute(
|
||||
NSAccessibility.Attribute.containsProtectedContent.rawValue as CFString)
|
||||
if protectedError == .success, protectedValue as? Bool == true { return true }
|
||||
|
||||
// Необязательного атрибута может не быть у обычного поля/окна.
|
||||
// Таймаут и ошибка связи отсутствием атрибута не считаются.
|
||||
// Явная защита выше ошибки роли: её нельзя потерять при частичном ответе AX.
|
||||
guard roleError == .success, let role = roleValue as? String, !role.isEmpty else { return nil }
|
||||
let optionalAbsent: [AXError] = [.attributeUnsupported, .noValue]
|
||||
guard (subroleError == .success && subroleValue is String) || optionalAbsent.contains(subroleError),
|
||||
(protectedError == .success && protectedValue is Bool) || optionalAbsent.contains(protectedError)
|
||||
else { return nil }
|
||||
return false
|
||||
}
|
||||
|
||||
/// Trigger the system prompt or, if previously denied, push the
|
||||
/// user toward the right Settings pane. Returns immediately;
|
||||
/// actual grant happens asynchronously.
|
||||
|
||||
@@ -103,7 +103,8 @@ func postKeyboardEventSteps(_ steps: [KeyboardEventStep], targetPID: pid_t? = ni
|
||||
enum KeyboardShortcutPoster {
|
||||
@discardableResult
|
||||
static func postReturn() -> Bool {
|
||||
postKeyboardEventSteps([
|
||||
guard TextInserter.targetAllowsPosting(nil) else { return false }
|
||||
return postKeyboardEventSteps([
|
||||
KeyboardEventStep(virtualKey: RETURN_KEYCODE, keyDown: true, flags: []),
|
||||
KeyboardEventStep(virtualKey: RETURN_KEYCODE, keyDown: false, flags: []),
|
||||
])
|
||||
@@ -188,10 +189,13 @@ enum TextInserter {
|
||||
}
|
||||
|
||||
fileprivate static func targetAllowsPosting(_ expectedTargetPID: pid_t?) -> Bool {
|
||||
textInsertionTargetAllowsPosting(
|
||||
guard let checkedPID = NSWorkspace.shared.frontmostApplication?.processIdentifier,
|
||||
textInsertionTargetAllowsPosting(
|
||||
expectedTargetPID: expectedTargetPID,
|
||||
currentTargetPID: NSWorkspace.shared.frontmostApplication?.processIdentifier
|
||||
)
|
||||
currentTargetPID: checkedPID
|
||||
), !Permissions.isDictationInputProtected else { return false }
|
||||
// AX — IPC: за время проверки фокус мог перейти к другому приложению.
|
||||
return NSWorkspace.shared.frontmostApplication?.processIdentifier == checkedPID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright © 2017
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -425,6 +425,35 @@ struct HungTranscriptionTests {
|
||||
@Suite("dictationStartRefusal")
|
||||
struct DictationStartRefusalTests {
|
||||
|
||||
@Test func backgroundSecureKeyboardInputDoesNotBlockOrdinaryFieldRecording() {
|
||||
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
|
||||
isBusy: false, secureInputActive: true,
|
||||
focusedInputProtected: false) == nil)
|
||||
}
|
||||
|
||||
@Test func actualProtectedFieldBlocksEvenWithoutGlobalKeyboardFlag() {
|
||||
for globalSecureInput in [false, true] {
|
||||
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
|
||||
isBusy: false, secureInputActive: globalSecureInput,
|
||||
focusedInputProtected: true) == .secureInputActive)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func ordinaryFieldRetainsModelAndBusyGuards() {
|
||||
#expect(dictationStartRefusal(modelReady: false, isRecording: false,
|
||||
isBusy: false, secureInputActive: true,
|
||||
focusedInputProtected: false) == .modelNotReady)
|
||||
#expect(dictationStartRefusal(modelReady: false, isRecording: false,
|
||||
isBusy: false, secureInputActive: true,
|
||||
modelWarming: true, focusedInputProtected: false) == nil)
|
||||
#expect(dictationStartRefusal(modelReady: true, isRecording: true,
|
||||
isBusy: false, secureInputActive: true,
|
||||
focusedInputProtected: false) == .alreadyRecording)
|
||||
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
|
||||
isBusy: true, secureInputActive: true,
|
||||
focusedInputProtected: false) == .transcriptionInFlight)
|
||||
}
|
||||
|
||||
/// Защищённый ввод: запись не стартует, причина названа — звонит отказ.
|
||||
@Test func secureInputBlocksRecording() {
|
||||
#expect(dictationStartRefusal(modelReady: true,
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import AppKit
|
||||
import ApplicationServices
|
||||
import Testing
|
||||
|
||||
@testable import IrizDictate
|
||||
|
||||
@Suite("Защита поля не равна глобальной защите клавиатуры")
|
||||
@MainActor
|
||||
struct FocusedInputProtectionTests {
|
||||
private func protection(role: String? = "AXTextField",
|
||||
roleError: AXError = .success,
|
||||
subrole: String? = nil,
|
||||
subroleError: AXError = .attributeUnsupported,
|
||||
protected: Bool? = nil,
|
||||
protectedError: AXError = .attributeUnsupported) -> Bool? {
|
||||
Permissions.inputProtection { attribute in
|
||||
switch attribute as String {
|
||||
case kAXRoleAttribute:
|
||||
return (roleError, role.map { $0 as CFString })
|
||||
case kAXSubroleAttribute:
|
||||
return (subroleError, subrole.map { $0 as CFString })
|
||||
case NSAccessibility.Attribute.containsProtectedContent.rawValue:
|
||||
return (protectedError, protected.map { NSNumber(value: $0) })
|
||||
default:
|
||||
Issue.record("Неожиданный запрос атрибута: \(attribute)")
|
||||
return (.attributeUnsupported, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func парольЗащищёнПриЛюбомГлобальномФлаге() {
|
||||
let focused = protection(subrole: kAXSecureTextFieldSubrole, subroleError: .success)
|
||||
#expect(focused == true)
|
||||
for global in [false, true] {
|
||||
#expect(dictationInputIsProtected(secureInputActive: global, focusedInputProtected: focused))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func защищённоеСодержимоеНеТребуетПарольнойПодроли() {
|
||||
#expect(protection(role: "AXTextArea", protected: true, protectedError: .success) == true)
|
||||
#expect(protection(subroleError: .cannotComplete,
|
||||
protected: true, protectedError: .success) == true)
|
||||
#expect(protection(roleError: .cannotComplete,
|
||||
protected: true, protectedError: .success) == true)
|
||||
#expect(protection(roleError: .cannotComplete,
|
||||
subrole: kAXSecureTextFieldSubrole, subroleError: .success) == true)
|
||||
}
|
||||
|
||||
@Test func обычноеПолеИОкноНеБлокируютсяФоновымФлагом() {
|
||||
for role in ["AXTextField", "AXTextArea", "AXWindow"] {
|
||||
let focused = protection(role: role)
|
||||
#expect(focused == false)
|
||||
#expect(!dictationInputIsProtected(secureInputActive: true, focusedInputProtected: focused))
|
||||
}
|
||||
#expect(protection(role: "AXWindow", subrole: "AXStandardWindow", subroleError: .success,
|
||||
protected: false, protectedError: .success) == false)
|
||||
#expect(protection(subroleError: .noValue, protectedError: .noValue) == false)
|
||||
}
|
||||
|
||||
@Test func ошибкаИОтсутствующаяРольОставляютСостояниеНеизвестным() {
|
||||
for error: AXError in [.cannotComplete, .invalidUIElement, .attributeUnsupported, .noValue] {
|
||||
#expect(protection(roleError: error) == nil)
|
||||
}
|
||||
#expect(protection(role: nil) == nil)
|
||||
#expect(protection(role: "") == nil)
|
||||
#expect(protection(subroleError: .cannotComplete) == nil)
|
||||
#expect(protection(protectedError: .cannotComplete) == nil)
|
||||
#expect(protection(subroleError: .success) == nil)
|
||||
#expect(protection(protectedError: .success) == nil)
|
||||
#expect(dictationInputIsProtected(secureInputActive: true, focusedInputProtected: nil))
|
||||
#expect(!dictationInputIsProtected(secureInputActive: false, focusedInputProtected: nil))
|
||||
}
|
||||
|
||||
@Test func запросОграниченМетаданнымиБезЗначенияИВыделения() {
|
||||
var requested: [String] = []
|
||||
let result = Permissions.inputProtection { attribute in
|
||||
let name = attribute as String
|
||||
requested.append(name)
|
||||
if name == kAXRoleAttribute { return (.success, "AXTextArea" as CFString) }
|
||||
return (.attributeUnsupported, nil)
|
||||
}
|
||||
#expect(result == false)
|
||||
#expect(requested == [kAXRoleAttribute, kAXSubroleAttribute,
|
||||
NSAccessibility.Attribute.containsProtectedContent.rawValue])
|
||||
#expect(!requested.contains(kAXValueAttribute))
|
||||
#expect(!requested.contains(kAXSelectedTextAttribute))
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,47 @@ struct HotkeyAutomatonTests {
|
||||
#expect(result.suppress)
|
||||
}
|
||||
|
||||
@Test func readinessIsLazyForEveryToggleRecordingRoute() {
|
||||
let routes: [(CGKeyCode, HotkeyTransitionAction, HotkeyTransitionAction)] = [
|
||||
(96, .press, .release),
|
||||
(97, .pressPrompt, .releasePrompt),
|
||||
(98, .pressTranslation, .releaseTranslation),
|
||||
]
|
||||
for (keycode, start, stop) in routes {
|
||||
var state = HotkeyTransitionState()
|
||||
var readinessCalls = 0
|
||||
func ready() -> Bool {
|
||||
readinessCalls += 1
|
||||
return true
|
||||
}
|
||||
func send(_ type: CGEventType, _ keycode: CGKeyCode,
|
||||
isRecording: Bool = false) -> HotkeyTransitionResult {
|
||||
state.transition(for: keyEvent(type, keycode),
|
||||
hotkey: hotkeyChoice(forKeycode: 96),
|
||||
historyHotkey: hotkeyChoice(forKeycode: 100),
|
||||
promptHotkey: hotkeyChoice(forKeycode: 97),
|
||||
promptHotkeyEnabled: true,
|
||||
translationHotkey: hotkeyChoice(forKeycode: 98),
|
||||
translationHotkeyEnabled: true,
|
||||
triggerMode: .toggle,
|
||||
isRecording: isRecording,
|
||||
canStartRecording: ready())
|
||||
}
|
||||
#expect(send(.keyDown, 0).actions.isEmpty)
|
||||
#expect(send(.keyUp, 0).actions.isEmpty)
|
||||
#expect(send(.keyDown, 100).actions == [.showHistory])
|
||||
_ = send(.keyUp, 100)
|
||||
#expect(readinessCalls == 0)
|
||||
|
||||
#expect(send(.keyDown, keycode).actions == [start])
|
||||
#expect(readinessCalls == 1)
|
||||
_ = send(.keyUp, keycode, isRecording: true)
|
||||
#expect(readinessCalls == 1)
|
||||
#expect(send(.keyDown, keycode, isRecording: true).actions == [stop])
|
||||
#expect(readinessCalls == 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func toggleReleaseIsNoOpButSuppressed() {
|
||||
var state = HotkeyTransitionState()
|
||||
_ = state.transition(for: flagsChanged(54, .maskCommand),
|
||||
|
||||
@@ -25,7 +25,7 @@ macOS 26; на 14 и 15 приложение работает, но плашка
|
||||
|
||||
**Что меняется на диске:** ничего. Это чтение.
|
||||
|
||||
**Что ты получишь:** ответ, пойдет ли дальше, и на какой ветке визуала ты окажешься.
|
||||
**Что вы получите:** ответ, пойдет ли дальше, и на какой ветке визуала ты окажешься.
|
||||
|
||||
**Развилка:** нет Xcode, не беда. Возьми готовый образ со страницы Releases, и шаги про
|
||||
сборку мы пропустим.
|
||||
@@ -39,7 +39,7 @@ macOS 26; на 14 и 15 приложение работает, но плашка
|
||||
|
||||
**Что меняется на диске:** появляется одна папка, около 40 МБ. Больше ничего никуда не пишется.
|
||||
|
||||
**Что ты получишь:** дерево проекта, в котором видно `Sources`, `Tests`, `scripts` и `docs`.
|
||||
**Что вы получите:** дерево проекта, в котором видно `Sources`, `Tests`, `scripts` и `docs`.
|
||||
|
||||
## Шаг 3: собираем приложение
|
||||
|
||||
@@ -53,7 +53,7 @@ macOS 26; на 14 и 15 приложение работает, но плашка
|
||||
**Что меняется на диске:** первая команда не меняет ничего. Вторая тянет зависимости Swift
|
||||
(около 300 МБ в `.build`) и кладет готовое приложение в `/Applications`.
|
||||
|
||||
**Что ты получишь:** значок в строке меню наверху справа и окно знакомства.
|
||||
**Что вы получите:** значок в строке меню наверху справа и окно знакомства.
|
||||
|
||||
**Развилка:** не хочешь отдавать `/Applications`, скажи, соберем в папку проекта и запустим
|
||||
оттуда.
|
||||
@@ -79,7 +79,7 @@ macOS 26; на 14 и 15 приложение работает, но плашка
|
||||
«К установке модели». Если загрузка завершилась ошибкой, прочитай причину в окне и нажми
|
||||
«Попробовать снова» после ее устранения. Без модели пробу не начинаем.
|
||||
|
||||
**Что ты получишь:** после установки модели и выдачи разрешений проверим диктовку в окне
|
||||
**Что вы получите:** после установки модели и выдачи разрешений проверим диктовку в окне
|
||||
знакомства. Нажми клавишу, скажи фразу, нажми еще раз. Текст появится в поле пробы.
|
||||
|
||||
## Шаг 5: проверяем, что все честно
|
||||
@@ -95,7 +95,7 @@ macOS 26; на 14 и 15 приложение работает, но плашка
|
||||
**Что меняется на диске:** тесты обновляют `.build` и пишут служебные логи. Ворота также
|
||||
убирают временные файлы своих тестов.
|
||||
|
||||
**Что ты получишь:** отчет о выполненных проверках. Если есть отказ или пропуск, он останется
|
||||
**Что вы получите:** отчет о выполненных проверках. Если есть отказ или пропуск, он останется
|
||||
в отчете, а не превратится в обещание, что все работает.
|
||||
|
||||
```bash
|
||||
|
||||
@@ -62,6 +62,16 @@ A maintainer reviews the draft, the release notes and a clean-machine install, r
|
||||
|
||||
Before publishing, check the DMG after downloading it from the draft: mount it, verify its signature, launch a copied app in English and Chinese, and complete the permissions/model/first-dictation flow. Check the public asset hashes against the local output. Do not report a microphone or Intel test that was not performed.
|
||||
|
||||
After publication, **App download** checks the README buttons and downloads all four public release files without authentication. It also runs after relevant changes on `main` and through **Run workflow**. Run the same checks locally with Node 22.15 or newer:
|
||||
|
||||
```bash
|
||||
node scripts/check_app_download.mjs --selftest
|
||||
node scripts/check_app_download.mjs --local
|
||||
node scripts/check_app_download.mjs
|
||||
```
|
||||
|
||||
The live check follows the stable URL, verifies both complete DMGs against GitHub's asset sizes and digests, the manifest and `SHA256SUMS.txt`, and checks the manifest source against the release tag. It rejects unexpected files, HTML responses, truncated downloads and changes to Latest during the check. Requests use fixed GitHub hosts, at most five redirects, two attempts and a ten-minute total deadline; DMGs stream through SHA-256 without writing local files. A passing run confirms anonymous download integrity. Installation, signatures, permissions and first dictation still need the macOS checks above.
|
||||
|
||||
## Developer ID and notarization
|
||||
|
||||
Current public builds are not notarized. A self-signed or ad-hoc signature is not an Apple Developer ID signature. Neither proves that Apple has reviewed the app.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,33 @@
|
||||
# iriz 0.2.3
|
||||
|
||||

|
||||
|
||||
## English
|
||||
|
||||
Dictation no longer immediately stops with a red cross just because another program keeps Secure Keyboard Entry active. If macOS Accessibility confirms that the current field or window is ordinary, iriz can start recording there.
|
||||
|
||||
Password fields, secure content and anything iriz cannot verify still fail closed. The same protection applies before pasting text and before a delayed Enter key. Audio capture and the speech-recognition core did not change in this release.
|
||||
|
||||
The meeting export introduced in 0.2.2 remains in the app and DMG: minutes, the full available transcript on a separate page, matching JSON and the built-in document template.
|
||||
|
||||
The download is for Apple Silicon on macOS 14 or newer. The Parakeet model is separate and is about 500 MB. The app uses ad hoc signing and is not notarized by Apple. We do not claim to have tested Intel Macs or first launch from a clean macOS account.
|
||||
|
||||
## Русский
|
||||
|
||||
Диктовка больше не обрывается сразу с красным крестиком лишь потому, что другая программа держит включённым Secure Keyboard Entry. Если Accessibility в macOS подтверждает, что текущее поле или окно обычное, iriz начинает запись.
|
||||
|
||||
Парольные поля, защищённое содержимое и всё, что iriz не смог проверить, по-прежнему блокируются. Та же защита действует перед вставкой текста и отложенным Enter. Захват звука и движок распознавания речи в этом выпуске не менялись.
|
||||
|
||||
Экспорт встреч из 0.2.2 остаётся внутри приложения и DMG: протокол, вся доступная расшифровка на отдельной странице, соответствующий JSON и встроенный шаблон документа.
|
||||
|
||||
Файл предназначен для Mac с Apple Silicon и macOS 14 или новее. Модель Parakeet скачивается отдельно и занимает около 500 МБ. Приложение подписано ad hoc и не прошло нотаризацию Apple. Работа на Intel и первый запуск в чистой учётной записи macOS не заявлены как проверенные.
|
||||
|
||||
## 简体中文
|
||||
|
||||
现在,即使其他程序仍启用了 Secure Keyboard Entry,听写也不会因此立刻以红叉结束。只要 macOS 的 Accessibility 确认当前输入框或窗口不是受保护内容,iriz 就可以开始录音。
|
||||
|
||||
密码输入框、安全内容,以及 iriz 无法确认的状态仍会按 fail-closed 原则阻止操作。粘贴文本和延迟发送 Enter 之前也会执行同样的保护。本版本没有修改音频采集或语音识别核心。
|
||||
|
||||
0.2.2 加入的会议导出仍包含在应用和 DMG 中:会议纪要、另起一页的全部可用转写文本、对应的 JSON,以及内置文档模板。
|
||||
|
||||
此下载适用于 macOS 14 或更高版本的 Apple Silicon Mac。Parakeet 模型需要另外下载,大小约为 500 MB。应用使用 ad hoc 签名,尚未通过 Apple 公证。我们尚未验证 Intel Mac 或全新 macOS 账户的首次启动。
|
||||
+427
-401
File diff suppressed because it is too large
Load Diff
+27031
-25319
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,568 @@
|
||||
#!/usr/bin/env node
|
||||
// Anonymous live checks stream bytes only; draft checks mount read-only and run one isolated UI export.
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rm, stat } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { basename, dirname, join, resolve, sep } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { crc32, inflateSync } from 'node:zlib';
|
||||
|
||||
export const REPO = 'zarubinvibe/iriz';
|
||||
export const API = `https://api.github.com/repos/${REPO}`;
|
||||
export const DOWNLOAD = `https://github.com/${REPO}/releases`;
|
||||
export const STABLE = `${DOWNLOAD}/latest/download/iriz-macos-arm64.dmg`;
|
||||
const HOSTS = new Set(['github.com', 'api.github.com', 'release-assets.githubusercontent.com']);
|
||||
const META_LIMIT = 1024 * 1024;
|
||||
const DMG_LIMIT = 512 * 1024 * 1024;
|
||||
const HASH = /^[a-f0-9]{64}$/;
|
||||
const SHA = /^[a-f0-9]{40}$/;
|
||||
const MEETING_TEMPLATE_SHA = '8b4ffde7a7d09c6f3450b2de8667334fe79f544157553c3e81d77456b43807ff';
|
||||
const MEETING_FILES = [
|
||||
'README.md', 'data.schema.json', 'docs/filler-usage.md', 'docs/filling-rules.md',
|
||||
'docs/formatting.md', 'docs/owner-changes.md', 'docs/verification.md',
|
||||
'examples/data.example.json', 'examples/filled.example.docx', 'fields.json',
|
||||
'fonts/OFL.txt', 'fonts/PT_Serif-Web-Bold.ttf', 'fonts/PT_Serif-Web-Regular.ttf',
|
||||
'scripts/fill_template.py', 'scripts/verify_package.py', 'template.docx', 'template.md',
|
||||
'tests/test_fill_template.py',
|
||||
];
|
||||
export const UI_SHOT_NAMES = [
|
||||
'menu-normal', 'menu-alarm', 'menu-paused', 'menu-tap-dead',
|
||||
'settings', 'history-list', 'history-empty', 'history-rescue',
|
||||
].flatMap(surface => ['light', 'dark'].flatMap(theme => [1, 2]
|
||||
.map(scale => `${surface}-${theme}@${scale}x.png`)));
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const LOCALES = [['README.md', 'What This Is', 'Contents'], ['README.ru.md', 'Что это', 'Оглавление'], ['README.zh.md', '这是什么', '目录']];
|
||||
export const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const requireThat = (condition, message) => { if (!condition) throw new Error(message); };
|
||||
const sameNames = (actual, expected, label) => {
|
||||
requireThat(Array.isArray(actual) && actual.length === expected.length &&
|
||||
new Set(actual).size === actual.length && expected.every(name => actual.includes(name)), `${label}: wrong or duplicate filenames`);
|
||||
};
|
||||
|
||||
async function hashFile(path) {
|
||||
const hash = createHash('sha256');
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
async function sameFileBytes(left, right) {
|
||||
const [a, b] = await Promise.all([open(left, 'r'), open(right, 'r')]);
|
||||
const leftBuffer = Buffer.allocUnsafe(1024 * 1024), rightBuffer = Buffer.allocUnsafe(1024 * 1024);
|
||||
try {
|
||||
while (true) {
|
||||
const [leftRead, rightRead] = await Promise.all([a.read(leftBuffer), b.read(rightBuffer)]);
|
||||
if (leftRead.bytesRead !== rightRead.bytesRead) return false;
|
||||
if (!leftBuffer.subarray(0, leftRead.bytesRead).equals(rightBuffer.subarray(0, rightRead.bytesRead))) return false;
|
||||
if (leftRead.bytesRead === 0) return true;
|
||||
}
|
||||
} finally { await Promise.all([a.close(), b.close()]); }
|
||||
}
|
||||
|
||||
async function regularFile(path, label, maxBytes = DMG_LIMIT) {
|
||||
const info = await lstat(path).catch(() => null);
|
||||
requireThat(info?.isFile() && !info.isSymbolicLink() && info.size > 0 && info.size <= maxBytes,
|
||||
`${label}: missing, symlinked, empty or oversized`);
|
||||
return info;
|
||||
}
|
||||
|
||||
function nativeCommand(command, args, { cwd, env, timeout = 120_000 } = {}) {
|
||||
return new Promise((resolvePromise, rejectPromise) => execFile(command, args, {
|
||||
cwd, env, timeout, maxBuffer: 8 * META_LIMIT, windowsHide: true,
|
||||
}, (error, stdout, stderr) => {
|
||||
if (error) return rejectPromise(new Error(`${basename(command)} failed: ${String(stderr || stdout || error.message).trim()}`));
|
||||
resolvePromise({ stdout, stderr });
|
||||
}));
|
||||
}
|
||||
|
||||
export function trustedURL(value) {
|
||||
let url;
|
||||
try { url = new URL(value); } catch { throw new Error('Invalid download URL'); }
|
||||
requireThat(url.protocol === 'https:' && HOSTS.has(url.hostname) && !url.username &&
|
||||
!url.password && !url.port && !url.hash, 'Untrusted download URL');
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function request(url, {
|
||||
fetchImpl = globalThis.fetch, maxBytes = META_LIMIT, expectedBytes,
|
||||
capture = true, dmg = false, timeoutMs = 180_000, deadline = Date.now() + 600_000,
|
||||
attempts = 2, retryDelayMs = 1000,
|
||||
} = {}) {
|
||||
trustedURL(url);
|
||||
requireThat(Number.isInteger(attempts) && attempts >= 1 && attempts <= 2, 'Invalid retry bound');
|
||||
let lastError;
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
const controller = new AbortController();
|
||||
const remaining = Math.min(timeoutMs, deadline - Date.now());
|
||||
requireThat(remaining > 0, 'Download verification deadline exceeded');
|
||||
const timer = setTimeout(() => controller.abort(), remaining);
|
||||
let response;
|
||||
try {
|
||||
let current = url;
|
||||
const redirects = [];
|
||||
for (let hop = 0; hop <= 5; hop++) {
|
||||
trustedURL(current);
|
||||
try {
|
||||
response = await fetchImpl(current, {
|
||||
redirect: 'manual', credentials: 'omit', signal: controller.signal,
|
||||
headers: { Accept: 'application/octet-stream, application/json',
|
||||
'Accept-Encoding': 'identity', 'Cache-Control': 'no-cache',
|
||||
'User-Agent': 'iriz-anonymous-download-check' },
|
||||
});
|
||||
} catch {
|
||||
const error = new Error(controller.signal.aborted ? 'Download request timed out' : 'Anonymous network request failed');
|
||||
error.retryable = true;
|
||||
throw error;
|
||||
}
|
||||
if (![301, 302, 303, 307, 308].includes(response.status)) break;
|
||||
await response.body?.cancel();
|
||||
requireThat(hop < 5, 'Too many download redirects');
|
||||
const location = response.headers.get('location');
|
||||
requireThat(location, 'Redirect has no Location');
|
||||
current = trustedURL(new URL(location, current).href).href;
|
||||
redirects.push(current);
|
||||
}
|
||||
if (response.status !== 200) {
|
||||
const quota = response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0';
|
||||
const error = new Error(quota ? 'Anonymous GitHub API rate limit exhausted; download integrity is unverified' : `Anonymous HTTP request returned ${response.status}`);
|
||||
error.retryable = response.status === 429 || response.status >= 500;
|
||||
throw error;
|
||||
}
|
||||
requireThat(!/html/i.test(response.headers.get('content-type') || ''), 'HTML returned instead of a release file');
|
||||
requireThat(!response.headers.get('content-encoding') || response.headers.get('content-encoding') === 'identity', 'Unexpected content encoding');
|
||||
const length = response.headers.get('content-length');
|
||||
if (length !== null) {
|
||||
requireThat(/^\d+$/.test(length) && Number.isSafeInteger(Number(length)) && Number(length) <= maxBytes, 'Invalid or oversized Content-Length');
|
||||
if (expectedBytes !== undefined) requireThat(Number(length) === expectedBytes, 'Content-Length differs from asset size');
|
||||
}
|
||||
requireThat(response.body, 'Empty response body');
|
||||
const hash = createHash('sha256');
|
||||
const chunks = [];
|
||||
let bytes = 0;
|
||||
let prefix = Buffer.alloc(0);
|
||||
let tail = Buffer.alloc(0);
|
||||
try {
|
||||
for await (const part of response.body) {
|
||||
const chunk = Buffer.from(part);
|
||||
bytes += chunk.length;
|
||||
requireThat(bytes <= maxBytes && (expectedBytes === undefined || bytes <= expectedBytes), 'Response body exceeds its size limit');
|
||||
if (prefix.length < 512) prefix = Buffer.concat([prefix, chunk.subarray(0, 512 - prefix.length)]);
|
||||
requireThat(!/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(prefix.toString('utf8')), 'HTML returned instead of a release file');
|
||||
hash.update(chunk);
|
||||
if (capture) chunks.push(chunk);
|
||||
if (dmg) tail = Buffer.concat([tail, chunk]).subarray(-512);
|
||||
}
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
const timeout = new Error('Download body timed out');
|
||||
timeout.retryable = true;
|
||||
throw timeout;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
requireThat(bytes > 0, 'Empty response body');
|
||||
requireThat(length === null || bytes === Number(length), 'Truncated response body');
|
||||
requireThat(expectedBytes === undefined || bytes === expectedBytes, 'Downloaded size differs from release metadata');
|
||||
if (dmg) requireThat(bytes >= 512 && tail.subarray(0, 4).toString('ascii') === 'koly', 'Invalid DMG trailer');
|
||||
return { bytes, sha256: hash.digest('hex'), body: capture ? Buffer.concat(chunks) : undefined, redirects };
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (!error.retryable || attempt + 1 === attempts || Date.now() + retryDelayMs >= deadline) throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
}
|
||||
await new Promise(done => setTimeout(done, retryDelayMs));
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
function json(bytes, label) {
|
||||
try { return JSON.parse(bytes.toString('utf8')); } catch { throw new Error(`${label}: invalid JSON`); }
|
||||
}
|
||||
|
||||
export function releaseSnapshot(release) {
|
||||
requireThat(release && Number.isSafeInteger(release.id) && release.id > 0 &&
|
||||
release.draft === false && release.prerelease === false && /^v\d+\.\d+\.\d+$/.test(release.tag_name), 'Invalid latest release metadata');
|
||||
const version = release.tag_name.slice(1);
|
||||
const names = [`iriz-${version}-arm64.dmg`, 'iriz-macos-arm64.dmg', 'release-manifest.json', 'SHA256SUMS.txt'];
|
||||
sameNames(release.assets?.map(asset => asset.name), names, 'Release assets');
|
||||
const assets = names.map(name => {
|
||||
const asset = release.assets.find(item => item.name === name);
|
||||
requireThat(Number.isSafeInteger(asset.id) && asset.id > 0 && asset.state === 'uploaded' &&
|
||||
Number.isSafeInteger(asset.size) && asset.size > 0 && asset.size <= (name.endsWith('.dmg') ? DMG_LIMIT : META_LIMIT), `Invalid asset metadata: ${name}`);
|
||||
requireThat(/^sha256:[a-f0-9]{64}$/.test(asset.digest), `Missing or invalid GitHub digest: ${name}`);
|
||||
const url = `${DOWNLOAD}/download/${release.tag_name}/${name}`;
|
||||
requireThat(asset.browser_download_url === url, `Unexpected asset URL: ${name}`);
|
||||
return { name, id: asset.id, size: asset.size, digest: asset.digest.slice(7), url, updated_at: asset.updated_at };
|
||||
});
|
||||
return { id: release.id, tag: release.tag_name, version, assets };
|
||||
}
|
||||
|
||||
export function checksums(bytes, expected) {
|
||||
const result = new Map();
|
||||
const lines = bytes.toString('utf8').split(/\r?\n/);
|
||||
if (lines.at(-1) === '') lines.pop();
|
||||
for (const line of lines) {
|
||||
const match = /^([a-f0-9]{64}) ([a-zA-Z0-9._-]+)$/.exec(line);
|
||||
requireThat(match && expected.includes(match[2]) && !result.has(match[2]), 'Invalid, duplicate or unexpected checksum filename');
|
||||
result.set(match[2], match[1]);
|
||||
}
|
||||
sameNames([...result.keys()], expected, 'Checksums');
|
||||
return result;
|
||||
}
|
||||
|
||||
export function validateManifest(manifest, snapshot, downloaded) {
|
||||
requireThat(manifest?.version === snapshot.version && manifest.source_dirty === false && SHA.test(manifest.source_sha), 'Manifest version/source is invalid');
|
||||
const images = snapshot.assets.filter(asset => asset.name.endsWith('.dmg'));
|
||||
sameNames(manifest.artifacts?.map(item => item.file), images.map(item => item.name), 'Manifest artifacts');
|
||||
for (const asset of images) {
|
||||
const item = manifest.artifacts.find(entry => entry.file === asset.name);
|
||||
requireThat(item.bytes === asset.size && item.sha256 === downloaded.get(asset.name).sha256 &&
|
||||
Array.isArray(item.architectures) && item.architectures.length === 1 && item.architectures[0] === 'arm64', `Manifest artifact differs: ${asset.name}`);
|
||||
}
|
||||
// v0.2.2 was accepted independently; later documentation edits must not rewrite it.
|
||||
if (snapshot.version === '0.2.2') {
|
||||
requireThat(manifest.source_sha === 'dfb97e9069682da2ec9cc2dd4edce7e61ae051f6', 'Frozen v0.2.2 source changed');
|
||||
for (const image of images) requireThat(downloaded.get(image.name).sha256 ===
|
||||
'bbfa8c6f2e5988e087ef5e1f255f0a477b152cf108aaccf299f0cb60d95a1110', 'Frozen v0.2.2 image changed');
|
||||
}
|
||||
}
|
||||
|
||||
export function validateDownloadedManifest(manifest, { version, source, images, files }) {
|
||||
requireThat(manifest?.version === version && manifest.source_sha === source && manifest.source_dirty === false,
|
||||
'Downloaded manifest version/source is invalid');
|
||||
requireThat(manifest.notarized === false && manifest.signing?.mode === 'ad-hoc' && manifest.signing.identity === '-',
|
||||
'Downloaded manifest signing is not the required ad-hoc identity');
|
||||
sameNames(manifest.artifacts?.map(item => item.file), images, 'Downloaded manifest artifacts');
|
||||
for (const name of images) {
|
||||
const item = manifest.artifacts.find(value => value.file === name), file = files.get(name);
|
||||
requireThat(item.bytes === file.bytes && item.sha256 === file.sha256 &&
|
||||
Array.isArray(item.architectures) && item.architectures.length === 1 && item.architectures[0] === 'arm64',
|
||||
`Downloaded manifest artifact differs: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyMeetingPackage(packagePath) {
|
||||
const packageInfo = await lstat(packagePath).catch(() => null);
|
||||
requireThat(packageInfo?.isDirectory() && !packageInfo.isSymbolicLink(), 'Meeting package directory is invalid');
|
||||
const packageRoot = await realpath(packagePath);
|
||||
const manifestPath = join(packagePath, 'manifest.json');
|
||||
await regularFile(manifestPath, 'Meeting package manifest', META_LIMIT);
|
||||
const manifest = json(await readFile(manifestPath), 'Meeting package manifest');
|
||||
requireThat(manifest?.version === 1 && HASH.test(manifest.template_sha256) &&
|
||||
manifest.files && typeof manifest.files === 'object' && !Array.isArray(manifest.files),
|
||||
'Meeting package manifest is invalid');
|
||||
requireThat(manifest.files['template.docx'] === manifest.template_sha256,
|
||||
'Meeting template is not bound to its package manifest');
|
||||
requireThat(manifest.template_sha256 === MEETING_TEMPLATE_SHA,
|
||||
'Meeting template checksum differs from the shipped template');
|
||||
sameNames(Object.keys(manifest.files), MEETING_FILES, 'Meeting package files');
|
||||
for (const [relative, expected] of Object.entries(manifest.files)) {
|
||||
requireThat(/^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[a-zA-Z0-9._/-]+$/.test(relative) && HASH.test(expected),
|
||||
'Meeting package manifest contains an unsafe file');
|
||||
const path = resolve(packagePath, relative);
|
||||
requireThat(path.startsWith(`${resolve(packagePath)}${sep}`) &&
|
||||
(await realpath(path)).startsWith(`${packageRoot}${sep}`), 'Meeting package file escapes its bundle');
|
||||
await regularFile(path, `Meeting package file ${relative}`, 64 * META_LIMIT);
|
||||
requireThat(await hashFile(path) === expected, `Meeting package checksum differs: ${relative}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyDownloadedNative({ images, version, environment, run = nativeCommand }) {
|
||||
const tempBase = await realpath(environment.TMPDIR || tmpdir());
|
||||
const scratch = await mkdtemp(join(tempBase, 'iriz-release-verify-'));
|
||||
const mount = join(scratch, 'mount'), copiedApp = join(scratch, 'iriz.app'), home = join(scratch, 'home');
|
||||
const launchTemp = join(scratch, 'tmp'), shots = join(scratch, 'shots');
|
||||
await Promise.all([mkdir(mount), mkdir(home, { mode: 0o700 }), mkdir(launchTemp, { mode: 0o700 }), mkdir(shots)]);
|
||||
const cleanEnvironment = {
|
||||
HOME: home, CFFIXED_USER_HOME: home, TMPDIR: launchTemp,
|
||||
PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8',
|
||||
};
|
||||
let mounted = false, failure;
|
||||
try {
|
||||
for (const image of images)
|
||||
await run('/usr/bin/hdiutil', ['verify', image], { env: cleanEnvironment, timeout: 120_000 });
|
||||
await run('/usr/bin/hdiutil', ['attach', '-readonly', '-nobrowse', '-noautoopen', '-mountpoint', mount, images[0]],
|
||||
{ env: cleanEnvironment, timeout: 120_000 });
|
||||
mounted = true;
|
||||
const app = join(mount, 'iriz.app'), executable = join(app, 'Contents', 'MacOS', 'iriz');
|
||||
const appInfo = await lstat(app).catch(() => null);
|
||||
requireThat(appInfo?.isDirectory() && !appInfo.isSymbolicLink(), 'Mounted DMG has no regular iriz.app bundle');
|
||||
const appRoot = await realpath(app);
|
||||
requireThat(appRoot.startsWith(`${await realpath(mount)}${sep}`) &&
|
||||
(await realpath(executable)).startsWith(`${appRoot}${sep}`), 'Mounted app paths escape the DMG');
|
||||
const executableInfo = await regularFile(executable, 'Mounted app executable');
|
||||
requireThat((executableInfo.mode & 0o111) !== 0, 'Mounted app executable is not executable');
|
||||
const applications = join(mount, 'Applications'), applicationsInfo = await lstat(applications).catch(() => null);
|
||||
requireThat(applicationsInfo?.isSymbolicLink() && await readlink(applications) === '/Applications',
|
||||
'Mounted DMG Applications link is invalid');
|
||||
const resources = join(app, 'Contents', 'Resources');
|
||||
for (const bundle of ['IrizApp_IrizCore.bundle', 'IrizApp_IrizDictate.bundle']) {
|
||||
const info = await lstat(join(resources, bundle)).catch(() => null);
|
||||
requireThat(info?.isDirectory() && !info.isSymbolicLink(), `Mounted app resource bundle missing: ${bundle}`);
|
||||
}
|
||||
await verifyMeetingPackage(join(resources, 'IrizApp_IrizDictate.bundle', 'MeetingMinutes'));
|
||||
await regularFile(join(app, 'Contents', 'Info.plist'), 'Mounted app Info.plist', META_LIMIT);
|
||||
const plistVersion = await run('/usr/bin/plutil', ['-extract', 'CFBundleShortVersionString', 'raw',
|
||||
'-o', '-', join(app, 'Contents', 'Info.plist')], { env: cleanEnvironment });
|
||||
requireThat(String(plistVersion.stdout).trim() === version, 'Mounted app bundle version differs');
|
||||
const minimumOS = await run('/usr/bin/plutil', ['-extract', 'LSMinimumSystemVersion', 'raw',
|
||||
'-o', '-', join(app, 'Contents', 'Info.plist')], { env: cleanEnvironment });
|
||||
requireThat(String(minimumOS.stdout).trim() === '14.0', 'Mounted app minimum macOS version differs');
|
||||
const architecture = await run('/usr/bin/lipo', ['-archs', executable], { env: cleanEnvironment });
|
||||
requireThat(String(architecture.stdout).trim() === 'arm64', 'Mounted app executable is not exact arm64');
|
||||
await run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=2', app], { env: cleanEnvironment });
|
||||
const signature = await run('/usr/bin/codesign', ['-dv', '--verbose=4', app], { env: cleanEnvironment });
|
||||
requireThat(/(?:^|\n)Signature=adhoc(?:\n|$)/.test(`${signature.stdout}\n${signature.stderr}`),
|
||||
'Mounted app signature is not ad-hoc');
|
||||
await run('/usr/bin/ditto', [app, copiedApp], { env: cleanEnvironment, timeout: 120_000 });
|
||||
const copiedInfo = await lstat(copiedApp).catch(() => null);
|
||||
requireThat(copiedInfo?.isDirectory() && !copiedInfo.isSymbolicLink() &&
|
||||
(await realpath(copiedApp)).startsWith(`${await realpath(scratch)}${sep}`),
|
||||
'Copied app bundle is invalid');
|
||||
await run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=2', copiedApp],
|
||||
{ env: cleanEnvironment });
|
||||
await run('/usr/bin/hdiutil', ['detach', mount], { env: cleanEnvironment, timeout: 30_000 });
|
||||
mounted = false;
|
||||
const copiedExecutable = join(copiedApp, 'Contents', 'MacOS', 'iriz');
|
||||
await run(copiedExecutable, ['--export-ui-shots', shots],
|
||||
{ cwd: home, env: cleanEnvironment, timeout: 120_000 });
|
||||
const shotEntries = await readdir(shots, { withFileTypes: true });
|
||||
const shotFiles = shotEntries.filter(entry => entry.isFile()).map(entry => entry.name);
|
||||
sameNames(shotFiles, UI_SHOT_NAMES, 'Copied app UI shots');
|
||||
for (const name of UI_SHOT_NAMES) {
|
||||
await regularFile(join(shots, name), `UI shot ${name}`, 32 * META_LIMIT);
|
||||
const handle = await open(join(shots, name), 'r');
|
||||
const signature = Buffer.alloc(8);
|
||||
try { requireThat((await handle.read(signature)).bytesRead === 8 &&
|
||||
signature.equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])), `UI shot is not PNG: ${name}`); }
|
||||
finally { await handle.close(); }
|
||||
}
|
||||
} catch (error) { failure = error; }
|
||||
finally {
|
||||
if (mounted) {
|
||||
try {
|
||||
await run('/usr/bin/hdiutil', ['detach', mount], { env: cleanEnvironment, timeout: 30_000 });
|
||||
mounted = false;
|
||||
}
|
||||
catch (error) { if (!failure) failure = error; }
|
||||
}
|
||||
if (!mounted) {
|
||||
try { await rm(scratch, { recursive: true, force: true }); }
|
||||
catch (error) { if (!failure) failure = error; }
|
||||
}
|
||||
}
|
||||
if (failure) throw failure;
|
||||
}
|
||||
|
||||
export async function verifyDownloadedRelease({
|
||||
environment = process.env, nativeProbe = verifyDownloadedNative,
|
||||
} = {}) {
|
||||
const assetInput = environment.PRODUCT_RELEASE_ASSET_DIR;
|
||||
const version = environment.PRODUCT_RELEASE_VERSION;
|
||||
const tag = environment.PRODUCT_RELEASE_TAG;
|
||||
const source = environment.PRODUCT_RELEASE_SOURCE_SHA;
|
||||
const token = environment.PRODUCT_RELEASE_VERIFY_TOKEN;
|
||||
requireThat(typeof assetInput === 'string' && assetInput.length > 0, 'PRODUCT_RELEASE_ASSET_DIR is required');
|
||||
requireThat(/^\d+\.\d+\.\d+$/.test(version || '') && tag === `v${version}`,
|
||||
'Downloaded release version/tag is invalid');
|
||||
requireThat(SHA.test(source || ''), 'Downloaded release source SHA is invalid');
|
||||
requireThat(typeof token === 'string' && /^[a-zA-Z0-9._-]{16,256}$/.test(token),
|
||||
'Downloaded release verify token is invalid');
|
||||
requireThat(['draft', 'published-assets'].includes(environment.PRODUCT_RELEASE_STAGE),
|
||||
'Downloaded release stage is invalid');
|
||||
requireThat(resolve(assetInput) === assetInput, 'Downloaded release asset path must be absolute');
|
||||
const inputInfo = await lstat(assetInput).catch(() => null);
|
||||
requireThat(inputInfo?.isDirectory() && !inputInfo.isSymbolicLink(),
|
||||
'Downloaded release asset path is not a regular directory');
|
||||
const assetDir = await realpath(assetInput);
|
||||
const rootInfo = await lstat(assetDir);
|
||||
requireThat(rootInfo.isDirectory() && !rootInfo.isSymbolicLink(), 'Downloaded release asset path is not a directory');
|
||||
const images = [`iriz-${version}-arm64.dmg`, 'iriz-macos-arm64.dmg'];
|
||||
const expected = [...images, 'release-manifest.json', 'SHA256SUMS.txt'];
|
||||
const entries = await readdir(assetDir, { withFileTypes: true });
|
||||
const rootFiles = entries.filter(entry => entry.isFile()).map(entry => entry.name);
|
||||
sameNames(rootFiles, expected, 'Downloaded release root files');
|
||||
for (const entry of entries) {
|
||||
requireThat(expected.includes(entry.name) ||
|
||||
(entry.isDirectory() && ['verifier-home', 'verifier-tmp'].includes(entry.name)),
|
||||
`Downloaded release has unexpected root entry: ${entry.name}`);
|
||||
}
|
||||
const files = new Map();
|
||||
for (const name of expected) {
|
||||
const path = join(assetDir, name);
|
||||
const info = await regularFile(path, `Downloaded release file ${name}`,
|
||||
name.endsWith('.dmg') ? DMG_LIMIT : META_LIMIT);
|
||||
files.set(name, { path, bytes: info.size, sha256: await hashFile(path) });
|
||||
}
|
||||
requireThat(await sameFileBytes(files.get(images[0]).path, files.get(images[1]).path),
|
||||
'Downloaded stable and versioned DMGs differ byte-for-byte');
|
||||
const expectedSums = expected.filter(name => name !== 'SHA256SUMS.txt');
|
||||
const sums = checksums(await readFile(files.get('SHA256SUMS.txt').path), expectedSums);
|
||||
for (const [name, digest] of sums)
|
||||
requireThat(files.get(name).sha256 === digest, `Downloaded SHA256SUMS mismatch: ${name}`);
|
||||
const manifest = json(await readFile(files.get('release-manifest.json').path), 'Downloaded manifest');
|
||||
validateDownloadedManifest(manifest, { version, source, images, files });
|
||||
await nativeProbe({ images: images.map(name => files.get(name).path), version, environment });
|
||||
return `PRODUCT_RELEASE_VERIFIED=${token}`;
|
||||
}
|
||||
|
||||
export async function verifyRelease(options = {}) {
|
||||
const deadline = Date.now() + 600_000;
|
||||
const get = (url, extra = {}) => request(url, { ...options, deadline, ...extra });
|
||||
const getJSON = async url => json((await get(url, { timeoutMs: 30_000 })).body, 'GitHub API');
|
||||
const snapshot = releaseSnapshot(await getJSON(`${API}/releases/latest`));
|
||||
const downloaded = new Map();
|
||||
for (const asset of snapshot.assets) {
|
||||
const stable = asset.name === 'iriz-macos-arm64.dmg';
|
||||
const result = await get(stable ? STABLE : asset.url, {
|
||||
maxBytes: asset.name.endsWith('.dmg') ? DMG_LIMIT : META_LIMIT,
|
||||
expectedBytes: asset.size, capture: !asset.name.endsWith('.dmg'), dmg: asset.name.endsWith('.dmg'),
|
||||
});
|
||||
requireThat(!stable || result.redirects.includes(asset.url), 'Stable URL resolved to another release');
|
||||
requireThat(result.sha256 === asset.digest, `GitHub SHA-256 mismatch: ${asset.name}`);
|
||||
downloaded.set(asset.name, result);
|
||||
}
|
||||
const versioned = downloaded.get(`iriz-${snapshot.version}-arm64.dmg`);
|
||||
const stable = downloaded.get('iriz-macos-arm64.dmg');
|
||||
requireThat(stable.sha256 === versioned.sha256 && stable.bytes === versioned.bytes, 'Stable and versioned images differ');
|
||||
const expectedSums = snapshot.assets.map(asset => asset.name).filter(name => name !== 'SHA256SUMS.txt');
|
||||
for (const [name, hash] of checksums(downloaded.get('SHA256SUMS.txt').body, expectedSums))
|
||||
requireThat(downloaded.get(name).sha256 === hash, `SHA256SUMS mismatch: ${name}`);
|
||||
const manifest = json(downloaded.get('release-manifest.json').body, 'Manifest');
|
||||
validateManifest(manifest, snapshot, downloaded);
|
||||
const ref = await getJSON(`${API}/git/ref/tags/${snapshot.tag}`);
|
||||
requireThat(ref.ref === `refs/tags/${snapshot.tag}`, 'Release tag ref differs');
|
||||
let object = ref.object;
|
||||
for (let depth = 0; object?.type === 'tag' && depth < 3; depth++) {
|
||||
requireThat(SHA.test(object.sha), 'Invalid annotated tag SHA');
|
||||
const tag = await getJSON(`${API}/git/tags/${object.sha}`);
|
||||
requireThat(tag.sha === object.sha, 'Annotated tag SHA differs');
|
||||
object = tag.object;
|
||||
}
|
||||
requireThat(object?.type === 'commit' && object.sha === manifest.source_sha, 'Release tag does not resolve to manifest source');
|
||||
const commit = await getJSON(`${API}/commits/${manifest.source_sha}`);
|
||||
requireThat(commit.sha === manifest.source_sha, 'Manifest source commit does not exist');
|
||||
const finalSnapshot = releaseSnapshot(await getJSON(`${API}/releases/latest`));
|
||||
requireThat(JSON.stringify(snapshot) === JSON.stringify(finalSnapshot), 'Latest release changed during verification; rerun against a stable release');
|
||||
return { version: snapshot.version, source_sha: manifest.source_sha, bytes: stable.bytes, sha256: stable.sha256 };
|
||||
}
|
||||
|
||||
function attribute(tag, name) {
|
||||
return new RegExp(`(?:^|\\s)${name}\\s*=\\s*(["'])(.*?)\\1`, 'i').exec(tag)?.[2];
|
||||
}
|
||||
|
||||
export function validateReadme(text, filename, heading, badgePath) {
|
||||
const start = '<!-- application-downloads:start -->';
|
||||
const end = '<!-- application-downloads:end -->';
|
||||
// Check rendered content, including whether the entire block was commented out.
|
||||
text = text.replace(/<!--[\s\S]*?-->/g, comment => [start, end].includes(comment) ? comment : '');
|
||||
let fence;
|
||||
text = text.split('\n').filter(line => {
|
||||
const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
||||
if (fence) {
|
||||
if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;
|
||||
return false;
|
||||
}
|
||||
if (marker) { fence = marker[1]; return false; }
|
||||
return !/^(?: {4}|\t)/.test(line);
|
||||
}).join('\n').replace(/<(pre|code)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi, '');
|
||||
requireThat(text.split(start).length === 2 && text.split(end).length === 2, `${filename}: one application download block required`);
|
||||
const from = text.indexOf(start), to = text.indexOf(end);
|
||||
const what = text.indexOf(`\n## ${heading}\n`);
|
||||
const contents = text.indexOf(`\n## ${LOCALES.find(([name]) => name === filename)?.[2]}\n`);
|
||||
requireThat(contents >= 0 && contents < from && from < to && what > to, `${filename}: application download must follow Contents and precede ${heading}`);
|
||||
const block = text.slice(from + start.length, to);
|
||||
const images = [...block.matchAll(/<a\b([^>]*)>([\s\S]*?)<\/a>/gi)]
|
||||
.filter(match => /<img\b/i.test(match[2]));
|
||||
requireThat(images.length === 1 && attribute(images[0][1], 'href') === STABLE,
|
||||
`${filename}: one linked application badge required`);
|
||||
const image = /<img\b([^>]*)>/i.exec(images[0][2]);
|
||||
requireThat(image && attribute(image[1], 'src') === badgePath && attribute(image[1], 'alt')?.trim() &&
|
||||
attribute(image[1], 'width') === '180', `${filename}: application badge image/alt/width differs`);
|
||||
const oldShield = /\[!\[[^\]]*\]\(https:\/\/img\.shields\.io\/[^\n]*\)\]\(https:\/\/github\.com\/zarubinvibe\/iriz\/releases\/latest\/download\/iriz-macos-arm64\.dmg\)/;
|
||||
requireThat(!oldShield.test(text), `${filename}: obsolete Shields download CTA remains`);
|
||||
for (const match of text.matchAll(/<a\b([^>]*)>([\s\S]*?)<\/a>/gi)) {
|
||||
if (attribute(match[1], 'href') === STABLE && /<img\b/i.test(match[2]))
|
||||
requireThat(match.index > from && match.index < to, `${filename}: application badge outside its block`);
|
||||
}
|
||||
}
|
||||
|
||||
export function validateBadgePNG(png) {
|
||||
requireThat(png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])), 'Invalid badge PNG signature');
|
||||
const compressed = [];
|
||||
let width, height, ended = false;
|
||||
for (let offset = 8; offset < png.length;) {
|
||||
requireThat(offset + 12 <= png.length, 'Truncated badge PNG chunk');
|
||||
const length = png.readUInt32BE(offset), type = png.toString('ascii', offset + 4, offset + 8);
|
||||
const end = offset + length + 12;
|
||||
requireThat(end <= png.length, 'Truncated badge PNG data');
|
||||
requireThat(crc32(png.subarray(offset + 4, end - 4)) === png.readUInt32BE(end - 4), 'Badge PNG chunk checksum differs');
|
||||
if (offset === 8) requireThat(type === 'IHDR', 'Badge PNG has no IHDR');
|
||||
if (type === 'IHDR') {
|
||||
requireThat(offset === 8 && length === 13, 'Invalid badge PNG IHDR');
|
||||
width = png.readUInt32BE(offset + 8); height = png.readUInt32BE(offset + 12);
|
||||
// ponytail: the approved badge is RGBA8 without interlacing; extend only for a redesigned asset.
|
||||
requireThat(width > 0 && height > 0 && width * height <= 4_000_000 &&
|
||||
png.subarray(offset + 16, offset + 21).equals(Buffer.from([8, 6, 0, 0, 0])), 'Unsupported badge PNG dimensions/format');
|
||||
} else if (type === 'IDAT') compressed.push(png.subarray(offset + 8, end - 4));
|
||||
else if (type === 'IEND') {
|
||||
requireThat(length === 0 && end === png.length, 'Invalid badge PNG ending');
|
||||
ended = true;
|
||||
} else requireThat(/^[a-z]/.test(type) || type === 'PLTE', 'Unknown critical badge PNG chunk');
|
||||
offset = end;
|
||||
}
|
||||
requireThat(ended && compressed.length > 0, 'Incomplete badge PNG');
|
||||
const stride = width * 4 + 1, expected = stride * height;
|
||||
const pixels = inflateSync(Buffer.concat(compressed), { maxOutputLength: expected });
|
||||
requireThat(pixels.length === expected, 'Badge PNG pixel data is truncated');
|
||||
for (let row = 0; row < height; row++) requireThat(pixels[row * stride] <= 4, 'Invalid badge PNG row filter');
|
||||
}
|
||||
|
||||
export async function verifyReadmes(root = ROOT) {
|
||||
const base = await realpath(root);
|
||||
const read = async (path, limit = META_LIMIT) => {
|
||||
const absolute = await realpath(resolve(base, path));
|
||||
requireThat(absolute.startsWith(`${base}${sep}`), 'Local asset escapes checkout');
|
||||
const info = await stat(absolute);
|
||||
requireThat(info.isFile() && info.size > 0 && info.size <= limit, `Invalid local file: ${path}`);
|
||||
return readFile(absolute);
|
||||
};
|
||||
const config = json(await read('.github/family-page.json'), 'Family page');
|
||||
requireThat(config.owner === 'zarubinvibe' && config.slug === 'iriz', 'Unexpected family page repository');
|
||||
const downloads = config.application?.downloads;
|
||||
requireThat(Array.isArray(downloads) && downloads.length === 1 && downloads[0].id === 'macos-arm64' &&
|
||||
downloads[0].kind === 'direct' && downloads[0].url === STABLE, 'Application download configuration differs');
|
||||
const badge = downloads[0].badge;
|
||||
requireThat(badge && /^docs\/assets\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+\.png$/.test(badge.path) && HASH.test(badge.sha256) && badge.width === 180, 'Invalid application badge configuration');
|
||||
const png = await read(badge.path, 8 * META_LIMIT);
|
||||
requireThat(sha256(png) === badge.sha256, 'Application badge hash differs');
|
||||
validateBadgePNG(png);
|
||||
for (const [filename, heading] of LOCALES)
|
||||
validateReadme((await read(filename)).toString('utf8'), filename, heading, badge.path);
|
||||
return LOCALES.map(([filename]) => filename);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
assert(args.length <= 1 && (!args.length || ['--selftest', '--local'].includes(args[0])), 'Usage: node scripts/check_app_download.mjs [--selftest|--local]');
|
||||
if (args[0] === '--selftest') return (await import('./check_app_download_test.mjs')).selftest();
|
||||
if (process.env.PRODUCT_RELEASE_ASSET_DIR) {
|
||||
assert(args.length === 0, 'Downloaded release verification takes no arguments');
|
||||
console.log(await verifyDownloadedRelease());
|
||||
return;
|
||||
}
|
||||
const readmes = await verifyReadmes();
|
||||
console.log(`PASS: application download CTA in ${readmes.join(', ')}`);
|
||||
if (args[0] === '--local') return;
|
||||
console.log('Checking the public release anonymously (maximum 10 minutes).');
|
||||
const result = await verifyRelease();
|
||||
console.log(`PASS: v${result.version}, ${result.bytes} bytes per DMG, SHA-256 ${result.sha256}, source ${result.source_sha}`);
|
||||
console.log('Download integrity verified. macOS installation, signature, permissions and dictation require separate checks.');
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href)
|
||||
main().catch(error => { console.error(`FAIL: ${error.message}`); process.exitCode = 1; });
|
||||
@@ -0,0 +1,374 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmod, cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { crc32, deflateSync } from 'node:zlib';
|
||||
import { API, DOWNLOAD, STABLE, sha256, trustedURL, request, releaseSnapshot,
|
||||
checksums, validateManifest, validateReadme, validateBadgePNG, verifyRelease,
|
||||
verifyDownloadedNative, verifyDownloadedRelease, UI_SHOT_NAMES } from './check_app_download.mjs';
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
|
||||
async function downloadedFixture(work) {
|
||||
const root = await mkdtemp(join(tmpdir(), 'iriz-downloaded-release-test-'));
|
||||
const version = '9.8.7', source = 'a'.repeat(40), token = 'receipt-token-123456';
|
||||
const images = [`iriz-${version}-arm64.dmg`, 'iriz-macos-arm64.dmg'];
|
||||
const dmg = Buffer.from('synthetic identical dmg bytes');
|
||||
const manifest = {
|
||||
version, source_sha: source, source_dirty: false, notarized: false,
|
||||
signing: { mode: 'ad-hoc', identity: '-' },
|
||||
artifacts: images.map(file => ({
|
||||
file, bytes: dmg.length, sha256: sha256(dmg), architectures: ['arm64'],
|
||||
})),
|
||||
};
|
||||
const files = new Map(images.map(name => [name, dmg]));
|
||||
files.set('release-manifest.json', Buffer.from(JSON.stringify(manifest)));
|
||||
files.set('SHA256SUMS.txt', Buffer.from([...files]
|
||||
.map(([name, bytes]) => `${sha256(bytes)} ${name}\n`).join('')));
|
||||
for (const [name, bytes] of files) await writeFile(join(root, name), bytes);
|
||||
const writeChecksums = async () => {
|
||||
const bytes = Buffer.from([...files].filter(([name]) => name !== 'SHA256SUMS.txt')
|
||||
.map(([name, value]) => `${sha256(value)} ${name}\n`).join(''));
|
||||
files.set('SHA256SUMS.txt', bytes);
|
||||
await writeFile(join(root, 'SHA256SUMS.txt'), bytes);
|
||||
};
|
||||
const writeManifest = async value => {
|
||||
const bytes = Buffer.from(JSON.stringify(value));
|
||||
files.set('release-manifest.json', bytes);
|
||||
await writeFile(join(root, 'release-manifest.json'), bytes);
|
||||
await writeChecksums();
|
||||
};
|
||||
const environment = {
|
||||
PRODUCT_RELEASE_ASSET_DIR: root,
|
||||
PRODUCT_RELEASE_VERSION: version,
|
||||
PRODUCT_RELEASE_TAG: `v${version}`,
|
||||
PRODUCT_RELEASE_SOURCE_SHA: source,
|
||||
PRODUCT_RELEASE_VERIFY_TOKEN: token,
|
||||
PRODUCT_RELEASE_STAGE: 'draft',
|
||||
};
|
||||
try { return await work({ root, environment, manifest, files, images, token, writeChecksums, writeManifest }); }
|
||||
finally { await rm(root, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
function nativeFixtureRunner({ failCodesign = false, minimumOS = '14.0', shotNames = UI_SHOT_NAMES } = {}) {
|
||||
const calls = [];
|
||||
const run = async (command, args, options = {}) => {
|
||||
calls.push([command, ...args]);
|
||||
assert.equal(options.env.GH_TOKEN, undefined);
|
||||
assert.equal(options.env.HOME, options.env.CFFIXED_USER_HOME);
|
||||
if (command === '/usr/bin/hdiutil' && args[0] === 'attach') {
|
||||
const mount = args[args.indexOf('-mountpoint') + 1];
|
||||
const resources = join(mount, 'iriz.app', 'Contents', 'Resources');
|
||||
const meeting = join(resources, 'IrizApp_IrizDictate.bundle', 'MeetingMinutes');
|
||||
const executable = join(mount, 'iriz.app', 'Contents', 'MacOS', 'iriz');
|
||||
await mkdir(join(resources, 'IrizApp_IrizCore.bundle'), { recursive: true });
|
||||
await mkdir(join(executable, '..'), { recursive: true });
|
||||
await writeFile(executable, 'synthetic executable');
|
||||
await writeFile(join(mount, 'iriz.app', 'Contents', 'Info.plist'), 'synthetic plist');
|
||||
await chmod(executable, 0o755);
|
||||
await symlink('/Applications', join(mount, 'Applications'));
|
||||
await cp(new URL('../Sources/IrizDictate/Resources/MeetingMinutes', import.meta.url), meeting,
|
||||
{ recursive: true });
|
||||
}
|
||||
if (command === '/usr/bin/plutil') return {
|
||||
stdout: `${args.includes('LSMinimumSystemVersion') ? minimumOS : '9.8.7'}\n`, stderr: '',
|
||||
};
|
||||
if (command === '/usr/bin/lipo') return { stdout: 'arm64\n', stderr: '' };
|
||||
if (command === '/usr/bin/codesign' && args[0] === '-dv') {
|
||||
if (failCodesign) throw new Error('synthetic codesign failure');
|
||||
return { stdout: '', stderr: 'Signature=adhoc\nTeamIdentifier=not set\n' };
|
||||
}
|
||||
if (command === '/usr/bin/ditto') await cp(args[0], args[1], { recursive: true });
|
||||
if (args[0] === '--export-ui-shots') {
|
||||
assert.equal(options.cwd, options.env.HOME);
|
||||
for (const name of shotNames) await writeFile(join(args[1], name), PNG_SIGNATURE);
|
||||
}
|
||||
return { stdout: '', stderr: '' };
|
||||
};
|
||||
return { calls, run };
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const version = '9.8.7';
|
||||
const source = 'a'.repeat(40);
|
||||
const dmg = Buffer.alloc(768, 7);
|
||||
dmg.write('koly', dmg.length - 512);
|
||||
const images = [`iriz-${version}-arm64.dmg`, 'iriz-macos-arm64.dmg'];
|
||||
const manifest = { version, source_sha: source, source_dirty: false,
|
||||
artifacts: images.map(file => ({ file, bytes: dmg.length, sha256: sha256(dmg), architectures: ['arm64'] })) };
|
||||
const files = new Map(images.map(name => [name, dmg]));
|
||||
files.set('release-manifest.json', Buffer.from(JSON.stringify(manifest)));
|
||||
files.set('SHA256SUMS.txt', Buffer.from([...files].map(([name, bytes]) => `${sha256(bytes)} ${name}\n`).join('')));
|
||||
const release = { id: 123, tag_name: `v${version}`, draft: false, prerelease: false,
|
||||
assets: [...files].map(([name, bytes], index) => ({ name, id: index + 1, state: 'uploaded',
|
||||
size: bytes.length, digest: `sha256:${sha256(bytes)}`, browser_download_url: `${DOWNLOAD}/download/v${version}/${name}` })) };
|
||||
const calls = [];
|
||||
let latestReads = 0;
|
||||
const data = { files, release, manifest, calls, source, version, changeLatest: false, annotated: false };
|
||||
data.fetchImpl = async (url, options) => {
|
||||
calls.push(url);
|
||||
assert.equal(options.credentials, 'omit');
|
||||
assert.equal(options.redirect, 'manual');
|
||||
assert.equal(options.headers.Authorization, undefined);
|
||||
assert.equal(options.headers.Cookie, undefined);
|
||||
assert.equal(options.headers['Accept-Encoding'], 'identity');
|
||||
const response = bytes => new Response(bytes, { headers: { 'content-length': String(Buffer.byteLength(bytes)) } });
|
||||
const json = object => response(JSON.stringify(object));
|
||||
if (url === `${API}/releases/latest`) {
|
||||
latestReads++;
|
||||
return json(data.changeLatest && latestReads > 1 ? { ...release, id: 124 } : release);
|
||||
}
|
||||
if (url === `${API}/git/ref/tags/v${version}`) return json({ ref: `refs/tags/v${version}`,
|
||||
object: { type: data.annotated ? 'tag' : 'commit', sha: data.annotated ? 'b'.repeat(40) : source } });
|
||||
if (url === `${API}/git/tags/${'b'.repeat(40)}`) return json({ sha: 'b'.repeat(40), object: { type: 'commit', sha: source } });
|
||||
if (url === `${API}/commits/${source}`) return json({ sha: source });
|
||||
if (url === STABLE) return new Response(null, { status: 302,
|
||||
headers: { location: `${DOWNLOAD}/download/v${version}/iriz-macos-arm64.dmg` } });
|
||||
if (url.startsWith(`${DOWNLOAD}/download/v${version}/`)) return new Response(null, { status: 302,
|
||||
headers: { location: `https://release-assets.githubusercontent.com/fixture/${url.split('/').at(-1)}?signature=private-in-logs` } });
|
||||
if (url.startsWith('https://release-assets.githubusercontent.com/fixture/')) {
|
||||
const name = new URL(url).pathname.split('/').at(-1);
|
||||
const body = files.get(name);
|
||||
return body ? response(body) : new Response(null, { status: 404 });
|
||||
}
|
||||
throw new Error(`Unexpected fixture URL: ${url}`);
|
||||
};
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function selftest() {
|
||||
let passed = 0;
|
||||
const test = async (name, work) => {
|
||||
try { await work(); passed++; }
|
||||
catch (error) { throw new Error(`Selftest ${name}: ${error.message}`); }
|
||||
};
|
||||
const run = data => verifyRelease({ fetchImpl: data.fetchImpl, retryDelayMs: 0 });
|
||||
const reject = async (data, pattern) => assert.rejects(() => run(data), pattern);
|
||||
const responseOptions = body => ({ fetchImpl: async () => new Response(body), attempts: 1, retryDelayMs: 0 });
|
||||
|
||||
await test('complete anonymous release', async () => {
|
||||
const data = fixture(), result = await run(data);
|
||||
assert.equal(result.version, data.version);
|
||||
assert.equal(result.bytes, 768);
|
||||
assert.equal(result.source_sha, data.source);
|
||||
assert.equal(data.calls.filter(url => url === `${API}/releases/latest`).length, 2);
|
||||
assert(data.calls.includes(STABLE));
|
||||
});
|
||||
await test('annotated tag', async () => { const data = fixture(); data.annotated = true; await run(data); });
|
||||
await test('network retry recovers', async () => {
|
||||
let calls = 0;
|
||||
const result = await request(STABLE, { retryDelayMs: 0, fetchImpl: async () => {
|
||||
if (++calls === 1) throw new Error('offline');
|
||||
return new Response('ok');
|
||||
} });
|
||||
assert.equal(result.bytes, 2); assert.equal(calls, 2);
|
||||
});
|
||||
await test('network retry bounded', async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(() => request(STABLE, { retryDelayMs: 0, fetchImpl: async () => { calls++; throw new Error('offline'); } }), /network request failed/);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
await test('HTTP retry bounded', async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(() => request(STABLE, { retryDelayMs: 0,
|
||||
fetchImpl: async () => { calls++; return new Response(null, { status: 503 }); } }), /503/);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
await test('rate limit is not green', async () => {
|
||||
await assert.rejects(() => request(STABLE, { fetchImpl: async () => new Response(null,
|
||||
{ status: 403, headers: { 'x-ratelimit-remaining': '0' } }) }), /rate limit exhausted/);
|
||||
});
|
||||
await test('request timeout', async () => {
|
||||
await assert.rejects(() => request(STABLE, { attempts: 1, timeoutMs: 5,
|
||||
fetchImpl: (_url, options) => new Promise((_resolve, rejectPromise) => options.signal.addEventListener('abort', () => rejectPromise(new Error('abort')))) }), /timed out/);
|
||||
});
|
||||
await test('stalled response body timeout', async () => {
|
||||
await assert.rejects(() => request(STABLE, { attempts: 1, timeoutMs: 5,
|
||||
fetchImpl: async (_url, options) => new Response(new ReadableStream({ start(controller) {
|
||||
options.signal.addEventListener('abort', () => controller.error(new Error('aborted')));
|
||||
} })) }), /body timed out/);
|
||||
});
|
||||
await test('run deadline', async () => assert.rejects(() => request(STABLE, {
|
||||
deadline: Date.now() - 1, fetchImpl: async () => { throw new Error('must not fetch'); } }), /deadline exceeded/));
|
||||
await test('untrusted URL boundaries', () => {
|
||||
for (const url of ['http://github.com/test', 'https://github.com.evil.test/', 'https://127.0.0.1/',
|
||||
'https://[::1]/', 'https://169.254.169.254/', 'https://github.com:444/',
|
||||
'https://user:password@github.com/', 'https://evil.test/', 'file:///tmp/file', 'https://github.com/#token'])
|
||||
assert.throws(() => trustedURL(url), /Untrusted/);
|
||||
});
|
||||
await test('unsafe redirects never fetched', async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(() => request(STABLE, { fetchImpl: async () => {
|
||||
calls++; return new Response(null, { status: 302, headers: { location: 'https://127.0.0.1/metadata' } });
|
||||
} }), /Untrusted/);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
await test('redirect loop bounded', async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(() => request(STABLE, { fetchImpl: async () => { calls++;
|
||||
return new Response(null, { status: 302, headers: { location: STABLE } }); } }), /Too many/);
|
||||
assert.equal(calls, 6);
|
||||
});
|
||||
await test('missing redirect location', async () => assert.rejects(() => request(STABLE,
|
||||
{ fetchImpl: async () => new Response(null, { status: 302 }) }), /no Location/));
|
||||
await test('HTML 200 without MIME', async () => assert.rejects(() => request(STABLE,
|
||||
responseOptions('<!doctype html><html>error</html>')), /HTML/));
|
||||
await test('HTML 200 MIME', async () => assert.rejects(() => request(STABLE,
|
||||
{ fetchImpl: async () => new Response('arbitrary', { headers: { 'content-type': 'text/html' } }) }), /HTML/));
|
||||
await test('empty response', async () => assert.rejects(() => request(STABLE, responseOptions('')), /Empty/));
|
||||
await test('truncated body', async () => assert.rejects(() => request(STABLE,
|
||||
{ fetchImpl: async () => new Response('short', { headers: { 'content-length': '10' } }) }), /Truncated/));
|
||||
await test('body exceeds size limit', async () => assert.rejects(() => request(STABLE,
|
||||
{ ...responseOptions('overflow'), maxBytes: 4 }), /size limit/));
|
||||
await test('oversized headers', async () => assert.rejects(() => request(STABLE,
|
||||
{ maxBytes: 4, fetchImpl: async () => new Response('x', { headers: { 'content-length': '5' } }) }), /oversized/));
|
||||
await test('expected asset size mismatch', async () => assert.rejects(() => request(STABLE,
|
||||
{ ...responseOptions('short'), expectedBytes: 10 }), /size differs/));
|
||||
await test('corrupt DMG trailer', async () => assert.rejects(() => request(STABLE,
|
||||
{ ...responseOptions(Buffer.alloc(768)), dmg: true }), /DMG trailer/));
|
||||
await test('interrupted body', async () => assert.rejects(() => request(STABLE,
|
||||
{ fetchImpl: async () => new Response(new ReadableStream({ start(controller) { controller.error(new Error('stream interrupted')); } })) }), /stream interrupted/));
|
||||
await test('empty release asset list', () => { const data = fixture(); data.release.assets = []; assert.throws(() => releaseSnapshot(data.release), /filenames/); });
|
||||
await test('unexpected release asset', () => { const data = fixture(); data.release.assets[0].name = '../other.dmg'; assert.throws(() => releaseSnapshot(data.release), /filenames/); });
|
||||
await test('duplicate release asset', () => { const data = fixture(); data.release.assets[0] = data.release.assets[1]; assert.throws(() => releaseSnapshot(data.release), /filenames/); });
|
||||
await test('missing GitHub digest', () => { const data = fixture(); data.release.assets[0].digest = null; assert.throws(() => releaseSnapshot(data.release), /digest/); });
|
||||
await test('metadata cannot choose another host', () => { const data = fixture(); data.release.assets[0].browser_download_url = 'https://evil.test/a'; assert.throws(() => releaseSnapshot(data.release), /Unexpected asset URL/); });
|
||||
await test('missing file', async () => { const data = fixture(); data.files.delete('iriz-macos-arm64.dmg'); await reject(data, /404/); });
|
||||
await test('wrong digest', async () => {
|
||||
const data = fixture(), copy = Buffer.from(data.files.get('iriz-macos-arm64.dmg'));
|
||||
copy[0] ^= 1; data.files.set('iriz-macos-arm64.dmg', copy); await reject(data, /SHA-256 mismatch/);
|
||||
});
|
||||
await test('stable resolves to wrong version', async () => {
|
||||
const data = fixture(), original = data.fetchImpl;
|
||||
data.fetchImpl = (url, options) => url === STABLE ? new Response(null, { status: 302,
|
||||
headers: { location: 'https://release-assets.githubusercontent.com/fixture/iriz-macos-arm64.dmg' } }) : original(url, options);
|
||||
await reject(data, /another release/);
|
||||
});
|
||||
await test('latest changed mid-download', async () => { const data = fixture(); data.changeLatest = true; await reject(data, /Latest release changed/); });
|
||||
await test('checksums reject malicious names and duplicates', () => {
|
||||
for (const text of ['', `${'a'.repeat(64)} ../file\n`, `${'a'.repeat(64)} $(touch_file)\n`, `${'a'.repeat(64)} good\n${'a'.repeat(64)} good\n`])
|
||||
assert.throws(() => checksums(Buffer.from(text), ['good']), /filename/);
|
||||
});
|
||||
await test('manifest wrong version and dirty source', () => {
|
||||
const data = fixture(), snapshot = releaseSnapshot(data.release);
|
||||
assert.throws(() => validateManifest({ ...data.manifest, version: '0.0.0' }, snapshot, new Map()), /version\/source/);
|
||||
assert.throws(() => validateManifest({ ...data.manifest, source_dirty: true }, snapshot, new Map()), /version\/source/);
|
||||
});
|
||||
await test('downloaded release emits receipt only after native verification', () => downloadedFixture(async data => {
|
||||
let probed = false;
|
||||
const receipt = await verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => { probed = true; } });
|
||||
assert.equal(probed, true);
|
||||
assert.equal(receipt, `PRODUCT_RELEASE_VERIFIED=${data.token}`);
|
||||
}));
|
||||
await test('downloaded release refuses invalid receipt token', () => downloadedFixture(async data => {
|
||||
data.environment.PRODUCT_RELEASE_VERIFY_TOKEN = '';
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => assert.fail('native probe must not run') }), /verify token/);
|
||||
}));
|
||||
await test('downloaded release refuses invalid stage', () => downloadedFixture(async data => {
|
||||
data.environment.PRODUCT_RELEASE_STAGE = 'published';
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => assert.fail('native probe must not run') }), /stage/);
|
||||
}));
|
||||
await test('downloaded release refuses manifest contract drift', () => downloadedFixture(async data => {
|
||||
await data.writeManifest({ ...data.manifest, source_dirty: true });
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => assert.fail('native probe must not run') }), /manifest version\/source/);
|
||||
await data.writeManifest({ ...data.manifest, signing: { mode: 'self-signed', identity: 'local' } });
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => assert.fail('native probe must not run') }), /required ad-hoc/);
|
||||
}));
|
||||
await test('downloaded release refuses checksum mismatch', () => downloadedFixture(async data => {
|
||||
const bad = Buffer.from(data.files.get('SHA256SUMS.txt').toString().replace(/^[a-f0-9]{64}/, '0'.repeat(64)));
|
||||
await writeFile(join(data.root, 'SHA256SUMS.txt'), bad);
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => assert.fail('native probe must not run') }), /SHA256SUMS mismatch/);
|
||||
}));
|
||||
await test('downloaded release propagates native probe failure without receipt', () => downloadedFixture(async data => {
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: async () => { throw new Error('synthetic hdiutil failure'); } }), /synthetic hdiutil failure/);
|
||||
}));
|
||||
await test('downloaded native probe uses readonly mount and clean launch smoke', () => downloadedFixture(async data => {
|
||||
const native = nativeFixtureRunner();
|
||||
const receipt = await verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: input => verifyDownloadedNative({ ...input, run: native.run }) });
|
||||
assert.equal(receipt, `PRODUCT_RELEASE_VERIFIED=${data.token}`);
|
||||
assert.equal(native.calls.filter(call => call[0] === '/usr/bin/hdiutil' && call[1] === 'verify').length, 2);
|
||||
assert(native.calls.some(call => call[0] === '/usr/bin/hdiutil' && call[1] === 'attach' &&
|
||||
call.includes('-readonly') && call.includes('-nobrowse') && call.includes('-noautoopen')));
|
||||
assert(native.calls.some(call => call[0] === '/usr/bin/lipo' && call[1] === '-archs'));
|
||||
assert.equal(native.calls.filter(call => call[0] === '/usr/bin/codesign' && call[1] === '--verify').length, 2);
|
||||
assert(native.calls.some(call => call[0] === '/usr/bin/ditto'));
|
||||
const detach = native.calls.findIndex(call => call[0] === '/usr/bin/hdiutil' && call[1] === 'detach');
|
||||
const launch = native.calls.findIndex(call => call[1] === '--export-ui-shots');
|
||||
assert(detach >= 0 && launch > detach && native.calls[launch][0].includes('/iriz.app/Contents/MacOS/iriz'));
|
||||
}));
|
||||
await test('downloaded native probe requires macOS 14', () => downloadedFixture(async data => {
|
||||
const native = nativeFixtureRunner({ minimumOS: '13.0' });
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: input => verifyDownloadedNative({ ...input, run: native.run }) }), /minimum macOS/);
|
||||
assert.equal(native.calls.at(-1)[0], '/usr/bin/hdiutil');
|
||||
assert.equal(native.calls.at(-1)[1], 'detach');
|
||||
}));
|
||||
await test('downloaded native probe requires every expected UI shot', () => downloadedFixture(async data => {
|
||||
const native = nativeFixtureRunner({ shotNames: UI_SHOT_NAMES.slice(1) });
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: input => verifyDownloadedNative({ ...input, run: native.run }) }), /UI shots/);
|
||||
}));
|
||||
await test('downloaded native probe detaches after mounted check failure', () => downloadedFixture(async data => {
|
||||
const native = nativeFixtureRunner({ failCodesign: true });
|
||||
await assert.rejects(() => verifyDownloadedRelease({ environment: data.environment,
|
||||
nativeProbe: input => verifyDownloadedNative({ ...input, run: native.run }) }), /synthetic codesign failure/);
|
||||
assert.equal(native.calls.at(-1)[0], '/usr/bin/hdiutil');
|
||||
assert.equal(native.calls.at(-1)[1], 'detach');
|
||||
assert(!native.calls.some(call => call[1] === '--export-ui-shots'));
|
||||
}));
|
||||
const badge = 'docs/assets/download-macos.png';
|
||||
const block = `<!-- application-downloads:start -->\n<a href="${STABLE}"><img src="${badge}" alt="Download for macOS" width="180"></a>\n[Download](${STABLE})\n<!-- application-downloads:end -->`;
|
||||
const readme = `# iriz\n\n## Contents\n\n${block}\n\n## What This Is\n`;
|
||||
await test('README badge after Contents and before What', () => validateReadme(readme, 'README.md', 'What This Is', badge));
|
||||
await test('README badge missing', () => assert.throws(() => validateReadme(readme.replace('<img', '<span'), 'README.md', 'What This Is', badge), /badge/));
|
||||
await test('README wrong href', () => assert.throws(() => validateReadme(readme.replace(`href="${STABLE}"`, 'href="https://example.com"'), 'README.md', 'What This Is', badge), /badge/));
|
||||
await test('README badge below What', () => assert.throws(() => validateReadme(`\n## What This Is\n${block}`, 'README.md', 'What This Is', badge), /precede/));
|
||||
await test('README obsolete CTA', () => assert.throws(() => validateReadme(`${readme}\n[](${STABLE})`, 'README.md', 'What This Is', badge), /obsolete/));
|
||||
await test('README commented badge', () => assert.throws(() => validateReadme(readme.replace('<a href', '<!-- <a href').replace('</a>', '</a> -->'), 'README.md', 'What This Is', badge), /badge/));
|
||||
await test('README whole block commented out', () => assert.throws(() => validateReadme(readme.replace(block, `<!-- hidden\n${block}\n-->`), 'README.md', 'What This Is', badge), /block required/));
|
||||
await test('README whole block inside code fence', () => assert.throws(() => validateReadme(readme.replace(block, `\`\`\`html\n${block}\n\`\`\``), 'README.md', 'What This Is', badge), /block required/));
|
||||
await test('README unclosed code fence', () => assert.throws(() => validateReadme(readme.replace(block, `\`\`\`html\n${block}`), 'README.md', 'What This Is', badge), /block required/));
|
||||
await test('README indented code', () => assert.throws(() => validateReadme(readme.replace(block, block.split('\n').map(line => ` ${line}`).join('\n')), 'README.md', 'What This Is', badge), /block required/));
|
||||
await test('README preformatted block', () => assert.throws(() => validateReadme(readme.replace(block, `<pre>\n${block}\n</pre>`), 'README.md', 'What This Is', badge), /block required/));
|
||||
await test('README badge width zero', () => assert.throws(() => validateReadme(readme.replace('width="180"', 'width="0"'), 'README.md', 'What This Is', badge), /width/));
|
||||
await test('README data attributes are not links', () => assert.throws(() => validateReadme(readme.replace('href=', 'data-href='), 'README.md', 'What This Is', badge), /badge/));
|
||||
await test('README data source is not an image', () => assert.throws(() => validateReadme(readme.replace('src=', 'data-src='), 'README.md', 'What This Is', badge), /image/));
|
||||
await test('README badge before Contents', () => assert.throws(() => validateReadme(`# iriz\n${block}\n## Contents\n\n## What This Is\n`, 'README.md', 'What This Is', badge), /follow Contents/));
|
||||
const pngChunk = (name, bytes) => {
|
||||
const result = Buffer.alloc(bytes.length + 12);
|
||||
result.writeUInt32BE(bytes.length); result.write(name, 4); bytes.copy(result, 8);
|
||||
result.writeUInt32BE(crc32(result.subarray(4, result.length - 4)), result.length - 4);
|
||||
return result;
|
||||
};
|
||||
const pngHeader = PNG_SIGNATURE;
|
||||
const ihdr = Buffer.from([0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]);
|
||||
const png = Buffer.concat([pngHeader, pngChunk('IHDR', ihdr), pngChunk('IDAT', deflateSync(Buffer.alloc(5))), pngChunk('IEND', Buffer.alloc(0))]);
|
||||
await test('valid badge PNG', () => validateBadgePNG(png));
|
||||
await test('PNG signature alone is not an image', () => assert.throws(() => validateBadgePNG(pngHeader), /Incomplete/));
|
||||
await test('truncated PNG', () => assert.throws(() => validateBadgePNG(png.subarray(0, -1)), /Truncated/));
|
||||
await test('PNG CRC differs', () => {
|
||||
const broken = Buffer.from(png); broken[20] ^= 1;
|
||||
assert.throws(() => validateBadgePNG(broken), /checksum/);
|
||||
});
|
||||
await test('PNG missing pixels', () => assert.throws(() => validateBadgePNG(Buffer.concat([
|
||||
pngHeader, pngChunk('IHDR', ihdr), pngChunk('IDAT', deflateSync(Buffer.alloc(1))), pngChunk('IEND', Buffer.alloc(0)),
|
||||
])), /pixel data/));
|
||||
await test('workflow stays public and read-only', async () => {
|
||||
const workflow = await readFile(new URL('../.github/workflows/app-download.yml', import.meta.url), 'utf8');
|
||||
assert.match(workflow, /github\.repository == 'zarubinvibe\/iriz' && github\.event\.repository\.visibility == 'public'/);
|
||||
assert.match(workflow, /contents: read/);
|
||||
assert.match(workflow, /persist-credentials: false/);
|
||||
assert.match(workflow, /runs-on: ubuntu-24\.04/);
|
||||
assert.match(workflow, /timeout-minutes: 15/);
|
||||
assert.doesNotMatch(workflow, /contents: write|GH_TOKEN|GITHUB_TOKEN|secrets\.|schedule:|pull_request_target:/);
|
||||
});
|
||||
console.log(`PASS: ${passed} offline app-download checks`);
|
||||
}
|
||||
+164
-73
@@ -22,8 +22,10 @@ minutes_files=(template.docx data.schema.json fields.json manifest.json README.m
|
||||
# ponytail: один диспетчер вместо библиотеки моков; настоящий DMG проверяет macOS CI.
|
||||
cat > "$test_root/bin/stub" <<'STUB'
|
||||
#!/bin/bash
|
||||
_test_stub_impl() (
|
||||
set -euo pipefail
|
||||
name="$(basename "$0")"
|
||||
name="$1"
|
||||
shift
|
||||
printf '%s' "$name" >> "$TEST_TRACE"
|
||||
printf ' <%s>' "$@" >> "$TEST_TRACE"
|
||||
printf '\n' >> "$TEST_TRACE"
|
||||
@@ -246,6 +248,17 @@ case "$name" in
|
||||
;;
|
||||
*) deny "$@" ;;
|
||||
esac
|
||||
)
|
||||
|
||||
if [ "${BASH_SOURCE[0]}" != "$0" ]; then
|
||||
for test_command in swift lipo vtool otool hdiutil codesign install_name_tool plutil git python3 \
|
||||
security xcrun osascript tiffutil curl wget open killall pkill kill ditto spctl python \
|
||||
cp mv rm mkdir touch ln; do
|
||||
eval "$test_command() { _test_stub_impl $test_command \"\$@\"; }"
|
||||
done
|
||||
else
|
||||
_test_stub_impl "$(basename "$0")" "$@"
|
||||
fi
|
||||
STUB
|
||||
chmod +x "$test_root/bin/stub"
|
||||
for command in swift lipo vtool otool hdiutil codesign install_name_tool plutil git python3 \
|
||||
@@ -253,9 +266,25 @@ for command in swift lipo vtool otool hdiutil codesign install_name_tool plutil
|
||||
cp mv rm mkdir touch ln; do
|
||||
ln -s stub "$test_root/bin/$command"
|
||||
done
|
||||
cat > "$test_root/no-kill.sh" <<'STUB'
|
||||
kill() { printf 'forbidden builtin kill\n' >> "$TEST_TRACE"; return 97; }
|
||||
STUB
|
||||
|
||||
probe_stub() {
|
||||
local label="$1" probe_command="$2" probe_status=0
|
||||
: > "$test_root/stub-probe-trace"
|
||||
env -i PATH="$test_root/bin:/usr/bin:/bin:/usr/sbin:/sbin" \
|
||||
BASH_ENV="$test_root/bin/stub" TEST_TRACE="$test_root/stub-probe-trace" \
|
||||
/bin/bash -c "$probe_command" >/dev/null 2>&1 || probe_status=$?
|
||||
[ "$probe_status" = 97 ] || {
|
||||
printf 'make_release_test: %s: заглушка вернула %s вместо 97\n' "$label" "$probe_status" >&2
|
||||
exit 1
|
||||
}
|
||||
[ "$(sed -n '1p' "$test_root/stub-probe-trace")" = 'security <unexpected>' ] \
|
||||
&& [ "$(wc -l < "$test_root/stub-probe-trace" | tr -d ' ')" = 1 ] || {
|
||||
printf 'make_release_test: %s: вызов не записан в trace ровно один раз\n' "$label" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
probe_stub 'shell function' 'security unexpected'
|
||||
probe_stub 'PATH executable' '/usr/bin/env security unexpected'
|
||||
|
||||
checks=0
|
||||
new_case() {
|
||||
@@ -284,7 +313,7 @@ run_release() {
|
||||
status=0
|
||||
(cd "$case_root" && env -i PATH="$test_root/bin:/usr/bin:/bin:/usr/sbin:/sbin" \
|
||||
TMPDIR="$case_root" LANG=en_US.UTF-8 \
|
||||
BASH_ENV="$test_root/no-kill.sh" TEST_CASE_ROOT="$case_root" \
|
||||
BASH_ENV="$test_root/bin/stub" TEST_CASE_ROOT="$case_root" \
|
||||
TEST_TRACE="$case_root/trace" TEST_REAL_PYTHON="$real_python" \
|
||||
TEST_MINUTES_FIXTURE="$test_root/MeetingMinutes" TEST_MINUTES_SHA="$minutes_sha" \
|
||||
SMLTLK_SIGN_IDENTITY=- IRIZ_DMG_HEADLESS=1 "$@" \
|
||||
@@ -340,97 +369,166 @@ expect_pass() {
|
||||
checks=$((checks + 1))
|
||||
}
|
||||
|
||||
for version in '../escape' '1.2.3/escape' '1.2.3;echo' ''; do
|
||||
parallel_pids=()
|
||||
parallel_failed=0
|
||||
parallel_limit=4
|
||||
wait_oldest_parallel() {
|
||||
local pid="${parallel_pids[0]}"
|
||||
wait "$pid" || parallel_failed=1
|
||||
parallel_pids=("${parallel_pids[@]:1}")
|
||||
}
|
||||
|
||||
wait_parallel_batch() {
|
||||
while [ "${#parallel_pids[@]}" -gt 0 ]; do wait_oldest_parallel; done
|
||||
[ "$parallel_failed" = 0 ]
|
||||
}
|
||||
|
||||
queue_parallel_case() {
|
||||
local case_number=$checks
|
||||
checks=$((checks + 1))
|
||||
if [ "${#parallel_pids[@]}" = "$parallel_limit" ]; then wait_oldest_parallel; fi
|
||||
(
|
||||
checks=$case_number
|
||||
"$@"
|
||||
) &
|
||||
parallel_pids+=("$!")
|
||||
}
|
||||
|
||||
parallel_expect_fail() {
|
||||
local label="$1" pattern="$2"
|
||||
shift 2
|
||||
new_case
|
||||
expect_fail "$label" "$pattern" "$@"
|
||||
}
|
||||
|
||||
parallel_expect_pass() {
|
||||
new_case
|
||||
expect_pass "$@"
|
||||
}
|
||||
|
||||
parallel_version_guard() {
|
||||
local version="$1"
|
||||
new_case
|
||||
if [ -z "$version" ]; then printf '\n' > "$case_root/RELEASE_VERSION"; fi
|
||||
expect_fail guard 'версия должна иметь вид' "SMLTLK_VERSION=$version"
|
||||
done
|
||||
}
|
||||
|
||||
for scratch in / /Applications '../outside' '.'; do
|
||||
parallel_symlink_guard() {
|
||||
new_case
|
||||
expect_fail guard 'рабочий путь должен быть внутри' "SMLTLK_SCRATCH=$scratch"
|
||||
done
|
||||
ln -s "$test_root" "$case_root/release/linked-scratch"
|
||||
expect_fail guard 'рабочий путь.*без симлинков' \
|
||||
"SMLTLK_SCRATCH=$case_root/release/linked-scratch/build"
|
||||
}
|
||||
|
||||
new_case
|
||||
ln -s "$test_root" "$case_root/release/linked-scratch"
|
||||
expect_fail guard 'рабочий путь.*без симлинков' "SMLTLK_SCRATCH=$case_root/release/linked-scratch/build"
|
||||
|
||||
new_case
|
||||
expect_fail guard 'нотаризация требует Developer ID Application' IRIZ_NOTARY_PROFILE=fixture
|
||||
|
||||
new_case
|
||||
expect_fail guard 'рабочий путь должен быть внутри' IRIZ_RELEASE_DIST=/
|
||||
|
||||
new_case
|
||||
expect_fail guard 'scratch и dist должны быть раздельными' "SMLTLK_SCRATCH=$case_root/release/dist/build"
|
||||
|
||||
new_case
|
||||
expect_fail 'resource bundle' 'нет ресурсного IrizApp_IrizCore[.]bundle' TEST_FAULT=missing-bundle
|
||||
|
||||
new_case
|
||||
expect_fail 'localization resources' 'в бандле нет таблицы перевода zh-hans' TEST_FAULT=missing-locale
|
||||
|
||||
for fault in minutes-bundle minutes-digest minutes-symlink minutes-extra-symlink; do
|
||||
new_case
|
||||
reason='пакет протокола MeetingMinutes не найден'
|
||||
parallel_minutes_fault() {
|
||||
local fault="$1" reason='пакет протокола MeetingMinutes не найден'
|
||||
case "$fault" in
|
||||
minutes-digest) reason='SHA-256 шаблона протокола не совпадает с эталоном$' ;;
|
||||
*symlink) reason='симлинк в пакете протокола:' ;;
|
||||
esac
|
||||
new_case
|
||||
expect_fail "$fault" "$reason" "TEST_FAULT=$fault"
|
||||
[ -f "$case_root/injected-fault" ] || fail "$fault: сбой пакета не был внедрён"
|
||||
done
|
||||
for minutes_file in "${minutes_files[@]}"; do
|
||||
}
|
||||
|
||||
parallel_missing_minutes_file() {
|
||||
local minutes_file="$1"
|
||||
new_case
|
||||
expect_fail "missing $minutes_file" 'пакет протокола' TEST_FAULT=minutes-file "TEST_MISSING_FILE=$minutes_file"
|
||||
grep -Fxq "make_release: пакет протокола: отсутствует или пуст $minutes_file" "$case_root/output" \
|
||||
|| fail 'неверная причина отказа или не назван отсутствующий файл пакета'
|
||||
[ -f "$case_root/injected-fault" ] || fail 'пропажа файла пакета не была внедрена'
|
||||
}
|
||||
|
||||
parallel_rpath_prefix() {
|
||||
new_case
|
||||
expect_fail 'rpath prefix' 'rpath фреймворков отсутствует после упаковки' TEST_FAULT=rpath-prefix
|
||||
grep -q '^install_name_tool ' "$case_root/trace" || fail 'rpath prefix: FrameworksExtra принят за Frameworks'
|
||||
}
|
||||
|
||||
parallel_mounted_fault() {
|
||||
local fault="$1" reason='смонтированный .* неполон или подпись в нём не проходит'
|
||||
if [ "$fault" = mounted-arch ]; then reason='в .*/mount[.].*/iriz[.]app/Contents/MacOS/iriz нет архитектуры arm64'; fi
|
||||
if [ "$fault" = mounted-minutes-file ]; then reason='пакет протокола: отсутствует или пуст template[.]docx$'; fi
|
||||
new_case
|
||||
expect_fail "$fault" "$reason" "TEST_FAULT=$fault"
|
||||
[ -f "$case_root/injected-fault" ] || fail "$fault: отказ не был внедрён в смонтированный образ"
|
||||
cmp -s "$case_root/owned-mount" "$case_root/detached-mount" || fail "$fault: собственный том остался подключён"
|
||||
[ "$(grep -c '^hdiutil <detach>' "$case_root/trace")" = 1 ] || fail "$fault: лишний detach"
|
||||
}
|
||||
|
||||
for version in '../escape' '1.2.3/escape' '1.2.3;echo' ''; do
|
||||
queue_parallel_case parallel_version_guard "$version"
|
||||
done
|
||||
|
||||
new_case
|
||||
expect_fail 'arm64 framework' 'в whisper[.]framework нет архитектуры arm64' TEST_FAULT=framework-arm64
|
||||
for scratch in / /Applications '../outside' '.'; do
|
||||
queue_parallel_case parallel_expect_fail guard 'рабочий путь должен быть внутри' \
|
||||
"SMLTLK_SCRATCH=$scratch"
|
||||
done
|
||||
|
||||
new_case
|
||||
expect_fail 'universal framework' 'в whisper[.]framework нет архитектуры x86_64' \
|
||||
queue_parallel_case parallel_symlink_guard
|
||||
queue_parallel_case parallel_expect_fail guard \
|
||||
'нотаризация требует Developer ID Application' IRIZ_NOTARY_PROFILE=fixture
|
||||
queue_parallel_case parallel_expect_fail guard \
|
||||
'рабочий путь должен быть внутри' IRIZ_RELEASE_DIST=/
|
||||
queue_parallel_case parallel_expect_fail guard \
|
||||
'scratch и dist должны быть раздельными' \
|
||||
"SMLTLK_SCRATCH=$test_root/case-$checks with space/release/dist/build"
|
||||
|
||||
queue_parallel_case parallel_expect_fail 'resource bundle' \
|
||||
'нет ресурсного IrizApp_IrizCore[.]bundle' TEST_FAULT=missing-bundle
|
||||
queue_parallel_case parallel_expect_fail 'localization resources' \
|
||||
'в бандле нет таблицы перевода zh-hans' TEST_FAULT=missing-locale
|
||||
|
||||
for fault in minutes-bundle minutes-digest minutes-symlink minutes-extra-symlink; do
|
||||
queue_parallel_case parallel_minutes_fault "$fault"
|
||||
done
|
||||
for minutes_file in "${minutes_files[@]}"; do
|
||||
queue_parallel_case parallel_missing_minutes_file "$minutes_file"
|
||||
done
|
||||
queue_parallel_case parallel_expect_fail 'arm64 framework' \
|
||||
'в whisper[.]framework нет архитектуры arm64' TEST_FAULT=framework-arm64
|
||||
queue_parallel_case parallel_expect_fail 'universal framework' \
|
||||
'в whisper[.]framework нет архитектуры x86_64' \
|
||||
IRIZ_RELEASE_VARIANTS='arm64 universal' TEST_FAULT=framework-universal
|
||||
|
||||
new_case
|
||||
expect_fail 'rpath install' 'не удалось добавить rpath фреймворков' TEST_FAULT=rpath-install
|
||||
|
||||
new_case
|
||||
expect_fail 'rpath no-op' 'rpath фреймворков отсутствует после упаковки' TEST_FAULT=rpath-noop
|
||||
|
||||
new_case
|
||||
expect_fail 'rpath prefix' 'rpath фреймворков отсутствует после упаковки' TEST_FAULT=rpath-prefix
|
||||
grep -q '^install_name_tool ' "$case_root/trace" || fail 'rpath prefix: FrameworksExtra принят за Frameworks'
|
||||
queue_parallel_case parallel_expect_fail 'rpath install' \
|
||||
'не удалось добавить rpath фреймворков' TEST_FAULT=rpath-install
|
||||
queue_parallel_case parallel_expect_fail 'rpath no-op' \
|
||||
'rpath фреймворков отсутствует после упаковки' TEST_FAULT=rpath-noop
|
||||
queue_parallel_case parallel_rpath_prefix
|
||||
|
||||
for target in app framework; do
|
||||
binary='IrizApp'
|
||||
if [ "$target" = framework ]; then binary='whisper[.]framework/whisper'; fi
|
||||
for fault in minos-missing platform-ios minos-high; do
|
||||
new_case
|
||||
expect_fail "$target $fault" "minOS/платформа не подтверждены для каждого среза .*/$binary$" \
|
||||
queue_parallel_case parallel_expect_fail "$target $fault" \
|
||||
"minOS/платформа не подтверждены для каждого среза .*/$binary$" \
|
||||
"TEST_FAULT=$target-$fault"
|
||||
done
|
||||
done
|
||||
|
||||
new_case
|
||||
expect_fail 'DMG verify' 'шаг «hdiutil verify [(]arm64[)]» упал[.]' TEST_FAULT=dmg-verify
|
||||
queue_parallel_case parallel_expect_fail 'DMG verify' \
|
||||
'шаг «hdiutil verify [(]arm64[)]» упал[.]' TEST_FAULT=dmg-verify
|
||||
|
||||
for fault in mounted-signature mounted-arch mounted-minutes-file; do
|
||||
new_case
|
||||
reason='смонтированный .* неполон или подпись в нём не проходит'
|
||||
if [ "$fault" = mounted-arch ]; then reason='в .*/mount[.].*/iriz[.]app/Contents/MacOS/iriz нет архитектуры arm64'; fi
|
||||
if [ "$fault" = mounted-minutes-file ]; then reason='пакет протокола: отсутствует или пуст template[.]docx$'; fi
|
||||
expect_fail "$fault" "$reason" "TEST_FAULT=$fault"
|
||||
[ -f "$case_root/injected-fault" ] || fail "$fault: отказ не был внедрён в смонтированный образ"
|
||||
cmp -s "$case_root/owned-mount" "$case_root/detached-mount" || fail "$fault: собственный том остался подключён"
|
||||
[ "$(grep -c '^hdiutil <detach>' "$case_root/trace")" = 1 ] || fail "$fault: лишний detach"
|
||||
queue_parallel_case parallel_mounted_fault "$fault"
|
||||
done
|
||||
|
||||
new_case
|
||||
expect_pass
|
||||
default_case_root="$test_root/case-$checks with space"
|
||||
queue_parallel_case parallel_expect_pass
|
||||
universal_case_root="$test_root/case-$checks with space"
|
||||
queue_parallel_case parallel_expect_pass IRIZ_RELEASE_VARIANTS='arm64 universal' SMLTLK_VERSION=2.3.4 \
|
||||
"IRIZ_RELEASE_DIST=$universal_case_root/release/custom-dist" IRIZ_DMG_HEADLESS= CI=true
|
||||
notary_case_root="$test_root/case-$checks with space"
|
||||
queue_parallel_case parallel_expect_pass TEST_NOTARY=1 IRIZ_NOTARY_PROFILE=fixture \
|
||||
'SMLTLK_SIGN_IDENTITY=Developer ID Application: Fixture (TEST123)'
|
||||
anchor_case_root="$test_root/case-$checks with space"
|
||||
queue_parallel_case parallel_expect_fail 'DMG Apple anchor' \
|
||||
'шаг «проверка подписи образа arm64» упал[.]' \
|
||||
TEST_NOTARY=1 IRIZ_NOTARY_PROFILE=fixture TEST_FAULT=dmg-anchor \
|
||||
'SMLTLK_SIGN_IDENTITY=Developer ID Application: Fixture (TEST123)'
|
||||
wait_parallel_batch
|
||||
|
||||
case_root="$default_case_root"
|
||||
[ -f "$case_root/release/dist/iriz-1.2.3-arm64.dmg" ] || fail 'нет versioned arm64 DMG'
|
||||
[ -f "$case_root/release/dist/iriz-macos-arm64.dmg" ] || fail 'нет стабильного arm64 alias'
|
||||
if grep -q -- '<x86_64>' "$case_root/trace"; then fail 'universal собрался без opt-in'; fi
|
||||
@@ -462,15 +560,11 @@ for row in manifest["artifacts"]:
|
||||
assert (dist / "iriz-1.2.3-arm64.dmg").read_bytes() == (dist / "iriz-macos-arm64.dmg").read_bytes()
|
||||
PY
|
||||
|
||||
new_case
|
||||
expect_pass IRIZ_RELEASE_VARIANTS='arm64 universal' SMLTLK_VERSION=2.3.4 \
|
||||
"IRIZ_RELEASE_DIST=$case_root/release/custom-dist" IRIZ_DMG_HEADLESS= CI=true
|
||||
case_root="$universal_case_root"
|
||||
[ -f "$case_root/release/custom-dist/iriz-2.3.4-universal.dmg" ] || fail 'opt-in universal не собрался'
|
||||
grep -q -- '<x86_64>' "$case_root/trace" || fail 'universal не запросил x86_64'
|
||||
|
||||
new_case
|
||||
expect_pass TEST_NOTARY=1 IRIZ_NOTARY_PROFILE=fixture \
|
||||
'SMLTLK_SIGN_IDENTITY=Developer ID Application: Fixture (TEST123)'
|
||||
case_root="$notary_case_root"
|
||||
"$real_python" - "$case_root" <<'PY'
|
||||
import json, pathlib, re, sys
|
||||
root = pathlib.Path(sys.argv[1])
|
||||
@@ -490,10 +584,7 @@ assert manifest["signing"] == {"identity": "Developer ID Application: Fixture (T
|
||||
"mode": "developer-id", "targets": ["app", "dmg"]}, manifest
|
||||
PY
|
||||
|
||||
new_case
|
||||
expect_fail 'DMG Apple anchor' 'шаг «проверка подписи образа arm64» упал[.]' \
|
||||
TEST_NOTARY=1 IRIZ_NOTARY_PROFILE=fixture TEST_FAULT=dmg-anchor \
|
||||
'SMLTLK_SIGN_IDENTITY=Developer ID Application: Fixture (TEST123)'
|
||||
case_root="$anchor_case_root"
|
||||
[ -f "$case_root/injected-fault" ] || fail 'Apple anchor: отказ не был внедрён'
|
||||
if grep -Eq '^xcrun <notarytool> <submit> <[^>]*[.]dmg>' "$case_root/trace"; then
|
||||
fail 'DMG отправлен на нотаризацию после отказа Apple anchor'
|
||||
|
||||
Reference in New Issue
Block a user