Compare commits

..

1 Commits

Author SHA1 Message Date
mnovak 04a6031c5d [browser] Firefox: one extension source for Firefox, Edge and Chrome; frames, public suffixes, the caller check, 2FA codes and saving logins; v0.20.0
- custos-browser: fill_allowed (a frame gets a login only when its page would too), public suffixes match
  exactly only (psl), ports digits only, caller (which extension started the host); spoof tests.
- custos-native: answers not_allowed to anything but the Custos extension, browser_totp and browser_save,
  the frame's and the page's origins, a random session per connection (its match code on Custos's cards).
- extension/: manifest.firefox.json (gecko id custos@marek-novak.cz) and manifest.chromium.json, one set of
  scripts; the popup shows 2FA codes, the save offer and the connection's code; tools/extension.mjs builds
  each browser and reproducible zips; tools/extension-test.mjs runs the background against a fake browser.
2026-11-22 21:57:35 +01:00
25 changed files with 1508 additions and 1335 deletions
+8 -4
View File
@@ -1,7 +1,7 @@
# Custos Domi — core (public) # Custos Domi — core (public)
Custos (Latin: guardian) is a local-first password and secret manager in the Domi ecosystem. Custos (Latin: guardian) is a local-first password and secret manager in the Domi ecosystem.
This repository is the **public, CPAL-1.0 core** (MPL-2.0 before v0.20.0): everything that touches plaintext or keys. This repository is the **public, MPL-2.0 core**: everything that touches plaintext or keys.
The Windows app lives in the private `Custos` repo and depends on this one by git tag. The Windows app lives in the private `Custos` repo and depends on this one by git tag.
## Layout ## Layout
@@ -16,9 +16,11 @@ crates/custos-team team vaults' pure parts: member keys, policy evaluation, s
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli
crates/custos-browser which login belongs on which page (origins, no fuzzy matching), native messaging frames crates/custos-browser which login belongs on which page and frame (origins, public suffixes, no fuzzy matching),
crates/custos-native the browser extension's native messaging host: three ops, rebuilt, to custos.exe's pipe only which extension started the host, native messaging frames
extension/ the MV3 extension for Edge and Chrome (fixed id jchkapmceepdnlhagfppeckggaecdcmn) crates/custos-native the browser extension's native messaging host: five browser_* ops, rebuilt, to custos.exe's pipe only
extension/ the MV3 extension, one source for Firefox (custos@marek-novak.cz) and Edge/Chrome (fixed id
jchkapmceepdnlhagfppeckggaecdcmn); tools/extension.mjs builds each, tools/extension-test.mjs
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code) docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
docs/FACTORS.md version 2: any two factors open the vault; the machine store docs/FACTORS.md version 2: any two factors open the vault; the machine store
docs/KEYS.md secret keys, API keys and key pairs docs/KEYS.md secret keys, API keys and key pairs
@@ -36,6 +38,8 @@ docs/TEAM.md team vaults (member slots, kind 6), policies, sign.request
``` ```
cargo test --workspace # all mandatory tests cargo test --workspace # all mandatory tests
cargo test --workspace --release # same, faster Argon2 cargo test --workspace --release # same, faster Argon2
node tools/extension-test.mjs # the extension's background against a fake browser
node tools/extension.mjs --zip # target/extension/{firefox,chromium}/ and their zips
# the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake): # the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake):
nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm
node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it
Generated
+30 -13
View File
@@ -329,14 +329,15 @@ dependencies = [
[[package]] [[package]]
name = "custos-browser" name = "custos-browser"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"psl",
"zeroize", "zeroize",
] ]
[[package]] [[package]]
name = "custos-gen" name = "custos-gen"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"custos-vault", "custos-vault",
"data-encoding", "data-encoding",
@@ -348,7 +349,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-kdbx" name = "custos-kdbx"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"aes", "aes",
"argon2", "argon2",
@@ -369,7 +370,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-keys" name = "custos-keys"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"custos-vault", "custos-vault",
"ed25519-dalek", "ed25519-dalek",
@@ -382,9 +383,10 @@ dependencies = [
[[package]] [[package]]
name = "custos-native" name = "custos-native"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"custos-browser", "custos-browser",
"rand 0.10.3",
"serde_json", "serde_json",
"windows-sys", "windows-sys",
"zeroize", "zeroize",
@@ -392,11 +394,11 @@ dependencies = [
[[package]] [[package]]
name = "custos-qr" name = "custos-qr"
version = "0.21.0" version = "0.20.0"
[[package]] [[package]]
name = "custos-seal" name = "custos-seal"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"chacha20poly1305", "chacha20poly1305",
"hkdf", "hkdf",
@@ -409,7 +411,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-share" name = "custos-share"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"argon2", "argon2",
"chacha20poly1305", "chacha20poly1305",
@@ -426,7 +428,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-sign" name = "custos-sign"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"blake2 0.10.6", "blake2 0.10.6",
"data-encoding", "data-encoding",
@@ -446,7 +448,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-team" name = "custos-team"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"custos-seal", "custos-seal",
"custos-sign", "custos-sign",
@@ -464,7 +466,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-totp" name = "custos-totp"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"custos-vault", "custos-vault",
"data-encoding", "data-encoding",
@@ -477,7 +479,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-vault" name = "custos-vault"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"argon2", "argon2",
"bip39", "bip39",
@@ -503,7 +505,7 @@ dependencies = [
[[package]] [[package]]
name = "custos-wasm" name = "custos-wasm"
version = "0.21.0" version = "0.20.0"
dependencies = [ dependencies = [
"custos-qr", "custos-qr",
"custos-seal", "custos-seal",
@@ -1025,6 +1027,21 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "psl"
version = "2.1.261"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3058f918351d1ee290ff4e70243e419b33269dcb83bc8cd46c5afa8a97a90012"
dependencies = [
"psl-types",
]
[[package]]
name = "psl-types"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
[[package]] [[package]]
name = "qrcode" name = "qrcode"
version = "0.14.1" version = "0.14.1"
+2 -2
View File
@@ -3,9 +3,9 @@ resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package] [workspace.package]
version = "0.21.0" version = "0.20.0"
edition = "2024" edition = "2024"
license = "CPAL-1.0" license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
[workspace.dependencies] [workspace.dependencies]
+345 -140
View File
@@ -1,168 +1,373 @@
Common Public Attribution License Version 1.0 (CPAL) Mozilla Public License Version 2.0
==================================
1. “Definitions” 1. Definitions
--------------
1.0.1 “Commercial Use” means distribution or otherwise making the Covered Code available to a third party. 1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.1 “Contributor” means each entity that creates or contributes to the creation of Modifications. 1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.2 “Contributor Version” means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor. 1.3. "Contribution"
means Covered Software of a particular Contributor.
1.3 “Covered Code” means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof. 1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.4 “Electronic Distribution Mechanism” means a mechanism generally accepted in the software development community for the electronic transfer of data. 1.5. "Incompatible With Secondary Licenses"
means
1.5 “Executable” means Covered Code in any form other than Source Code. (a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
1.6 “Initial Developer” means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A. (b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.7 “Larger Work” means a work which combines Covered Code or portions thereof with code not governed by the terms of this License. 1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.8 “License” means this document. 1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8.1 “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein. 1.8. "License"
means this document.
1.9 “Modifications” means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is: 1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications. 1.10. "Modifications"
means any of the following:
B. Any new file that contains any part of the Original Code or previous Modifications. (a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
1.10 “Original Code” means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License. (b) any new file in Source Code Form that contains any Covered
Software.
1.10.1 “Patent Claims” means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor. 1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.11 “Source Code” means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor’s choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge. 1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.12 “You” (or “Your”) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, “You” includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 1.13. "Source Code Form"
means the form of the work preferred for making modifications.
2. Source Code License. 1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2.1 The Initial Developer Grant. 2. License Grants and Conditions
The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: --------------------------------
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and 2.1. Grants
(b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof). Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License. (a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices. (b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2 Contributor Grant. 2.2. Effective Date
Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination). 2.3. Limitations on Grant Scope
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code. The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
(d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor. distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
3. Distribution Obligations. Contributor:
3.1 Application of License. (a) for any code that a Contributor has removed from Covered Software;
The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients’ rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5. or
3.2 Availability of Source Code. (b) for infringements caused by: (i) Your and any other third party's
Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party. modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
3.3 Description of Modifications. Version); or
You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.
(c) under Patent Claims infringed by Covered Software in the absence of
3.4 Intellectual Property Matters its Contributions.
(a) Third Party Claims. If Contributor has knowledge that a license under a third party’s intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled “LEGAL” which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained. This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
(b) Contributor APIs. If Contributor’s Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file. the notice requirements in Section 3.4).
(c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor’s Modifications are Contributor’s original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License. 2.4. Subsequent Licenses
3.5 Required Notices. No Contributor makes additional grants as a result of Your choice to
You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients’ rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer. distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
3.6 Distribution of Executable Versions. permitted under the terms of Section 3.3).
You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients’ rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient’s rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer, Original Developer or any Contributor. You hereby agree to indemnify the Initial Developer, Original Developer and every Contributor for any liability incurred by the Initial Developer, Original Developer or such Contributor as a result of any such terms You offer.
2.5. Representation
3.7 Larger Works.
You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code. Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
4. Inability to Comply Due to Statute or Regulation. to grant the rights to its Contributions conveyed by this License.
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
2.6. Fair Use
5. Application of this License.
This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code. This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
6. Versions of the License. equivalents.
6.1 New Versions. 2.7. Conditions
Socialtext, Inc. (“Socialtext”) may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
6.2 Effect of New Versions. in Section 2.1.
Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Socialtext. No one other than Socialtext has the right to modify the terms applicable to Covered Code created under this License.
3. Responsibilities
6.3 Derivative Works. -------------------
If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases “Socialtext”, “CPAL” or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the CPAL. (Filling in the name of the Initial Developer, Original Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)
3.1. Distribution of Source Form
7. DISCLAIMER OF WARRANTY.
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER, ORIGINAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
8. TERMINATION. the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
8.1 This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
8.2 If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer, Original Developer or a Contributor (the Initial Developer, Original Developer or Contributor against whom You file such action is referred to as “Participant”) alleging that: Form.
(a) such Participant’s Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above. 3.2. Distribution of Executable Form
(b) any software, hardware, or device, other than such Participant’s Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant. If You distribute Covered Software in Executable Form then:
8.3 If You assert a patent infringement claim against Participant alleging that such Participant’s Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license. (a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
8.4 In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination. the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
9. LIMITATION OF LIABILITY. than the cost of distribution to the recipient; and
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ORIGINAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY’S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
(b) You may distribute such Executable Form under the terms of this
10. U.S. GOVERNMENT END USERS. License, or sublicense it under different terms, provided that the
The Covered Code is a “commercial item,” as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of “commercial computer software” and “commercial computer software documentation,” as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein. license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
11. MISCELLANEOUS.
This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys’ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. 3.3. Distribution of a Larger Work
12. RESPONSIBILITY FOR CLAIMS. You may create and distribute a Larger Work under terms of Your choice,
As between Initial Developer, Original Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer, Original Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability. provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
13. MULTIPLE-LICENSED CODE. Software with a work governed by one or more Secondary Licenses, and the
Initial Developer may designate portions of the Covered Code as Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the CPAL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A. Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
14. ADDITIONAL TERM: ATTRIBUTION under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
(a) As a modest attribution to the organizer of the development of the Original Code (“Original Developer”), in the hope that its promotional value may help justify the time, money and effort invested in writing the Original Code, the Original Developer may include in Exhibit B (“Attribution Information”) a requirement that each time an Executable and Source Code or a Larger Work is launched or initially run (which includes initiating a session), a prominent display of the Original Developer’s Attribution Information (as defined below) must occur on the graphic user interface employed by the end user to access such Covered Code (which may include display on a splash screen), if any. The size of the graphic image should be consistent with the size of the other elements of the Attribution Information. If the access by the end user to the Executable and Source Code does not create a graphic user interface for access to the Covered Code, this obligation shall not apply. If the Original Code displays such Attribution Information in a particular form (such as in the form of a splash screen, notice at login, an “about” display, or dedicated attribution area on user interface screens), continued use of such form for that Attribution Information is one way of meeting this requirement for notice. Software under the terms of either this License or such Secondary
License(s).
(b) Attribution information may only include a copyright notice, a brief phrase, graphic image and a URL (“Attribution Information”) and is subject to the Attribution Limits as defined below. For these purposes, prominent shall mean display for sufficient duration to give reasonable notice to the user of the identity of the Original Developer and that if You include Attribution Information or similar information for other parties, You must ensure that the Attribution Information for the Original Developer shall be no less prominent than such Attribution Information or similar information for the other party. For greater certainty, the Original Developer may choose to specify in Exhibit B below that the above attribution requirement only applies to an Executable and Source Code resulting from the Original Code or any Modification, but not a Larger Work. The intent is to provide for reasonably modest attribution, therefore the Original Developer cannot require that You display, at any time, more than the following information as Attribution Information: (a) a copyright notice including the name of the Original Developer; (b) a word or one phrase (not exceeding 10 words); (c) one graphic image provided by the Original Developer; and (d) a URL (collectively, the “Attribution Limits”).
3.4. Notices
(c) If Exhibit B does not include any Attribution Information, then there are no requirements for You to display any Attribution Information of the Original Developer.
You may not remove or alter the substance of any license notices
(d) You acknowledge that all trademarks, service marks and/or trade names contained within the Attribution Information distributed with the Covered Code are the exclusive property of their owners and may only be used with the permission of their owners, or under circumstances otherwise permitted by law or as expressly set out in this License. (including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
15. ADDITIONAL TERM: NETWORK USE. the Covered Software, except that You may alter any license notices to
The term “External Deployment” means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2. the extent required to remedy known factual inaccuracies.
EXHIBIT A. Common Public Attribution License Version 1.0. 3.5. Application of Additional Terms
"The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/license/cpal_1-0. The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B. You may choose to offer, and to charge a fee for, warranty, support,
Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. indemnity or liability obligations to one or more recipients of Covered
The Original Code is CustosPublic. Software. However, You may do so only on Your own behalf, and not on
The Original Developer is the Initial Developer. behalf of any Contributor. You must make it absolutely clear that any
The Initial Developer of the Original Code is Marek Novák. All portions of the code written by Marek Novák are Copyright (c) 2026. All Rights Reserved. such warranty, support, indemnity, or liability obligation is offered by
Contributor: none." You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
EXHIBIT B. Attribution Information indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
Attribution Copyright Notice: Copyright (c) 2026 Marek Novák jurisdiction.
Attribution Phrase (not exceeding 10 words): Built on Domi
Attribution URL: https://aula.marek-novak.cz 4. Inability to Comply Due to Statute or Regulation
Graphic Image as provided in the Covered Code, if any: none. ---------------------------------------------------
Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+2 -18
View File
@@ -12,7 +12,7 @@ password and secret manager: everything that touches plaintext or keys.
| `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) | | `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) |
| `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) | | `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) |
| `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) | | `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) |
| `custos-browser`, `custos-native`, `extension/` | The Edge/Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.md)) | | `custos-browser`, `custos-native`, `extension/` | The Firefox, Edge and Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.md)) |
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md) Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md). for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
@@ -21,20 +21,4 @@ for what it does and does not protect. Report vulnerabilities as described in [`
cargo test --workspace cargo test --workspace
``` ```
## Licence Licence: MPL-2.0. The memorable-password words come from the EFF wordlist (CC BY 3.0 US), filtered with the ESDB/SCOWL English dictionary (see `crates/custos-gen/wordlists/SOURCES.md`).
CustosPublic is licensed under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`), from v0.20.0 on: see
[LICENSE](LICENSE). Versions before this change (up to and including v0.19.1) stay available under MPL-2.0 to those
who received them under it.
**Attribution (Exhibit B).** Anyone who redistributes CustosPublic, or software built on it, must show this credit
where CPAL-1.0 §14 asks for it:
| | |
| :-- | :-- |
| Attribution Copyright Notice | Copyright (c) 2026 Marek Novák |
| Attribution Phrase | Built on Domi |
| Attribution URL | https://aula.marek-novak.cz |
| Graphic Image | none |
Third-party parts keep their own licences. The memorable-password words come from the EFF wordlist (CC BY 3.0 US), filtered with the ESDB/SCOWL English dictionary (see `crates/custos-gen/wordlists/SOURCES.md`).
+2
View File
@@ -7,4 +7,6 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
# Mozilla's Public Suffix List, compiled in: a login for `github.io` or `co.uk` never goes to their subdomains.
psl = "2"
zeroize.workspace = true zeroize.workspace = true
+66
View File
@@ -0,0 +1,66 @@
//! Which extension started the native host. Browsers start `custos-native.exe` only for the extensions its
//! host manifest names (`allowed_origins` for Chromium, `allowed_extensions` for Firefox), and they say which
//! one it was in the host's arguments:
//!
//! - **Chromium** (Edge, Chrome): the first argument is the caller's origin, `chrome-extension://<id>/`
//! (then `--parent-window=<n>` on Windows);
//! - **Firefox**: the first argument is the host manifest's path, the second the add-on's id.
//!
//! The host checks them again ([`caller`]) and answers every request from anything else with `not_allowed`,
//! without reaching Custos: a second line behind the browser's own check, for a manifest someone else wrote.
/// The Chromium extension's id, fixed by the public key in its manifest (`extension/manifest.chromium.json`).
pub const CHROMIUM_ID: &str = "jchkapmceepdnlhagfppeckggaecdcmn";
/// The Firefox add-on's id (`browser_specific_settings.gecko.id` in `extension/manifest.firefox.json`).
pub const FIREFOX_ID: &str = "custos@marek-novak.cz";
/// The kind of browser the Custos extension runs in, as its host's arguments say.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Browser {
Chromium,
Firefox,
}
/// The caller of the host, from its arguments without the program name; `None` unless it is the Custos
/// extension.
pub fn caller<S: AsRef<str>>(args: &[S]) -> Option<Browser> {
let first = args.first()?.as_ref();
if first == format!("chrome-extension://{CHROMIUM_ID}/") {
return Some(Browser::Chromium);
}
// Firefox: <manifest path> <add-on id>. The path is the browser's business; the id must be exactly ours.
if first.to_ascii_lowercase().ends_with(".json") && args.get(1).map(AsRef::as_ref) == Some(FIREFOX_ID) {
return Some(Browser::Firefox);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_custos_extension_may_use_the_host() {
let edge = ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/", "--parent-window=0"];
assert_eq!(caller(&edge), Some(Browser::Chromium));
let firefox = [r"F:\Apps\Custos\cz.marek_novak.custos.firefox.json", "custos@marek-novak.cz"];
assert_eq!(caller(&firefox), Some(Browser::Firefox));
// Any other extension, a look-alike id, or no arguments at all (started by hand): refused.
let refused: [&[&str]; 11] = [
&["chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"],
&["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmnx/"],
&["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn"],
&["CHROME-EXTENSION://JCHKAPMCEEPDNLHAGFPPECKGGAECDCMN/"],
&["moz-extension://jchkapmceepdnlhagfppeckggaecdcmn/"],
&[r"C:\x\manifest.json", "evil@example.com"],
&[r"C:\x\manifest.json", "custos@marek-novak.cz.evil"],
&[r"C:\x\manifest.json", "Custos@marek-novak.cz"],
&["custos@marek-novak.cz"],
&[r"C:\x\manifest.txt", "custos@marek-novak.cz"],
&[],
];
for other in refused {
assert_eq!(caller(other), None, "{other:?}");
}
}
}
+114 -3
View File
@@ -6,7 +6,10 @@
//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it, //! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it,
//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains //! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains
//! (`paypa1.com`, `paypal.com.evil.net`) never match. //! (`paypa1.com`, `paypal.com.evil.net`) never match.
//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON). //! - [`fill_allowed`]: the same for a login field in a frame: the frame's origin, and the top page's too when
//! the frame is not the top page, so a login never goes into a site embedded by another one.
//! - [`caller`]: which extension started the native host (the browser's arguments), refused unless it is Custos's.
//! - [`framing`]: native messaging frames (a 4-byte little-endian length, then JSON), the same in every browser.
//! //!
//! ``` //! ```
//! use custos_browser::{login_matches, Origin}; //! use custos_browser::{login_matches, Origin};
@@ -16,6 +19,7 @@
//! # Ok::<(), custos_browser::OriginError>(()) //! # Ok::<(), custos_browser::OriginError>(())
//! ``` //! ```
pub mod caller;
pub mod framing; pub mod framing;
use std::fmt; use std::fmt;
@@ -95,6 +99,7 @@ fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u
} }
let port = match port { let port = match port {
None | Some("") => None, None | Some("") => None,
Some(p) if !p.bytes().all(|b| b.is_ascii_digit()) => return Err(OriginError::BadPort),
Some(p) => Some( Some(p) => Some(
p.parse::<u16>() p.parse::<u16>()
.map_err(|_| OriginError::BadPort) .map_err(|_| OriginError::BadPort)
@@ -157,7 +162,8 @@ pub enum Match {
/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes /// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes
/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and /// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and
/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for /// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for
/// an IP address matches only that exact host. /// an IP address matches only that exact host, and so does a login for a public suffix (`co.uk`, `github.io`,
/// Mozilla's Public Suffix List): its subdomains belong to different people.
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> { pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
if !page.fillable() { if !page.fillable() {
return None; return None;
@@ -171,7 +177,7 @@ pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
if item == at { if item == at {
return Some(Match::Exact); return Some(Match::Exact);
} }
if page.is_ip() || !item.contains('.') || item.starts_with('[') { if page.is_ip() || !item.contains('.') || item.starts_with('[') || psl::domain_str(&item).is_none() {
return None; return None;
} }
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain) at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
@@ -182,6 +188,23 @@ pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) ->
urls.into_iter().filter_map(|u| login_matches(u, page)).min() urls.into_iter().filter_map(|u| login_matches(u, page)).min()
} }
/// May the login with `urls` be filled into a field of the frame at `frame`, on the tab whose top page is `top`?
///
/// The frame must match (it is where the password goes). A frame that is not the top page (another origin) must
/// match **and** the top page must match too: `evil.net` embedding `github.com/login` in an iframe gets nothing,
/// and neither does a `github.com` page that embeds an advertiser's frame. The answer is the frame's match.
pub fn fill_allowed<'a>(
urls: impl IntoIterator<Item = &'a str> + Clone,
frame: &Origin,
top: &Origin,
) -> Option<Match> {
let m = best_match(urls.clone(), frame)?;
if frame != top && best_match(urls, top).is_none() {
return None;
}
Some(m)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -278,4 +301,92 @@ mod tests {
Some(Match::Subdomain) Some(Match::Subdomain)
); );
} }
/// Hostile pages, one trick each: none of them gets the `github.com` login.
#[test]
fn spoofed_addresses_never_get_a_login() {
let gh = "https://github.com";
// Look-alike hosts: punycode twins (Cyrillic and Greek letters), extra labels, hyphens, typos.
for evil in [
"https://xn--gthub-n4a.com/",
"https://xn--80ak6aa92e.com/",
"https://xn--github-xyz.com/",
"https://github.com.evil.net/",
"https://www.github.com.evil.net/",
"https://github.com-login.evil.net/",
"https://wwwgithub.com/",
"https://github.co.evil.net/",
"https://evil.net/github.com",
"https://evil.net/?next=https://github.com",
"https://evil.net/#@github.com",
] {
assert_eq!(login_matches(gh, &page(evil)), None, "{evil}");
}
// Addresses that hide their host: userinfo, encoded dots, backslashes, unicode, odd ports. Refused outright.
for bad in [
"https://github.com@evil.net/",
"https://github.com:443@evil.net/",
r"https://evil.net\@github.com/",
"https://github%2ecom/",
"https://github.com%2eevil.net/",
r"https://github.com\.evil.net/",
"https://g\u{0456}thub.com/",
"https://github.com:+443/",
"https://github.com:-1/",
"https://github.com: 443/",
] {
assert!(Origin::parse(bad).is_err(), "{bad}");
}
// A stored URL that hides its host never matches either.
assert_eq!(login_matches("https://evil.net@github.com", &page("https://github.com/")), None);
assert_eq!(
login_matches("https://bücher.de", &page("https://xn--bcher-kva.de/")),
None,
"only what the browser reports"
);
// Plain http, even of the right host, and https logins on http pages: never.
assert_eq!(login_matches(gh, &page("http://github.com/")), None);
assert_eq!(login_matches("http://github.com", &page("http://github.com/")), None);
assert_eq!(login_matches("http://github.com", &page("https://github.com/")), None);
// The case and a trailing dot are the same host; that is not a trick.
assert_eq!(login_matches(gh, &page("https://GITHUB.com./")), Some(Match::Exact));
}
#[test]
fn a_public_suffix_has_no_subdomains_to_fill() {
// Anyone can own a subdomain of these: a login saved for the suffix itself fits only the suffix.
for (login, other) in [
("https://github.io", "https://attacker.github.io/"),
("https://co.uk", "https://bank.co.uk/"),
("https://blogspot.com", "https://evil.blogspot.com/"),
("https://herokuapp.com", "https://evil.herokuapp.com/"),
] {
assert_eq!(login_matches(login, &page(other)), None, "{login} on {other}");
assert_eq!(login_matches(login, &page(&format!("{login}/"))), Some(Match::Exact), "{login}");
}
// A site on such a suffix keeps its own subdomains.
assert_eq!(
login_matches("https://mark.github.io", &page("https://docs.mark.github.io/")),
Some(Match::Subdomain)
);
assert_eq!(login_matches("https://mark.github.io", &page("https://eve.github.io/")), None);
assert_eq!(login_matches("https://bank.co.uk", &page("https://login.bank.co.uk/")), Some(Match::Subdomain));
}
#[test]
fn a_frame_gets_a_login_only_when_its_page_would_too() {
let gh = ["https://github.com"];
let (login, top_gh, evil) =
(page("https://github.com/login"), page("https://github.com/"), page("https://evil.net/"));
// The top page itself.
assert_eq!(fill_allowed(gh, &login, &login), Some(Match::Exact));
// A frame of the same site, on a page of the same site.
assert_eq!(fill_allowed(gh, &page("https://gist.github.com/"), &top_gh), Some(Match::Subdomain));
// github.com framed by evil.net: the frame's own origin matches, the page does not. Nothing.
assert_eq!(fill_allowed(gh, &login, &evil), None);
// An evil frame on github.com: its own origin does not match. Nothing.
assert_eq!(fill_allowed(gh, &evil, &top_gh), None);
// A plain-http top page around an https frame of the site: nothing either.
assert_eq!(fill_allowed(gh, &login, &page("http://github.com/")), None);
}
} }
+1
View File
@@ -8,6 +8,7 @@ repository.workspace = true
[dependencies] [dependencies]
custos-browser = { path = "../custos-browser" } custos-browser = { path = "../custos-browser" }
rand.workspace = true
serde_json.workspace = true serde_json.workspace = true
zeroize.workspace = true zeroize.workspace = true
+169 -37
View File
@@ -1,37 +1,95 @@
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it //! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Firefox, Edge or Chrome
//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards //! starts it when the extension connects, and talks to it over stdin/stdout in native messaging frames. It
//! three requests to the desktop Custos over its Domi pipe and returns the answers: //! forwards five requests to the desktop Custos over its Domi pipe and returns the answers:
//! //!
//! - `browser_status`: is Custos running and unlocked; //! - `browser_status`: is Custos running, and this connection's match code;
//! - `browser_match { origin }`: the logins for a page (title, username; never a password); //! - `browser_match { origin, top }`: the logins for a frame (title, username, has 2FA; never a password);
//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page. //! - `browser_fill { id, origin, top }`: one login's username, password and 2FA code, when it matches;
//! - `browser_totp { id, origin, top }`: only the 2FA code, for the popup;
//! - `browser_save { origin, top, username, password, title }`: offer a new login (or a changed password);
//! Custos shows a card and stores it only on *Save*.
//! //!
//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the //! The host adds nothing and decides nothing: Custos checks the origins against the login and asks the user
//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from //! once whether this host may use web logins. It forwards only those requests, rebuilt from their known fields,
//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses //! so the extension cannot reach Custos's other Domi requests through it. It answers nothing to an extension
//! a pipe that is not served by custos.exe. //! that is not Custos's (`custos_browser::caller`), and it refuses a pipe that is not served by custos.exe.
//!
//! Every request carries this connection's `session`: 32 random bytes made when the host starts. Custos shows
//! their match code on its card and in the audit; the extension shows the same code in its popup.
use std::io::{self, Write}; use std::io::{self, Write};
use custos_browser::caller::{Browser, caller};
use custos_browser::framing::{read_frame, write_frame}; use custos_browser::framing::{read_frame, write_frame};
use serde_json::{Value, json}; use serde_json::{Value, json};
use zeroize::Zeroizing; use zeroize::Zeroizing;
const PIPE: &str = r"\\.\pipe\custos-domi"; const PIPE: &str = r"\\.\pipe\custos-domi";
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill"]; const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill", "browser_totp", "browser_save"];
/// The connection: who started the host, and its session.
struct Conn {
browser: Browser,
session: String,
}
impl Conn {
fn new(browser: Browser) -> Conn {
use rand::Rng;
let mut raw = Zeroizing::new([0u8; 32]);
rand::rand_core::UnwrapErr(rand::rngs::SysRng).fill_bytes(raw.as_mut());
Conn { browser, session: raw.iter().map(|b| format!("{b:02x}")).collect() }
}
/// The browser's name as Custos shows it: Firefox is what the arguments say; for Chromium the extension
/// names it (Edge or Chrome), a label only.
fn browser_name(&self, hint: Option<&str>) -> &'static str {
match (self.browser, hint) {
(Browser::Firefox, _) => "firefox",
(Browser::Chromium, Some("edge")) => "edge",
(Browser::Chromium, Some("chrome")) => "chrome",
(Browser::Chromium, _) => "chromium",
}
}
}
/// A string field of at most `max` bytes, or `bad_request`.
fn field<'a>(v: &'a Value, name: &str, max: usize) -> Result<&'a str, &'static str> {
v.get(name).and_then(Value::as_str).filter(|s| s.len() <= max).ok_or("bad_request")
}
/// The request Custos gets: only known fields, of the right types. /// The request Custos gets: only known fields, of the right types.
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> { fn rebuild(msg: &[u8], conn: &Conn) -> Result<Value, &'static str> {
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?; let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?; let out = build(&v, conn);
let mut out = json!({ "op": op, "app": "Custos for your browser" }); // The parsed message can hold a password: wiped before it is dropped.
if op != "browser_status" { zeroize_json(v);
let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?; out
out["origin"] = origin.into(); }
fn build(v: &Value, conn: &Conn) -> Result<Value, &'static str> {
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
let hint = v.get("browser").and_then(Value::as_str);
let mut out = json!({
"op": op,
"app": "Custos for your browser",
"browser": conn.browser_name(hint),
"session": conn.session,
});
if op != "browser_status" {
out["origin"] = field(v, "origin", 2048)?.into();
out["top"] = field(v, "top", 2048)?.into();
}
if matches!(op, "browser_fill" | "browser_totp") {
out["id"] = field(v, "id", 128)?.into();
}
if op == "browser_save" {
out["username"] = field(v, "username", 1024)?.into();
out["password"] =
field(v, "password", 4096).and_then(|p| if p.is_empty() { Err("bad_request") } else { Ok(p) })?.into();
if let Some(t) = v.get("title") {
out["title"] = t.as_str().filter(|t| t.len() <= 200).ok_or("bad_request")?.into();
} }
if op == "browser_fill" {
let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?;
out["id"] = id.into();
} }
// The extension's own request number comes back with the answer, so it can pair them. // The extension's own request number comes back with the answer, so it can pair them.
if let Some(n) = v.get("seq").and_then(Value::as_u64) { if let Some(n) = v.get("seq").and_then(Value::as_u64) {
@@ -44,13 +102,19 @@ fn error(code: &str, seq: Option<u64>) -> Vec<u8> {
serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default() serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default()
} }
fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> { /// One answer. `conn` is `None` when the host was started by anything but the Custos extension: then every
/// request gets `not_allowed` and nothing reaches Custos.
fn answer(msg: &[u8], conn: Option<&Conn>, pipe: &str) -> Zeroizing<Vec<u8>> {
let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64)); let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64));
let req = match rebuild(msg) { let Some(conn) = conn else {
return Zeroizing::new(error("not_allowed", seq));
};
let req = match rebuild(msg, conn) {
Ok(r) => r, Ok(r) => r,
Err(code) => return Zeroizing::new(error(code, seq)), Err(code) => return Zeroizing::new(error(code, seq)),
}; };
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default()); let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
zeroize_json(req);
match pipe::call(pipe, &bytes) { match pipe::call(pipe, &bytes) {
Ok(resp) => { Ok(resp) => {
// Custos does not know the extension's request number: put it back. // Custos does not know the extension's request number: put it back.
@@ -68,13 +132,16 @@ fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> {
} }
} }
/// Wipes the strings of a parsed answer (it can hold a password) before dropping it. /// Wipes the strings of a parsed message (it can hold a password) before dropping it.
fn zeroize_json(v: Value) { fn zeroize_json(v: Value) {
use zeroize::Zeroize; use zeroize::Zeroize;
match v { match v {
Value::String(mut s) => s.zeroize(), Value::String(mut s) => s.zeroize(),
Value::Array(a) => a.into_iter().for_each(zeroize_json), Value::Array(a) => a.into_iter().for_each(zeroize_json),
Value::Object(o) => o.into_iter().for_each(|(_, v)| zeroize_json(v)), Value::Object(o) => o.into_iter().for_each(|(mut k, v)| {
k.zeroize();
zeroize_json(v)
}),
_ => {} _ => {}
} }
} }
@@ -82,6 +149,8 @@ fn zeroize_json(v: Value) {
fn main() { fn main() {
// Tests point the host at another Custos. // Tests point the host at another Custos.
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string()); let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
let args: Vec<String> = std::env::args().skip(1).collect();
let conn = caller(&args).map(Conn::new);
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout()); let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
loop { loop {
let msg = match read_frame(&mut stdin) { let msg = match read_frame(&mut stdin) {
@@ -89,7 +158,7 @@ fn main() {
// The extension disconnected, or sent something that is not a frame: done. // The extension disconnected, or sent something that is not a frame: done.
Ok(None) | Err(_) => return, Ok(None) | Err(_) => return,
}; };
let out = answer(&msg, &pipe); let out = answer(&msg, conn.as_ref(), &pipe);
let mut w = stdout.lock(); let mut w = stdout.lock();
if write_frame(&mut w, &out).is_err() || w.flush().is_err() { if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
return; return;
@@ -205,36 +274,99 @@ mod pipe {
mod tests { mod tests {
use super::*; use super::*;
fn conn(b: Browser) -> Conn {
Conn::new(b)
}
#[test] #[test]
fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() { fn only_the_browser_requests_pass_rebuilt_from_known_fields() {
let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap(); let c = conn(Browser::Chromium);
let fill = rebuild(
br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","top":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca","browser":"edge","session":"mine"}"#,
&c,
)
.unwrap();
assert_eq!( assert_eq!(
fill, fill,
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" }) json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "top": "https://github.com", "seq": 7,
"app": "Custos for your browser", "browser": "edge", "session": c.session })
); );
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status"); assert_eq!(c.session.len(), 64, "the host's own session, never the extension's");
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok()); assert_ne!(c.session, conn(Browser::Chromium).session, "a new one for every connection");
assert_eq!(rebuild(br#"{"op":"browser_status"}"#, &c).unwrap()["op"], "browser_status");
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz","top":"https://a.cz"}"#, &c).is_ok());
let totp =
rebuild(br#"{"op":"browser_totp","id":"x","origin":"https://a.cz","top":"https://a.cz"}"#, &c).unwrap();
assert_eq!(totp["id"], "x");
let save = rebuild(
br#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"mark","password":"pw","title":"A","extra":1}"#,
&c,
)
.unwrap();
assert_eq!(
(save["username"].as_str(), save["password"].as_str(), save["title"].as_str()),
(Some("mark"), Some("pw"), Some("A"))
);
assert!(save.get("extra").is_none());
// The browser's name: Firefox from the arguments, whatever the extension says; Chromium names itself.
let f = conn(Browser::Firefox);
assert_eq!(rebuild(br#"{"op":"browser_status","browser":"chrome"}"#, &f).unwrap()["browser"], "firefox");
assert_eq!(rebuild(br#"{"op":"browser_status","browser":"lynx"}"#, &c).unwrap()["browser"], "chromium");
// Custos's other Domi requests never pass through the browser's host. // Custos's other Domi requests never pass through the browser's host.
for other in [ for other in [
r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#, r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#,
r#"{"op":"list","namespace":"arca"}"#, r#"{"op":"list","namespace":"arca"}"#,
r#"{"op":"set","ref":"domi://x/y","value":"v"}"#, r#"{"op":"set","ref":"domi://x/y","value":"v"}"#,
r#"{"op":"subkey"}"#, r#"{"op":"subkey"}"#,
r#"{"op":"sign"}"#,
r#"{"op":"browser_anything","origin":"https://a.cz","top":"https://a.cz"}"#,
] { ] {
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}"); assert_eq!(rebuild(other.as_bytes(), &c), Err("bad_request"), "{other}");
}
// Missing or wrong fields, or too long.
for bad in [
r#"{"op":"browser_fill","origin":"https://a.cz","top":"https://a.cz"}"#,
r#"{"op":"browser_fill","id":"x","origin":"https://a.cz"}"#,
r#"{"op":"browser_match","origin":5,"top":"https://a.cz"}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m"}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m","password":""}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m","password":"p","title":7}"#,
"not json",
] {
assert!(rebuild(bad.as_bytes(), &c).is_err(), "{bad}");
}
let long = format!(
r#"{{"op":"browser_fill","id":"{}","origin":"https://a.cz","top":"https://a.cz"}}"#,
"x".repeat(129)
);
assert!(rebuild(long.as_bytes(), &c).is_err());
}
#[test]
fn an_extension_that_is_not_custos_gets_nothing() {
// Started by another extension (or by hand): `not_allowed` for every request, and the pipe is never
// opened (this pipe does not exist; reaching for it would answer `not_running`).
let args = ["chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"];
let conn = caller(&args).map(Conn::new);
assert!(conn.is_none());
for msg in [
&br#"{"op":"browser_status","seq":1}"#[..],
br#"{"op":"browser_match","origin":"https://github.com","top":"https://github.com","seq":2}"#,
br#"{"op":"browser_fill","id":"x","origin":"https://github.com","top":"https://github.com","seq":3}"#,
] {
let v: Value =
serde_json::from_slice(&answer(msg, conn.as_ref(), r"\\.\pipe\custos-test-nobody-here")).unwrap();
assert_eq!(v["error"], "not_allowed");
} }
// Missing or wrong fields.
assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err());
assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err());
assert!(rebuild(b"not json").is_err());
} }
#[test] #[test]
fn without_custos_the_answer_says_so_and_keeps_the_request_number() { fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
let out = answer(br#"{"op":"browser_status","seq":3}"#, r"\\.\pipe\custos-test-nobody-here"); let c = conn(Browser::Firefox);
let out = answer(br#"{"op":"browser_status","seq":3}"#, Some(&c), r"\\.\pipe\custos-test-nobody-here");
let v: Value = serde_json::from_slice(&out).unwrap(); let v: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 })); assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 }));
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, PIPE)).unwrap(); let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, Some(&c), PIPE)).unwrap();
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 })); assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
} }
} }
-6
View File
@@ -195,12 +195,6 @@ pub fn minisign_public(public: &[u8; 32], key_id: &[u8; 8]) -> String {
format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw)) format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw))
} }
/// A plain Ed25519 signature over `message` itself: no prehash, no digest, no wrapping (core 0.21.0, the Domi
/// licence, docs/SIGNING.md "Domi licences"). ed25519-dalek's deterministic RFC 8032 signature.
pub fn ed25519_plain(secret: &Ed25519Secret, message: &[u8]) -> [u8; 64] {
SigningKey::from_bytes(&secret.0).sign(message).to_bytes()
}
/// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`. /// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`.
/// The trusted comment is `timestamp:<unix seconds>\tfile:<file>\thashed`, as minisign writes it. /// The trusted comment is `timestamp:<unix seconds>\tfile:<file>\thashed`, as minisign writes it.
pub fn minisign( pub fn minisign(
-1
View File
@@ -20,7 +20,6 @@ mod crypto;
mod device; mod device;
mod format; mod format;
pub mod identity; pub mod identity;
pub mod licence;
mod item; mod item;
pub mod provision; pub mod provision;
mod recovery; mod recovery;
-843
View File
@@ -1,843 +0,0 @@
//! Domi licences (core 0.21.0, docs/SIGNING.md "Domi licences"; the byte format is Fundamentum's docs/LICENCE.md,
//! licence v1): the key `domi-licence`, the strict parser of what it signs, and Mark's licence grant.
//!
//! The key is an Ed25519 key in the signing store under the reserved id [`LICENCE_KEY`], with no scope: every
//! other signing path refuses it, so it signs only the two payload kinds here (a licence, a revocation list), and
//! no other key signs them. Its secret never leaves this module and `signing.rs`; only its public key does.
//!
//! What it signs is parsed here **before** anything else, byte for byte as the spec's strict parser does (§2.4
//! steps 1–4 and 7 for a licence, §4.1 for a revocation list): malformed input is refused with the spec's code and
//! never reaches a card. Then the grant decides: a licence from `licence-issue` (its Canalis app id, and a
//! Domi-signed program) whose apps are all on Mark's allowlist, within the cap, is signed at once; anything else
//! that is well formed asks Mark on a card. A revocation list always asks. Refused outright, never a card: a licence
//! whose `issued` is more than a day from this clock, a licence id this key signed before (`replay`), a revocation
//! list whose `seq` is not higher than the highest this key signed (`rollback`), and any caller but `licence-issue`.
//!
//! The grant and the log live in the signing store's `licence` member, which cores before 0.21.0 ignore (and drop if
//! they save the vault: then the grant is gone, which fails closed, and the service's own anti-rollback check still
//! holds, Fundamentum docs/LICENCE.md §4.2). The key itself is an ordinary Ed25519 entry every core reads.
use serde::{Deserialize, Serialize};
use crate::{Error, Vault};
/// The reserved id of the licence key.
pub const LICENCE_KEY: &str = "domi-licence";
/// The one Canalis app that may ask for a licence signature.
pub const LICENCE_ISSUER: &str = "licence-issue";
/// The first line of a licence payload, inside the signed bytes.
pub const LICENCE_PREFIX: &str = "domi-licence-v1\n";
/// The first line of a revocation list payload, inside the signed bytes.
pub const REVOCATIONS_PREFIX: &str = "domi-revocations-v1\n";
/// What the `sig:` line adds to a payload to make the file: `sig: ` (5), 86 characters, LF.
const SIG_LINE_LEN: usize = 5 + 86 + 1;
/// The largest licence payload signed: the spec caps the **file** at 4096 bytes, so a payload is at most what still
/// fits with its signature line. Stricter than the spec's payload parser, never looser.
pub const LICENCE_PAYLOAD_MAX: usize = 4096 - SIG_LINE_LEN;
/// The largest revocation list payload signed, for the spec's 61 440-byte file.
pub const REVOCATIONS_PAYLOAD_MAX: usize = 61_440 - SIG_LINE_LEN;
/// How far a licence's `issued` may be from this clock, either way (seconds).
pub const CLOCK_TOLERANCE_S: i64 = 86_400;
/// At most this many licence signatures in a rolling day; past it, each one asks on a card.
pub const DAY_CAP: usize = 50;
const DAY_MS: i64 = 86_400_000;
/// At most this many app ids on the allowlist.
pub const ALLOW_MAX: usize = 256;
/// At most this many signatures in the log. Every licence id and revocation `seq` signed must stay known (replay,
/// rollback), so a full log refuses to sign more rather than forget (`log_full`).
pub const LOG_MAX: usize = 20_000;
const MAX_APPS: usize = 64;
const MAX_SEQ: u64 = (1 << 53) - 1;
const LICENCE_FIELDS: [&str; 7] = ["id", "issued", "nickname", "bundle", "scope", "seats", "apps"];
const REVOCATION_FIELDS: [&str; 3] = ["seq", "issued", "revoked"];
/// A licence payload, as parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Licence {
pub id: String,
/// Unix seconds.
pub issued: i64,
pub nickname: String,
pub bundle: String,
/// `None` for `scope: household`, the seat count for `scope: seat`.
pub seats: Option<u8>,
/// Sorted ascending and unique.
pub apps: Vec<String>,
}
/// A revocation list payload, as parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Revocations {
pub seq: u64,
/// Unix seconds.
pub issued: i64,
/// Sorted strictly ascending.
pub revoked: Vec<String>,
}
/// What a payload is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Payload {
Licence(Licence),
Revocations(Revocations),
}
/// Why a payload is not signed. [`LicenceRefusal::code`] is the spec's error code (Fundamentum docs/LICENCE.md §8)
/// where the spec has one, else Custos's own. None carries payload or key bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum LicenceRefusal {
/// The spec's strict parser refused the payload (§2.4 steps 1–4 and 7, §4.1).
#[error("the payload is malformed: {0}")]
Malformed(&'static str),
/// There is no `domi-licence` key yet.
#[error("there is no licence key in this vault")]
NoKey,
/// Only `licence-issue` may ask.
#[error("only licence-issue may ask for a licence signature")]
NotAllowed,
/// The licence's `issued` is more than a day from this clock.
#[error("the licence is dated more than a day from this PC's clock")]
Clock,
/// This key signed a licence with this id before.
#[error("a licence with this id was signed before")]
Replay,
/// This key signed a revocation list with this `seq` or a higher one before.
#[error("a revocation list with this seq or a higher one was signed before")]
Rollback,
/// The log is full.
#[error("the licence log is full")]
LogFull,
/// Asked to sign without a card where the grant does not cover the request.
#[error("this needs Mark's answer on a card")]
NeedsCard,
}
impl LicenceRefusal {
pub fn code(self) -> &'static str {
match self {
LicenceRefusal::Malformed(c) => c,
LicenceRefusal::NoKey => "no_key",
LicenceRefusal::NotAllowed => "not_allowed",
LicenceRefusal::Clock => "clock",
LicenceRefusal::Replay => "replay",
LicenceRefusal::Rollback => "rollback",
LicenceRefusal::LogFull => "log_full",
LicenceRefusal::NeedsCard => "needs_card",
}
}
}
// ---- the strict parser (Fundamentum docs/LICENCE.md §2.4 steps 1–4 and 7, §4.1) ----
fn malformed(code: &'static str) -> LicenceRefusal {
LicenceRefusal::Malformed(code)
}
/// A licence id: 8–64 bytes of `[A-Za-z0-9_-]`.
pub fn licence_id_ok(s: &str) -> bool {
(8..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
/// A Tessera id (a bundle, an app): 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`.
pub fn tessera_id_ok(s: &str) -> bool {
(1..=32).contains(&s.len())
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& !s.starts_with('-')
&& !s.ends_with('-')
}
/// A nickname: 1–32 bytes of `[A-Za-z0-9 ._-]`, no space at either end, never two spaces in a row.
fn nickname_ok(s: &str) -> bool {
(1..=32).contains(&s.len())
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b' ' | b'.' | b'_' | b'-'))
&& !s.starts_with(' ')
&& !s.ends_with(' ')
&& !s.contains(" ")
}
/// `[1-9]`, `[1-4][0-9]` or `50`.
fn seats(s: &str) -> Option<u8> {
let ok = matches!(s.as_bytes(), [b'1'..=b'9'] | [b'1'..=b'4', b'0'..=b'9'] | [b'5', b'0']);
ok.then(|| s.parse().ok()).flatten()
}
/// Decimal 1 to 2^53 − 1, no leading zero, no sign.
fn seq(s: &str) -> Option<u64> {
let digits = !s.is_empty() && s.len() <= 16 && s.bytes().all(|b| b.is_ascii_digit()) && !s.starts_with('0');
digits.then(|| s.parse::<u64>().ok()).flatten().filter(|n| (1..=MAX_SEQ).contains(n))
}
/// `YYYY-MM-DDTHH:MM:SSZ`, year 2000–2999, a real Gregorian date, no leap second: Unix seconds.
pub fn parse_utc(s: &str) -> Option<i64> {
let b = s.as_bytes();
if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' || b[19] != b'Z' {
return None;
}
let num = |from: usize, to: usize| -> Option<i64> {
let part = &b[from..to];
part.iter().all(u8::is_ascii_digit).then(|| part.iter().fold(0i64, |n, d| n * 10 + i64::from(d - b'0')))
};
let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?);
let (h, mi, sec) = (num(11, 13)?, num(14, 16)?, num(17, 19)?);
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
let days_in = match mo {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return None,
};
if !(2000..=2999).contains(&y) || !(1..=days_in).contains(&d) || h > 23 || mi > 59 || sec > 59 {
return None;
}
// Days from the civil date (Howard Hinnant's algorithm).
let (yy, mm) = if mo <= 2 { (y - 1, mo + 9) } else { (y, mo - 3) };
let era = yy.div_euclid(400);
let yoe = yy - era * 400;
let doy = (153 * mm + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some(days * 86_400 + h * 3600 + mi * 60 + sec)
}
/// The apps value: every element a Tessera id, at most 64, then sorted ascending and unique (in that order of checks).
fn apps(s: &str) -> Result<Vec<String>, LicenceRefusal> {
let list: Vec<&str> = s.split(',').collect();
if !list.iter().all(|a| tessera_id_ok(a)) {
return Err(malformed("bad_apps"));
}
if list.len() > MAX_APPS {
return Err(malformed("too_many_apps"));
}
for pair in list.windows(2) {
match pair[0].cmp(pair[1]) {
std::cmp::Ordering::Equal => return Err(malformed("apps_duplicate")),
std::cmp::Ordering::Greater => return Err(malformed("apps_unsorted")),
std::cmp::Ordering::Less => {}
}
}
Ok(list.into_iter().map(String::from).collect())
}
/// `<name>: <value>`: a 1–16 byte `[a-z]` name, one space, a non-empty value.
fn field(line: &str) -> Result<(&str, &str), LicenceRefusal> {
let (name, value) = line.split_once(": ").ok_or(malformed("bad_line"))?;
if !(1..=16).contains(&name.len()) || !name.bytes().all(|b| b.is_ascii_lowercase()) || value.is_empty() {
return Err(malformed("bad_line"));
}
Ok((name, value))
}
/// Steps 1–4 on a payload, and the lines after the prefix (step 7's input). The prefix says the kind.
fn structure(input: &[u8]) -> Result<(bool, Vec<&str>), LicenceRefusal> {
if input.len() > REVOCATIONS_PAYLOAD_MAX {
return Err(malformed("too_large"));
}
if input.is_empty() {
return Err(malformed("truncated"));
}
if input.contains(&b'\r') {
return Err(malformed("crlf"));
}
if input.iter().any(|&b| b != b'\n' && !(0x20..=0x7e).contains(&b)) {
return Err(malformed("bad_byte"));
}
let licence = input.starts_with(LICENCE_PREFIX.as_bytes());
let prefix = if licence {
LICENCE_PREFIX
} else if input.starts_with(REVOCATIONS_PREFIX.as_bytes()) {
REVOCATIONS_PREFIX
} else if LICENCE_PREFIX.as_bytes().starts_with(input) || REVOCATIONS_PREFIX.as_bytes().starts_with(input) {
return Err(malformed("truncated"));
} else {
return Err(malformed("bad_prefix"));
};
if licence && input.len() > LICENCE_PAYLOAD_MAX {
return Err(malformed("too_large"));
}
if input.last() != Some(&b'\n') {
return Err(malformed("truncated"));
}
// Printable ASCII and LF only: valid UTF-8.
let text = std::str::from_utf8(input).map_err(|_| malformed("bad_byte"))?;
let body = &text[prefix.len()..];
let lines = if body.is_empty() { Vec::new() } else { body[..body.len() - 1].split('\n').collect() };
Ok((licence, lines))
}
fn licence_fields(lines: &[&str]) -> Result<Licence, LicenceRefusal> {
let mut v: [Option<&str>; 7] = [None; 7];
let mut last: Option<usize> = None;
let (mut issued, mut household, mut seat_count, mut app_list) = (None, None, None, None);
for line in lines {
let (name, value) = field(line)?;
let i = LICENCE_FIELDS.iter().position(|f| *f == name).ok_or(malformed("unknown_field"))?;
if v[i].is_some() {
return Err(malformed("duplicate_field"));
}
if last.is_some_and(|l| i < l) {
return Err(malformed("field_order"));
}
last = Some(i);
v[i] = Some(value);
match i {
0 if !licence_id_ok(value) => return Err(malformed("bad_id")),
1 => issued = Some(parse_utc(value).ok_or(malformed("bad_issued"))?),
2 if !nickname_ok(value) => return Err(malformed("bad_nickname")),
3 if !tessera_id_ok(value) => return Err(malformed("bad_bundle")),
4 => {
household = Some(match value {
"household" => true,
"seat" => false,
_ => return Err(malformed("bad_scope")),
})
}
5 => seat_count = Some(seats(value).ok_or(malformed("bad_seats"))?),
6 => app_list = Some(apps(value)?),
_ => {}
}
}
let (Some(id), Some(issued), Some(nickname), Some(bundle), Some(household), Some(apps)) =
(v[0], issued, v[2], v[3], household, app_list)
else {
return Err(malformed("missing_field"));
};
let seats = match (household, seat_count) {
(true, None) => None,
(true, Some(_)) => return Err(malformed("seats_with_household")),
(false, Some(n)) => Some(n),
(false, None) => return Err(malformed("seats_missing")),
};
Ok(Licence { id: id.into(), issued, nickname: nickname.into(), bundle: bundle.into(), seats, apps })
}
fn revocation_fields(lines: &[&str]) -> Result<Revocations, LicenceRefusal> {
let (mut seq_v, mut issued) = (None, None);
let mut revoked: Vec<String> = Vec::new();
let mut last: Option<usize> = None;
for line in lines {
let (name, value) = field(line)?;
let i = REVOCATION_FIELDS.iter().position(|f| *f == name).ok_or(malformed("unknown_field"))?;
let seen = match i {
0 => seq_v.is_some(),
1 => issued.is_some(),
_ => false,
};
if seen {
return Err(malformed("duplicate_field"));
}
if last.is_some_and(|l| i < l) {
return Err(malformed("field_order"));
}
last = Some(i);
match i {
0 => seq_v = Some(seq(value).ok_or(malformed("bad_seq"))?),
1 => issued = Some(parse_utc(value).ok_or(malformed("bad_issued"))?),
_ => {
if !licence_id_ok(value) {
return Err(malformed("bad_id"));
}
if let Some(prev) = revoked.last() {
match prev.as_str().cmp(value) {
std::cmp::Ordering::Equal => return Err(malformed("revoked_duplicate")),
std::cmp::Ordering::Greater => return Err(malformed("revoked_unsorted")),
std::cmp::Ordering::Less => {}
}
}
revoked.push(value.into());
}
}
}
let (Some(seq), Some(issued)) = (seq_v, issued) else { return Err(malformed("missing_field")) };
Ok(Revocations { seq, issued, revoked })
}
/// The strict parser on a payload: a licence (§2.4 steps 1–4 and 7) or a revocation list (§4.1), by its prefix.
/// Custos never sees a `sig:` line, so steps 5 and 6 do not apply: one in a payload is an `unknown_field`.
pub fn parse_payload(payload: &[u8]) -> Result<Payload, LicenceRefusal> {
let (licence, lines) = structure(payload)?;
if licence {
licence_fields(&lines).map(Payload::Licence)
} else {
revocation_fields(&lines).map(Payload::Revocations)
}
}
// ---- the grant, the log, and what Custos does with a request ----
/// Mark's licence grant: what `licence-issue` may have signed without a card. Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceGrant {
/// The app ids a licence may name and still be signed without a card (Tessera ids, sorted, unique).
pub allow: Vec<String>,
/// Unix milliseconds: when Mark gave it, or last changed it.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
}
/// How a signature was allowed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LicenceBy {
/// Mark's licence grant covered it: no card.
Grant,
/// Mark said yes on a card.
Card,
}
/// One signature in the log: when, what (a licence's id and apps, or a revocation list's seq and count), and how it
/// was allowed. Never the signature, the payload or the nickname.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceEntry {
pub at: i64,
pub by: LicenceBy,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub licence: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub apps: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seq: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked: Option<u64>,
}
/// The grant and the log, in the signing store.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceStore {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grant: Option<LicenceGrant>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub log: Vec<LicenceEntry>,
}
impl LicenceStore {
pub(crate) fn is_empty(&self) -> bool {
self.grant.is_none() && self.log.is_empty()
}
/// What this core could have written; anything else makes the vault refuse to open.
pub(crate) fn ok(&self) -> bool {
let grant_ok = self.grant.as_ref().is_none_or(|g| allow_ok(&g.allow));
let entry_ok = |e: &LicenceEntry| match (&e.licence, e.seq) {
(Some(id), None) => {
licence_id_ok(id)
&& e.revoked.is_none()
&& (1..=MAX_APPS).contains(&e.apps.len())
&& e.apps.iter().all(|a| tessera_id_ok(a))
}
(None, Some(n)) => (1..=MAX_SEQ).contains(&n) && e.apps.is_empty(),
_ => false,
};
grant_ok && self.log.len() <= LOG_MAX && self.log.iter().all(entry_ok)
}
}
fn allow_ok(allow: &[String]) -> bool {
allow.len() <= ALLOW_MAX && allow.iter().all(|a| tessera_id_ok(a)) && allow.windows(2).all(|p| p[0] < p[1])
}
/// Why a well-formed request asks Mark on a card instead of being signed at once. Shown on the card.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase", tag = "why")]
pub enum CardReason {
/// A revocation list always asks.
Revocations,
/// There is no licence grant.
NoGrant,
/// The caller is not a program signed with Domi's certificate.
NotDomiSigned,
/// *Sign only with a card* is ticked.
CardSigning,
/// These apps are not on the allowlist.
OffAllowlist { apps: Vec<String> },
/// The day's cap of licence signatures is reached.
OverCap { signed: usize },
}
/// What Custos would do with a well-formed request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LicenceAsk {
pub payload: Payload,
/// Empty: the grant signs it now. Else the card's reasons.
pub card: Vec<CardReason>,
}
/// Who asks: the caller's authenticated Canalis app id, and whether its program is signed with one of Domi's
/// code-signing certificates (the desktop's check; docs/25 in Custos).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Caller<'a> {
pub app: &'a str,
pub domi_signed: bool,
}
impl Vault {
/// Makes the licence key (Ed25519) and returns its 32-byte public key, the one the Atrium Domi service ships.
/// Refused when there is one already. Call it only from Mark's own click. The caller saves.
pub fn licence_key_create(&mut self, now: i64) -> Result<[u8; 32], Error> {
if self.signing.get(LICENCE_KEY).is_some() {
return Err(Error::Signing(format!("there is a key `{LICENCE_KEY}` already")));
}
let public = self.signing.add_licence_key(now);
let words = format!("licence key {LICENCE_KEY} made");
self.security.standing_note(crate::security::Action::StandingGranted, &words, now);
Ok(public)
}
/// The licence key's public key, if there is one.
pub fn licence_public(&self) -> Option<[u8; 32]> {
self.signing.get(LICENCE_KEY).and_then(|k| k.public)
}
/// The licence grant, if Mark gave it.
pub fn licence_grant(&self) -> Option<LicenceGrant> {
self.signing.licence.grant.clone()
}
/// Gives the licence grant, or replaces its allowlist (its counts stay), and writes `standing-granted`. Refused
/// while *Sign only with a card* is ticked, and before there is a licence key. Call it only from Mark's own click.
/// The caller saves.
pub fn licence_grant_set(&mut self, allow: &[String], now: i64) -> Result<LicenceGrant, Error> {
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(Error::Signing("Sign only with a card is ticked".into()));
}
if self.signing.get(LICENCE_KEY).is_none() {
return Err(Error::Signing("make the licence key first".into()));
}
let mut list: Vec<String> = Vec::new();
for a in allow.iter().map(|a| a.trim()).filter(|a| !a.is_empty()) {
if !tessera_id_ok(a) {
return Err(Error::Signing(format!("`{a}` is not an app id (a-z, 0-9 and -, up to 32)")));
}
list.push(a.to_string());
}
list.sort();
list.dedup();
if list.len() > ALLOW_MAX {
return Err(Error::Signing(format!("the allowlist holds at most {ALLOW_MAX} apps")));
}
let old = self.signing.licence.grant.clone();
let grant = LicenceGrant {
allow: list,
granted: now,
last_used: old.as_ref().and_then(|g| g.last_used),
uses: old.map_or(0, |g| g.uses),
};
let words = format!("Domi licences by {LICENCE_ISSUER}: {}", grant.allow.join(", "));
self.security.standing_note(crate::security::Action::StandingGranted, &words, now);
self.signing.licence.grant = Some(grant.clone());
Ok(grant)
}
/// Removes the licence grant (`standing-revoked`): from then on every licence asks on a card. The key and the log
/// stay. False when there is none. The caller saves.
pub fn licence_grant_revoke(&mut self, now: i64) -> bool {
let Some(g) = self.signing.licence.grant.take() else { return false };
let words = format!("Domi licences by {LICENCE_ISSUER}: {}", g.allow.join(", "));
self.security.standing_note(crate::security::Action::StandingRevoked, &words, now);
true
}
/// Every licence signature, oldest first.
pub fn licence_log(&self) -> &[LicenceEntry] {
&self.signing.licence.log
}
/// What Custos does with `payload` from `caller` at `now` (Unix milliseconds): refused (the code says why, no
/// card), signed by the grant (no reasons), or asked on a card (its reasons). Changes nothing.
pub fn licence_ask(&self, payload: &[u8], caller: Caller<'_>, now: i64) -> Result<LicenceAsk, LicenceRefusal> {
let parsed = parse_payload(payload)?;
if self.signing.get(LICENCE_KEY).is_none() {
return Err(LicenceRefusal::NoKey);
}
if caller.app != LICENCE_ISSUER {
return Err(LicenceRefusal::NotAllowed);
}
if self.signing.licence.log.len() >= LOG_MAX {
return Err(LicenceRefusal::LogFull);
}
let log = &self.signing.licence.log;
let mut card = Vec::new();
match &parsed {
Payload::Licence(l) => {
if (l.issued - now.div_euclid(1000)).abs() > CLOCK_TOLERANCE_S {
return Err(LicenceRefusal::Clock);
}
if log.iter().any(|e| e.licence.as_deref() == Some(l.id.as_str())) {
return Err(LicenceRefusal::Replay);
}
if !caller.domi_signed {
card.push(CardReason::NotDomiSigned);
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
card.push(CardReason::CardSigning);
}
match &self.signing.licence.grant {
None => card.push(CardReason::NoGrant),
Some(g) => {
let off: Vec<String> = l.apps.iter().filter(|a| !g.allow.contains(a)).cloned().collect();
if !off.is_empty() {
card.push(CardReason::OffAllowlist { apps: off });
}
}
}
let today = log.iter().filter(|e| e.licence.is_some() && e.at > now - DAY_MS).count();
if today >= DAY_CAP {
card.push(CardReason::OverCap { signed: today });
}
}
Payload::Revocations(r) => {
if log.iter().filter_map(|e| e.seq).any(|s| s >= r.seq) {
return Err(LicenceRefusal::Rollback);
}
card.push(CardReason::Revocations);
}
}
Ok(LicenceAsk { payload: parsed, card })
}
/// Checks `payload` again ([`Vault::licence_ask`]) and signs it: by the grant when `by` is [`LicenceBy::Grant`]
/// (refused with `needs_card` when the grant does not cover it), or after Mark's yes on a card. Returns the
/// signature in base64url without padding (86 characters), and logs it. The caller saves.
pub fn licence_sign(
&mut self,
payload: &[u8],
caller: Caller<'_>,
by: LicenceBy,
now: i64,
) -> Result<String, LicenceRefusal> {
let ask = self.licence_ask(payload, caller, now)?;
if by == LicenceBy::Grant && !ask.card.is_empty() {
return Err(LicenceRefusal::NeedsCard);
}
let signature = self.signing.licence_signature(payload).ok_or(LicenceRefusal::NoKey)?;
let entry = match &ask.payload {
Payload::Licence(l) => LicenceEntry {
at: now,
by,
licence: Some(l.id.clone()),
apps: l.apps.clone(),
seq: None,
revoked: None,
},
Payload::Revocations(r) => LicenceEntry {
at: now,
by,
licence: None,
apps: Vec::new(),
seq: Some(r.seq),
revoked: Some(r.revoked.len() as u64),
},
};
self.signing.licence.log.push(entry);
if by == LicenceBy::Grant
&& let Some(g) = self.signing.licence.grant.as_mut()
{
g.uses = g.uses.saturating_add(1);
g.last_used = Some(now);
}
Ok(data_encoding::BASE64URL_NOPAD.encode(&signature))
}
}
#[cfg(test)]
mod tests {
use super::*;
const NOW_S: i64 = 1_795_896_907; // 2026-11-28T20:15:07Z
const NOW: i64 = NOW_S * 1000;
fn licence(id: &str, apps: &str) -> Vec<u8> {
format!(
"domi-licence-v1\nid: {id}\nissued: 2026-11-28T20:15:07Z\nnickname: Novak family\nbundle: household-all\n\
scope: household\napps: {apps}\n"
)
.into_bytes()
}
fn revocations(seq: u64, ids: &[&str]) -> Vec<u8> {
let mut s = format!("domi-revocations-v1\nseq: {seq}\nissued: 2026-11-28T20:15:07Z\n");
for id in ids {
s.push_str(&format!("revoked: {id}\n"));
}
s.into_bytes()
}
fn code(p: &[u8]) -> &'static str {
parse_payload(p).unwrap_err().code()
}
const ISSUER: Caller<'static> = Caller { app: LICENCE_ISSUER, domi_signed: true };
fn vault() -> Vault {
let pw = crate::SecretString::from("pw");
let mut v = Vault::create(&pw, crate::KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.licence_key_create(NOW).unwrap();
v
}
#[test]
fn the_spec_example_parses_and_its_time_is_utc() {
assert_eq!(parse_utc("2026-11-28T20:15:07Z"), Some(NOW_S));
assert_eq!(parse_utc("2000-01-01T00:00:00Z"), Some(946_684_800));
assert_eq!(parse_utc("2024-02-29T00:00:00Z").is_some(), true);
for bad in ["2023-02-29T00:00:00Z", "2100-02-29T00:00:00Z", "1999-12-31T23:59:59Z", "2026-11-28T24:00:00Z",
"2026-11-28T20:15:60Z", "2026-11-28 20:15:07Z", "2026-11-28T20:15:07z", "2026-13-01T00:00:00Z"] {
assert_eq!(parse_utc(bad), None, "{bad}");
}
let Payload::Licence(l) = parse_payload(&licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,fiscus,medicus,tabula")).unwrap()
else {
panic!("a licence")
};
assert_eq!((l.issued, l.seats, l.apps.len()), (NOW_S, None, 4));
}
#[test]
fn a_malformed_payload_is_refused_with_the_specs_code() {
let ok = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula");
let with = |from: &str, to: &str| String::from_utf8(ok.clone()).unwrap().replace(from, to).into_bytes();
assert_eq!(code(b""), "truncated");
assert_eq!(code(b"domi-lic"), "truncated");
assert_eq!(code(b"hello\n"), "bad_prefix");
assert_eq!(code(&with("\n", "\r\n")), "crlf");
assert_eq!(code(&with("Novak", "Nov\tak")), "bad_byte");
assert_eq!(code(&ok[..ok.len() - 1]), "truncated");
assert_eq!(code(&with("id: ", "id:")), "bad_line");
assert_eq!(code(&with("bundle: ", "colour: blue\nbundle: ")), "unknown_field");
assert_eq!(code(&with("bundle: ", "id: k3Jx0Qm1T9yZpW2bA7cD4f\nbundle: ")), "duplicate_field");
assert_eq!(code(&with("nickname: Novak family\nbundle: household-all", "bundle: household-all\nnickname: Novak family")), "field_order");
assert_eq!(code(&with("scope: household\n", "")), "missing_field");
assert_eq!(code(&with("k3Jx0Qm1T9yZpW2bA7cD4e", "short")), "bad_id");
assert_eq!(code(&with("2026-11-28T20:15:07Z", "2026-02-30T20:15:07Z")), "bad_issued");
assert_eq!(code(&with("Novak family", "Novak family")), "bad_nickname");
assert_eq!(code(&with("household-all", "-all")), "bad_bundle");
assert_eq!(code(&with("scope: household", "scope: family")), "bad_scope");
assert_eq!(code(&with("scope: household", "scope: seat\nseats: 51")), "bad_seats");
assert_eq!(code(&with("scope: household", "scope: household\nseats: 2")), "seats_with_household");
assert_eq!(code(&with("scope: household", "scope: seat")), "seats_missing");
assert_eq!(code(&with("calenda,tabula", "calenda,,tabula")), "bad_apps");
assert_eq!(code(&with("calenda,tabula", "tabula,calenda")), "apps_unsorted");
assert_eq!(code(&with("calenda,tabula", "calenda,calenda")), "apps_duplicate");
let many: Vec<String> = (0..65).map(|i| format!("app{i:03}")).collect();
assert_eq!(code(&with("calenda,tabula", &many.join(","))), "too_many_apps");
assert_eq!(code(&with("apps: calenda,tabula\n", "apps: calenda,tabula\nsig: x\n")), "unknown_field");
let mut big = ok.clone();
big.truncate(big.len() - 1);
big.extend(std::iter::repeat_n(b'a', LICENCE_PAYLOAD_MAX));
big.push(b'\n');
assert_eq!(code(&big), "too_large");
// A seat licence is fine.
assert!(parse_payload(&with("scope: household", "scope: seat\nseats: 50")).is_ok());
}
#[test]
fn a_revocation_list_parses_strictly() {
let a = "AAAAAAAAAAAAAAAAAAAAAA";
let b = "BBBBBBBBBBBBBBBBBBBBBB";
assert!(matches!(parse_payload(&revocations(1, &[])).unwrap(), Payload::Revocations(r) if r.revoked.is_empty()));
assert!(matches!(parse_payload(&revocations(7, &[a, b])).unwrap(), Payload::Revocations(r) if r.seq == 7));
assert_eq!(code(&revocations(7, &[b, a])), "revoked_unsorted");
assert_eq!(code(&revocations(7, &[a, a])), "revoked_duplicate");
assert_eq!(code(&revocations(0, &[])), "bad_seq");
assert_eq!(code(&revocations(MAX_SEQ + 1, &[])), "bad_seq");
assert_eq!(code(b"domi-revocations-v1\nissued: 2026-11-28T20:15:07Z\n"), "missing_field");
let reordered = b"domi-revocations-v1\nseq: 3\nrevoked: AAAAAAAAAAAAAAAAAAAAAA\nissued: 2026-11-28T20:15:07Z\n";
assert_eq!(code(reordered), "field_order");
}
#[test]
fn the_grant_signs_an_allowed_licence_and_a_signature_verifies() {
let mut v = vault();
let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula");
// No grant yet: a card.
assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap().card, vec![CardReason::NoGrant]);
assert_eq!(v.licence_sign(&p, ISSUER, LicenceBy::Grant, NOW), Err(LicenceRefusal::NeedsCard));
v.licence_grant_set(&["tabula".into(), "calenda".into()], NOW).unwrap();
let sig = v.licence_sign(&p, ISSUER, LicenceBy::Grant, NOW).unwrap();
assert_eq!(sig.len(), 86);
let raw = data_encoding::BASE64URL_NOPAD.decode(sig.as_bytes()).unwrap();
let key = ed25519_dalek::VerifyingKey::from_bytes(&v.licence_public().unwrap()).unwrap();
let sig = ed25519_dalek::Signature::from_slice(&raw).unwrap();
assert!(key.verify_strict(&p, &sig).is_ok(), "plain Ed25519 over the exact payload");
assert_eq!(v.licence_grant().unwrap().uses, 1);
assert_eq!(v.licence_log()[0].licence.as_deref(), Some("k3Jx0Qm1T9yZpW2bA7cD4e"));
// The same id again is a replay, refused with no card.
assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap_err(), LicenceRefusal::Replay);
}
#[test]
fn off_the_allowlist_unsigned_programs_and_the_cap_ask_on_a_card() {
let mut v = vault();
v.licence_grant_set(&["tabula".into()], NOW).unwrap();
let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula");
assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap().card, vec![CardReason::OffAllowlist { apps: vec!["calenda".into()] }]);
let unsigned = Caller { app: LICENCE_ISSUER, domi_signed: false };
let q = licence("k3Jx0Qm1T9yZpW2bA7cD4f", "tabula");
assert_eq!(v.licence_ask(&q, unsigned, NOW).unwrap().card, vec![CardReason::NotDomiSigned]);
for i in 0..DAY_CAP {
v.licence_sign(&licence(&format!("id-number-{i:03}"), "tabula"), ISSUER, LicenceBy::Grant, NOW).unwrap();
}
assert_eq!(v.licence_ask(&q, ISSUER, NOW).unwrap().card, vec![CardReason::OverCap { signed: DAY_CAP }]);
// Mark's card signs past the cap; a day later the grant signs again.
assert!(v.licence_sign(&q, ISSUER, LicenceBy::Card, NOW).is_ok());
let r = licence("k3Jx0Qm1T9yZpW2bA7cD4g", "tabula");
assert_eq!(v.licence_ask(&r, ISSUER, NOW + DAY_MS).unwrap().card, vec![]);
}
#[test]
fn refused_without_a_card_another_caller_a_bad_clock_and_a_rollback() {
let mut v = vault();
v.licence_grant_set(&["tabula".into()], NOW).unwrap();
let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "tabula");
let other = Caller { app: "atrium", domi_signed: true };
assert_eq!(v.licence_ask(&p, other, NOW).unwrap_err(), LicenceRefusal::NotAllowed);
assert_eq!(v.licence_ask(&p, ISSUER, NOW + 2 * DAY_MS).unwrap_err(), LicenceRefusal::Clock);
assert_eq!(v.licence_ask(&p, ISSUER, NOW - 2 * DAY_MS).unwrap_err(), LicenceRefusal::Clock);
// A revocation list always asks, and never goes back.
let r5 = revocations(5, &["k3Jx0Qm1T9yZpW2bA7cD4e"]);
assert_eq!(v.licence_ask(&r5, ISSUER, NOW).unwrap().card, vec![CardReason::Revocations]);
assert_eq!(v.licence_sign(&r5, ISSUER, LicenceBy::Grant, NOW), Err(LicenceRefusal::NeedsCard));
v.licence_sign(&r5, ISSUER, LicenceBy::Card, NOW).unwrap();
assert_eq!(v.licence_ask(&r5, ISSUER, NOW).unwrap_err(), LicenceRefusal::Rollback);
assert_eq!(v.licence_ask(&revocations(4, &[]), ISSUER, NOW).unwrap_err(), LicenceRefusal::Rollback);
assert!(v.licence_ask(&revocations(6, &[]), ISSUER, NOW).is_ok());
}
#[test]
fn the_licence_key_signs_nothing_else_and_its_state_survives_a_save() {
let mut v = vault();
assert!(v.licence_key_create(NOW).is_err(), "one licence key");
let req = crate::signing::Request {
key: LICENCE_KEY.into(),
kind: crate::signing::SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-1".into()),
context: crate::signing::Context {
repo: "mnovak/Custos".into(),
pipeline: "release".into(),
file: "x.exe".into(),
..Default::default()
},
via: crate::signing::Via::Local,
};
assert!(matches!(v.signing_check(&req), Err(crate::signing::Refusal::Invalid(_))));
assert!(v.signing_set_scope(LICENCE_KEY, &["*".into()], &["*".into()]).is_err());
v.licence_grant_set(&["tabula".into()], NOW).unwrap();
v.licence_sign(&licence("k3Jx0Qm1T9yZpW2bA7cD4e", "tabula"), ISSUER, LicenceBy::Grant, NOW).unwrap();
let again = Vault::open(&v.to_bytes().unwrap(), &crate::SecretString::from("pw")).unwrap();
assert_eq!(again.licence_public(), v.licence_public());
assert_eq!(again.licence_grant(), v.licence_grant());
assert_eq!(again.licence_log(), v.licence_log());
}
}
+3 -62
View File
@@ -299,8 +299,6 @@ pub(crate) struct Store {
pub(crate) audit: Vec<AuditEntry>, pub(crate) audit: Vec<AuditEntry>,
standing: Vec<StandingRule>, standing: Vec<StandingRule>,
android: Option<AndroidGrant>, android: Option<AndroidGrant>,
/// The licence grant and log (core 0.21.0, `licence.rs`).
pub(crate) licence: crate::licence::LicenceStore,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -338,10 +336,6 @@ pub(crate) struct StoreJson {
/// The Android grant (core 0.19.0); absent while there is none. Older cores ignore and drop it. /// The Android grant (core 0.19.0); absent while there is none. Older cores ignore and drop it.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
android: Option<AndroidGrant>, android: Option<AndroidGrant>,
/// The licence grant and log (core 0.21.0); absent while empty. Older cores ignore and drop it: the grant is then
/// gone (every licence asks on a card), and the key, an ordinary Ed25519 entry, stays.
#[serde(default, skip_serializing_if = "Option::is_none")]
licence: Option<crate::licence::LicenceStore>,
} }
fn b64(bytes: &[u8]) -> String { fn b64(bytes: &[u8]) -> String {
@@ -369,11 +363,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> {
impl Store { impl Store {
pub(crate) fn is_empty(&self) -> bool { pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() && self.android.is_none()
&& self.audit.is_empty()
&& self.standing.is_empty()
&& self.android.is_none()
&& self.licence.is_empty()
} }
pub(crate) fn from_json(j: StoreJson) -> Option<Store> { pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
@@ -435,20 +425,7 @@ impl Store {
if j.android.as_ref().is_some_and(|g| !grant_ok(g)) { if j.android.as_ref().is_some_and(|g| !grant_ok(g)) {
return None; return None;
} }
let licence = j.licence.unwrap_or_default(); Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android })
// The licence key is what `add_licence_key` makes: Ed25519 with its public key, release, no scope.
let licence_key_ok = |k: &Key| {
k.id != crate::licence::LICENCE_KEY
|| (k.kind == KeyKind::Ed25519
&& k.role == Role::Release
&& k.public.is_some()
&& k.pipelines.is_empty()
&& k.repos.is_empty())
};
if !licence.ok() || !keys.iter().all(licence_key_ok) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android, licence })
} }
pub(crate) fn json(&self) -> Option<StoreJson> { pub(crate) fn json(&self) -> Option<StoreJson> {
@@ -482,42 +459,12 @@ impl Store {
audit: self.audit.clone(), audit: self.audit.clone(),
standing: self.standing.clone(), standing: self.standing.clone(),
android: self.android.clone(), android: self.android.clone(),
licence: (!self.licence.is_empty()).then(|| self.licence.clone()),
}) })
} }
pub(crate) fn get(&self, id: &str) -> Option<&Key> { pub(crate) fn get(&self, id: &str) -> Option<&Key> {
self.keys.iter().find(|k| k.id == id) self.keys.iter().find(|k| k.id == id)
} }
/// Adds the licence key (`licence.rs`): Ed25519, a release key with no scope and no minisign key id, so no
/// pipeline or repository can ever be in its scope. The caller checked there is none. Returns its public key.
pub(crate) fn add_licence_key(&mut self, now: i64) -> [u8; 32] {
let ed = custos_sign::new_ed25519();
self.keys.push(Key {
id: crate::licence::LICENCE_KEY.into(),
kind: KeyKind::Ed25519,
role: Role::Release,
name: "Domi licence".into(),
secret: Secret::Ed25519(ed.secret),
public: Some(ed.public),
key_id: None,
cert: None,
issuer: None,
created: now,
pipelines: Vec::new(),
repos: Vec::new(),
});
ed.public
}
/// The licence key's plain Ed25519 signature over `payload` (`licence.rs` parsed and allowed it).
pub(crate) fn licence_signature(&self, payload: &[u8]) -> Option<[u8; 64]> {
match &self.get(crate::licence::LICENCE_KEY)?.secret {
Secret::Ed25519(s) => Some(custos_sign::ed25519_plain(s, payload)),
_ => None,
}
}
} }
/// Unix seconds from the vault's milliseconds, as minisign and approvals count them. /// Unix seconds from the vault's milliseconds, as minisign and approvals count them.
@@ -793,7 +740,7 @@ impl Vault {
{ {
return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into())); return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into()));
} }
if self.signing.get(id).is_some() || id == crate::licence::LICENCE_KEY { if self.signing.get(id).is_some() {
return Err(Error::Signing(format!("there is a key `{id}` already"))); return Err(Error::Signing(format!("there is a key `{id}` already")));
} }
let name = spec.name.trim(); let name = spec.name.trim();
@@ -867,9 +814,6 @@ impl Vault {
if k.kind == KeyKind::RootCa { if k.kind == KeyKind::RootCa {
return Err(Error::Signing("a root CA signs no requests, so it has no scope".into())); return Err(Error::Signing("a root CA signs no requests, so it has no scope".into()));
} }
if k.id == crate::licence::LICENCE_KEY {
return Err(Error::Signing("the licence key signs Domi licences only, so it has no scope".into()));
}
k.pipelines = pipelines; k.pipelines = pipelines;
k.repos = repos; k.repos = repos;
Ok(()) Ok(())
@@ -897,9 +841,6 @@ impl Vault {
/// The check, and the approval it read (for an approval request). /// The check, and the approval it read (for an approval request).
fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option<custos_sign::Approval>), Refusal> { fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option<custos_sign::Approval>), Refusal> {
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?; let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
if k.id == crate::licence::LICENCE_KEY {
return Err(Refusal::Invalid(format!("`{}` signs Domi licences only (licence.rs)", k.id)));
}
let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release; let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release;
let fits = match (k.kind, req.kind) { let fits = match (k.kind, req.kind) {
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY, (KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY,
+67 -36
View File
@@ -1,12 +1,13 @@
# Custos in the browser # Custos in the browser
Version 1 of the browser extension: Chromium (Edge and Chrome) on Windows, logins only. Passkeys come later. Version 2 of the browser extension (core 0.20.0): Firefox, Edge and Chrome on Windows, from one source; logins
and their 2FA codes, and saving a new login. Passkeys come later.
The extension, its native host and the rule that decides which login belongs on which page are all in this The extension, its native host and the rule that decides which login belongs on which page are all in this
public repository, so anyone can read what the browser side does. The desktop app (the private `Custos` public repository, so anyone can read what the browser side does. The desktop app (the private `Custos`
repo) holds the vault and answers the host; its side is `docs/13_browser.md` there. repo) holds the vault and answers the host; its side is `docs/13_browser.md` there.
``` ```
page ─(content script)─► service worker ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe page ─(content script)─► background ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe
extension/content.js extension/background.js crates/custos-native the desktop app extension/content.js extension/background.js crates/custos-native the desktop app
``` ```
@@ -14,11 +15,12 @@ page ─(content script)─► service worker ─(native messaging)─► custos
| Piece | What it does | What it never does | | Piece | What it does | What it never does |
|:--|:--|:--| |:--|:--|:--|
| `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on click asks for the logins of *its own frame*, and fills the one the person picks. | Fill without a click; read anything from Custos before the list is opened; trust what the page says about its own address. | | `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on a (trusted) click asks for the logins of *its own frame*, and fills the one the person picks: username and password, or only the 2FA code on a page that asks only for that. When a form is sent with a password the person typed (not one Custos filled), offers to save it. | Fill without a click; read anything from Custos before the list is opened; put a secret anywhere but its field; trust what the page says about its own address. |
| `extension/popup.*` | The toolbar popup: the logins for the active tab; a click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. | | `extension/popup.*` | The toolbar popup: the logins for the active tab, a 2FA code on request, a login offered for saving, and this connection's match code. A click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. |
| `extension/background.js` | Owns the one connection to the native host; turns each request into `browser_status`, `browser_match` or `browser_fill`, with the origin taken from **`sender.url`** (the frame's real URL, as the browser reports it). | Accept messages from pages or other extensions (`sender.id` must be its own). | | `extension/background.js` | Owns the one connection to the native host; turns each request into a `browser_*` op, with the frame's origin from **`sender.url`** and its page's from **`sender.tab.url`** (as the browser reports them). Holds a login offered for saving in memory, for its tab, at most 3 minutes. | Accept messages from pages or other extensions (`sender.id` must be its own); ask for a frame whose real origin is not its URL's (`sender.origin`, e.g. a sandboxed frame); write anything to `storage`. |
| `crates/custos-native` | The native messaging host. Reads frames from stdin, **rebuilds** each request from its known fields (op, origin ≤ 2 KiB, id ≤ 128 bytes, seq), forwards it to the Custos pipe and returns the answer. | Forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed answers are zeroized). | | `crates/custos-native` | The native messaging host. Checks who started it (`custos_browser::caller`); reads frames from stdin, **rebuilds** each request from its known fields, adds its connection's `session`, forwards it to the Custos pipe and returns the answer. | Answer an extension that is not Custos's (`not_allowed`, nothing reaches Custos); forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed messages are zeroized). |
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match` (which login fits which page) and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. | | `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match`, `fill_allowed` (which login fits which frame of which page), `caller`, and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
| `tools/extension.mjs` | Builds `target/extension/firefox/` and `…/chromium/` from the one source with each browser's manifest (`extension/manifest.<browser>.json`) and the workspace version; `--zip` writes reproducible packages for AMO and the stores. | Differ per browser: the scripts are the same files. |
## Which login goes where (`custos-browser`) ## Which login goes where (`custos-browser`)
@@ -31,69 +33,98 @@ fields (an item may have several) match a page when:
3. the ports are equal (the stored URL's port, or the scheme's default when it names none); 3. the ports are equal (the stored URL's port, or the scheme's default when it names none);
4. the page's host is the login's host (**exact**; `www.` counts as the host) or a subdomain of it 4. the page's host is the login's host (**exact**; `www.` counts as the host) or a subdomain of it
(**subdomain**: `accounts.github.com` for `github.com`). A login for a subdomain never goes to its parent (**subdomain**: `accounts.github.com` for `github.com`). A login for a subdomain never goes to its parent
or to a sibling. A login for an IP address or a bare name (`cz`) matches only that exact host. or to a sibling. A login for an IP address, a bare name (`cz`) or a **public suffix** (`co.uk`, `github.io`,
`herokuapp.com`: Mozilla's Public Suffix List, the `psl` crate) matches only that exact host, because the
subdomains of a public suffix belong to different people;
5. **in a frame** (`fill_allowed`): the frame matches, and when the frame is not the top page, the top page
matches too. `evil.net` framing `github.com/login` gets nothing, and neither does an ad frame on
`github.com`.
URLs with userinfo (`https://bank.cz@evil.net`) are refused outright. Look-alikes (`github.com.evil.net`, URLs with userinfo (`https://bank.cz@evil.net`), a port that is not only digits (`:+443`) or a host that is not
ASCII (the browser reports punycode, and that is what is compared) are refused outright. Look-alikes (`github.com.evil.net`,
`githuh.com`, punycode twins) never match, because nothing is compared but labels. Exact matches are offered `githuh.com`, punycode twins) never match, because nothing is compared but labels. Exact matches are offered
before subdomain matches, then by title; at most 50 logins per page. before subdomain matches, then by title; at most 50 logins per page.
## The messages ## The messages
Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON. The host accepts at most 64 KiB per Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON (the same in Firefox and Chromium). The
message (the desktop pipe's limit). Every request may carry `seq` (a number); the answer carries it back. host accepts at most 64 KiB per message (the desktop pipe's limit). Every request may carry `seq` (a number); the
answer carries it back. The host adds `app`, `browser` (`firefox` from its arguments; `edge`, `chrome` or
`chromium` as the extension says, a label) and `session` (64 hex digits, random per connection) to each.
| Extension → host | Host → Custos | Answer | | Extension → host | Answer |
|:--|:--|:--| |:--|:--|
| `{"op":"browser_status"}` | `{"op":"browser_status","app":"Custos for your browser"}` | `{"ok":true}` | | `{"op":"browser_status"}` | `{"ok":true,"code":"123456"}`: the session's match code |
| `{"op":"browser_match","origin":"https://github.com"}` | + `origin` | `{"ok":true,"logins":[{"id","title","username"}]}`: never a password | | `{"op":"browser_match","origin","top"}` | `{"ok":true,"logins":[{"id","title","username","totp"}]}` (`totp`: it has a 2FA code); never a secret |
| `{"op":"browser_fill","id":"…","origin":"…"}` | + `origin`, `id` | `{"ok":true,"username","password","totp"}` only if that login matches `origin`, else `"error":"no_match"` | | `{"op":"browser_fill","id","origin","top"}` | `{"ok":true,"username","password","totp"}` only if that login may go into that frame of that page, else `no_match` |
| `{"op":"browser_totp","id","origin","top"}` | `{"ok":true,"totp","remaining"}` (seconds left) under the same rule; `no_totp` without one |
| `{"op":"browser_save","origin","top","username","password"[,"title"]}` | after Custos's card: `{"ok":true,"saved":"new"/"updated"/"unchanged"}`, or `refused` |
Errors the extension turns into a sentence: `not_connected` (no host registered), `not_running`, Limits: `origin`, `top` ≤ 2 KiB, `id` ≤ 128 bytes, `username` ≤ 1 KiB, `password` 1 byte to 4 KiB, `title`
`not_custos` (the pipe's server is not `custos.exe`: nothing was sent), `locked`, `denied`, `not_found`, ≤ 200 bytes. Errors the extension turns into a sentence: `not_connected` (no host registered), `not_allowed`
`no_match`, `no_answer`, `bad_request`. (not the Custos extension), `not_running`, `not_custos` (the pipe's server is not `custos.exe`: nothing was sent),
`locked`, `denied`, `refused`, `not_found`, `no_match`, `no_totp`, `no_answer`, `bad_request`.
## What Custos checks (the desktop's side, summarised) ## What Custos checks (the desktop's side, summarised)
- The host is a Domi client like any other: Custos identifies it by its executable and asks the person once - The host is a Domi client like any other: Custos identifies it by its executable and asks the person once
whether it may use **`web-logins/`**. That grant is the browser's only; no `domi://` ref may use the whether it may use **`web-logins/`**. That grant is the browser's only; no `domi://` ref may use the
`web-logins` namespace and the browser ops reach nothing else. `web-logins` namespace and the browser ops reach nothing else.
- Custos parses the origin again with `custos-browser` and checks the login against it on **every** - Custos parses both origins again with `custos-browser` and checks the login with `fill_allowed` on **every**
`browser_fill`, whatever the extension asked for before. `browser_fill` and `browser_totp`, whatever the extension asked for before.
- The grant card shows the session's match code, the one the popup shows. Every fill, code and save goes in the
vault's audit with that code.
- `browser_save` always shows a card (*Save* / *Don't save*): a new *Web login* for the origin, or, when a login
of that site has the same username, its new password. An identical login is `unchanged`, without a card.
- Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then - Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then
answers `locked`. answers `locked`.
## Registration and the extension id ## Registration and the extension ids
The extension's `manifest.json` carries a public `key`, which fixes its id to | Browser | Extension id | Host manifest | Registry (HKCU, per user) |
**`jchkapmceepdnlhagfppeckggaecdcmn`** however it is loaded (unpacked or packed). The desktop's *Connect* |:--|:--|:--|:--|
writes the host manifest with `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]` | Firefox | `custos@marek-novak.cz` (`browser_specific_settings.gecko.id`) | `"allowed_extensions": ["custos@marek-novak.cz"]` | `Software\Mozilla\NativeMessagingHosts\cz.marek_novak.custos` |
and registers it under `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` and | Edge | `jchkapmceepdnlhagfppeckggaecdcmn` (the `key` in `manifest.chromium.json`) | `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]` | `Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` |
`HKCU\Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos`, so only this extension can start | Chrome | the same | the same | `Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos` |
the host. The private key that matches the public key is not in this repository; it is only needed to pack a
`.crx` with the same id. The desktop writes both host manifests and registers them. The Chromium `key` fixes the id however the extension
is loaded; the private key that matches it is not in this repository (it is held in Custos) and is needed only to
pack a `.crx`, or for the first upload to the Chrome Web Store, to keep the id. Release Firefox installs only
add-ons signed by Mozilla: the Firefox zip is signed through AMO as an *unlisted* (self-distributed) add-on.
## Threat model, briefly ## Threat model, briefly
- A malicious **page** cannot ask for a login: content scripts run in an isolated world, the button and list - A malicious **page** cannot ask for a login: content scripts run in an isolated world, the button and list
are in a closed shadow root, the origin comes from the browser, and filling needs a click in Custos's own UI. are in a closed shadow root, the origin comes from the browser, and filling needs a click in Custos's own UI.
A page *can* read what was filled into its own fields: that is what filling is. A page *can* read what was filled into its own fields: that is what filling is.
- A malicious **frame** on a good site is a different origin: it gets only its own origin's logins. - A malicious **frame** on a good site is a different origin: it gets only its own origin's logins, and those
- Another **extension** cannot message this one (`sender.id`), and cannot start the host (`allowed_origins`). only if the page around it matches them too. A good site framed by a malicious page gets nothing.
- Another **extension** cannot message this one (`sender.id`), cannot start the host (`allowed_origins`,
`allowed_extensions`), and if a stray manifest let it, the host answers it only `not_allowed` (`caller`).
- A page can make the extension *offer* to save a login for **its own** origin, with values of its choosing; it
is saved only on Custos's card, which names the site.
- A program that **impersonates Custos** by creating the pipe first gets nothing: the host checks the pipe - A program that **impersonates Custos** by creating the pipe first gets nothing: the host checks the pipe
server's image path ends in `\custos.exe` before writing the request. (A process of the same user that can server's image path ends in `\custos.exe` before writing the request. (A process of the same user that can
replace `custos.exe` is out of scope, as everywhere in Custos: docs/THREAT_MODEL.md.) replace `custos.exe` is out of scope, as everywhere in Custos: docs/THREAT_MODEL.md.)
- The extension holds no secret at rest and no state beyond the open native port. - The extension holds no secret at rest. Its only state is the open native port and, for a login offered for
saving, that login in the background's memory for at most 3 minutes (JavaScript strings cannot be wiped;
they are dropped).
## Not yet ## Not yet
Passkeys (WebAuthn through the extension), Firefox, saving new logins from the browser, filling cards. Passkeys (WebAuthn through the extension), filling cards, other operating systems.
## Tests ## Tests
``` ```
cargo test -p custos-browser -p custos-native cargo test -p custos-browser -p custos-native
node tools/extension-test.mjs
``` ```
`custos-browser` covers origin parsing, look-alikes, ports and schemes, bare names and IPs, best-of-several and `custos-browser` covers origin parsing, look-alikes (punycode twins, extra labels, userinfo, encoded dots,
the frames; `custos-native` that only the three ops pass, rebuilt from known fields. The desktop repo has the backslashes, odd ports), public suffixes, frames and their pages, ports and schemes, bare names and IPs,
pipe tests and an end-to-end run in Edge. best-of-several, the callers and the frames. `custos-native` covers that only the five ops pass, rebuilt from
known fields, and that another extension gets `not_allowed` without reaching Custos. `tools/extension-test.mjs`
runs the background script against a fake browser: origins from the browser and never from the message, frames,
sandboxed and blank frames, other extensions, a locked Custos, and a login offered for saving that never comes back
out. The desktop repo has the pipe tests and the end-to-end runs in each browser.
-78
View File
@@ -302,77 +302,6 @@ Never covered by the grant: another kind, the server runner, a pipeline other th
matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card* matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card*
is ticked. is ticked.
## Domi licences (core 0.21.0)
A Domi licence is a small text file the Atrium Domi service checks before it unlocks a paid app. Its byte format,
the paste code, the revocation list and the service's own checks are Fundamentum's `docs/LICENCE.md` (licence v1);
this core is the one that **signs**, and it parses what it signs exactly as that spec's strict parser does. The code
is `crates/custos-vault/src/licence.rs`.
### The key
- One key per vault, **`domi-licence`**: Ed25519, made in the vault by Mark's click (`licence_key_create`), never
exported. Only its 32-byte public key leaves (`licence_public`); the service ships it.
- It is stored as an ordinary Ed25519 entry (release, **no scope**, no minisign key id), so every core reads the vault
as before. An empty scope is never in scope, so no older core can sign with it either.
- It signs **only** the two payload kinds below, as a plain Ed25519 signature over the exact payload bytes (no
prehash, no digest; `custos_sign::ed25519_plain`). `signing_check` refuses it for every other kind, its scope
cannot be set, no Android key can take its id, and no other key signs these payloads.
### What it signs
| Payload | Starts with | Cap (bytes) | Parser |
| :-- | :-- | :-- | :-- |
| a licence | `domi-licence-v1
` | 4004 | LICENCE.md §2.4 steps 1–4 and 7 |
| a revocation list | `domi-revocations-v1
` | 61 348 | LICENCE.md §4.1 |
The caps are the spec's file caps (4096 and 61 440) less the `sig:` line (92 bytes), so every file signed here also
passes the service's size check. A malformed payload is refused with the spec's error code (§8: `too_large`,
`crlf`, `bad_byte`, `bad_prefix`, `truncated`, `bad_line`, `unknown_field`, `duplicate_field`, `field_order`,
`missing_field`, `bad_id`, `bad_issued`, `bad_nickname`, `bad_bundle`, `bad_scope`, `bad_seats`,
`seats_with_household`, `seats_missing`, `bad_apps`, `apps_unsorted`, `apps_duplicate`, `too_many_apps`,
`bad_seq`, `revoked_unsorted`, `revoked_duplicate`) and **never reaches a card**. A payload never contains a `sig:`
line: one is an `unknown_field`.
### The licence grant
One grant per vault, in `signing.licence.grant`, given by Mark's click (`licence_grant_set`, `standing-granted`) and
removed the same way (`licence_grant_revoke`, `standing-revoked`):
```json
"licence": { "grant": { "allow": ["calenda", "fiscus", "medicus", "tabula"], "granted": 1795896907000,
"lastUsed": 1795896990000, "uses": 4 },
"log": [ { "at": 1795896990000, "by": "grant", "licence": "k3Jx0Qm1T9yZpW2bA7cD4e",
"apps": ["calenda", "tabula"] },
{ "at": 1795897000000, "by": "card", "seq": 7, "revoked": 3 } ] }
```
`licence_ask(payload, caller, now)` decides, and changes nothing:
| | Result |
| :-- | :-- |
| malformed | refused, the spec's code |
| no `domi-licence` key | refused, `no_key` |
| a caller whose Canalis app id is not `licence-issue` | refused, `not_allowed` |
| the log holds 20 000 signatures | refused, `log_full` (it never forgets what replay and rollback need) |
| a licence whose `issued` is more than 24 h from this clock, either way | refused, `clock` |
| a licence id this key signed before | refused, `replay` |
| a revocation list whose `seq` is not higher than every `seq` this key signed | refused, `rollback` |
| a revocation list | **a card, always** |
| a licence, and any of: no grant; a caller program not signed with Domi's certificate; *Sign only with a card* ticked; an app not on `allow`; 50 licences signed in the last 24 h | a card, with each reason |
| a licence and none of those | signed by the grant, no card |
`licence_sign(payload, caller, by, now)` checks again, refuses `needs_card` when `by` is `grant` and the grant does
not cover it, signs, returns the signature in base64url without padding (86 characters), logs it (when, how, the
licence id and its apps, or the list's `seq` and how many ids it revokes: never the signature, the payload or the
nickname) and counts the grant's use.
Cores before 0.21.0 ignore `signing.licence` and drop it if they save the vault: the grant is then gone, so every
licence asks again, and the key stays. Replay and rollback are then only as good as what is left; the service keeps
its own anti-rollback check (LICENCE.md §4.2), which a restored or rewritten vault cannot get past.
## The audit log ## The audit log
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets `audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
@@ -432,13 +361,6 @@ Vault::android_grant_set(repos, o, c, now) -> Result<AndroidGrant,
Vault::android_grant_revoke(now) -> bool Vault::android_grant_revoke(now) -> bool
Vault::android_grant_fits(req, now) -> bool Vault::android_grant_fits(req, now) -> bool
Vault::android_grant_make_key(repo, pipeline, via, now) -> Result<String, Error> Vault::android_grant_make_key(repo, pipeline, via, now) -> Result<String, Error>
licence::parse_payload(bytes) -> Payload | LicenceRefusal (core 0.21.0)
Vault::licence_key_create(now) -> [u8; 32] // the public key, never the secret
Vault::licence_public() -> Option<[u8; 32]>
Vault::licence_grant() / licence_grant_set(allow, now) / licence_grant_revoke(now)
Vault::licence_ask(payload, Caller { app, domi_signed }, now) -> LicenceAsk { payload, card: [CardReason] }
Vault::licence_sign(payload, caller, LicenceBy::{Grant, Card}, now) -> base64url signature
Vault::licence_log() -> [LicenceEntry]
``` ```
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test. No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
+151 -31
View File
@@ -1,27 +1,41 @@
// Custos's service worker (docs/BROWSER.md). It owns the connection to the native host and answers the // Custos's background script (docs/BROWSER.md): an event page in Firefox, a service worker in Edge and Chrome.
// content scripts and the popup. The page origin it sends to Custos is always the browser's (`sender.url`, // It owns the connection to the native host and answers the content scripts and the popup. The origins it sends
// the tab's URL), never what a page says about itself; Custos decides which logins belong to it. // to Custos are always the browser's (`sender.url` of the frame, `sender.tab.url` of its page), never what a page
// says about itself; Custos decides which logins belong there.
//
// It keeps no secret at rest: nothing goes to `storage`, and a login offered for saving waits in memory only, for
// its tab, until it is saved, dismissed or three minutes old.
const api = globalThis.browser ?? globalThis.chrome;
const HOST = 'cz.marek_novak.custos'; const HOST = 'cz.marek_novak.custos';
const SAVE_KEPT_MS = 3 * 60_000;
/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */ /** Which browser this is, for Custos's card (a label only: the host knows Firefox from its arguments). */
function browserHint() {
const brands = (globalThis.navigator?.userAgentData?.brands ?? []).map((b) => b.brand);
if (brands.includes('Microsoft Edge')) return 'edge';
if (brands.includes('Google Chrome')) return 'chrome';
return null;
}
/** The native host, connected on first use; the browser keeps the background alive while it is open. */
let port = null; let port = null;
let seq = 0; let seq = 0;
const waiting = new Map(); const waiting = new Map();
function connect() { function connect() {
if (port) return port; if (port) return port;
port = chrome.runtime.connectNative(HOST); port = api.runtime.connectNative(HOST);
port.onMessage.addListener((msg) => { port.onMessage.addListener((msg) => {
const w = waiting.get(msg.seq); const w = waiting.get(msg?.seq);
if (!w) return; if (!w) return;
waiting.delete(msg.seq); waiting.delete(msg.seq);
w(msg); w(msg);
}); });
port.onDisconnect.addListener(() => { port.onDisconnect.addListener((p) => {
// Not registered, or the host exited: every open request fails the same way. // Not registered, or the host exited: every open request fails the same way.
const why = chrome.runtime.lastError?.message ?? ''; const why = `${p?.error?.message ?? api.runtime.lastError?.message ?? ''}`;
const error = /not found|forbidden/i.test(why) ? 'not_connected' : 'not_running'; const error = /not found|forbidden|no such native application|not allowed/i.test(why) ? 'not_connected' : 'not_running';
for (const w of waiting.values()) w({ ok: false, error }); for (const w of waiting.values()) w({ ok: false, error });
waiting.clear(); waiting.clear();
port = null; port = null;
@@ -34,19 +48,19 @@ function ask(request) {
const n = ++seq; const n = ++seq;
waiting.set(n, resolve); waiting.set(n, resolve);
try { try {
connect().postMessage({ ...request, seq: n }); connect().postMessage({ ...request, browser: browserHint(), seq: n });
} catch { } catch {
waiting.delete(n); waiting.delete(n);
resolve({ ok: false, error: 'not_connected' }); resolve({ ok: false, error: 'not_connected' });
} }
// Custos may wait up to a minute for an unlock or an approval. // Custos may wait up to a minute for an unlock or an answer on its card.
setTimeout(() => { setTimeout(() => {
if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' }); if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' });
}, 75_000); }, 75_000);
}); });
} }
/** `https://host[:port]` of a page or frame URL; null for anything Custos never fills. */ /** `scheme://host[:port]` of a page or frame URL; null for anything Custos never fills. */
function originOf(url) { function originOf(url) {
try { try {
const u = new URL(url); const u = new URL(url);
@@ -57,35 +71,141 @@ function originOf(url) {
} }
} }
chrome.runtime.onMessage.addListener((msg, sender, reply) => { /**
// Only this extension's own pages and content scripts reach here; pages cannot send to it. * The frame's origin and its page's, from what the browser says about the sender. Null when either is unknown,
if (sender.id !== chrome.runtime.id) return false; * or when the frame's real origin is not its URL's (a sandboxed frame has an opaque origin: it gets nothing).
(async () => { */
function placeOf(sender) {
const origin = originOf(sender.url);
if (!origin) return null;
if (typeof sender.origin === 'string' && sender.origin !== origin) return null;
const top = sender.frameId === 0 ? origin : originOf(sender.tab?.url);
if (!top) return null;
return { origin, top };
}
// ---- logins offered for saving: in memory, per tab ----
const offers = new Map();
function offerFor(tabId) {
const o = offers.get(tabId);
if (o && Date.now() - o.at > SAVE_KEPT_MS) offers.delete(tabId);
return offers.get(tabId) ?? null;
}
function showBadge(tabId) {
const on = !!offerFor(tabId);
Promise.resolve(api.action.setBadgeText({ tabId, text: on ? '1' : '' })).catch(() => {});
if (on) Promise.resolve(api.action.setBadgeBackgroundColor({ tabId, color: '#c9a96e' })).catch(() => {});
}
api.tabs.onRemoved.addListener((tabId) => offers.delete(tabId));
/** What the popup and the page may see of an offer: never its password. */
const offerView = (o) => (o ? { host: new URL(o.origin).host, username: o.username } : null);
async function save(tabId) {
const o = offerFor(tabId);
if (!o) return { ok: false, error: 'gone' };
offers.delete(tabId);
showBadge(tabId);
const r = await ask({ op: 'browser_save', origin: o.origin, top: o.top, username: o.username, password: o.password, title: o.title });
o.password = '';
return r;
}
async function activeTab() {
const [tab] = await api.tabs.query({ active: true, currentWindow: true });
return tab ?? null;
}
// ---- messages from the content scripts and the popup ----
async function handle(msg, sender) {
switch (msg?.kind) { switch (msg?.kind) {
case 'status': case 'status':
return reply(await ask({ op: 'browser_status' })); return ask({ op: 'browser_status' });
case 'match': { case 'match': {
// From a content script: the logins for the frame it runs in. // From a content script: the logins for the frame it runs in, on its page.
const origin = originOf(sender.url); const at = placeOf(sender);
if (!origin) return reply({ ok: false, error: 'no_match' }); if (!at) return { ok: false, error: 'no_match' };
return reply({ ...(await ask({ op: 'browser_match', origin })), origin }); return { ...(await ask({ op: 'browser_match', ...at })), origin: at.origin };
} }
case 'fill': { case 'fill':
case 'totp': {
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there. // The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
const origin = originOf(sender.url); const at = placeOf(sender);
if (!origin || typeof msg.id !== 'string') return reply({ ok: false, error: 'no_match' }); if (!at || typeof msg.id !== 'string') return { ok: false, error: 'no_match' };
return reply(await ask({ op: 'browser_fill', id: msg.id, origin })); return ask({ op: msg.kind === 'fill' ? 'browser_fill' : 'browser_totp', id: msg.id, ...at });
} }
case 'offer-save': {
// A login form was sent with a password Custos did not fill: keep it for this tab until the person decides.
const at = placeOf(sender);
const tabId = sender.tab?.id;
if (!at || tabId == null || typeof msg.password !== 'string' || !msg.password || msg.password.length > 4096) {
return { ok: false, error: 'bad_request' };
}
const username = typeof msg.username === 'string' ? msg.username.slice(0, 1024) : '';
const title = new URL(at.origin).host;
offers.set(tabId, { ...at, username, password: msg.password, title, at: Date.now() });
showBadge(tabId);
// The open connection keeps a service worker (Edge, Chrome) alive, and the offer with it.
void ask({ op: 'browser_status' });
return { ok: true, offer: offerView(offers.get(tabId)) };
}
case 'pending-save': {
// The top page of the tab that sent the form, on the same site, asks whether to show the offer.
const at = placeOf(sender);
const o = sender.tab?.id != null ? offerFor(sender.tab.id) : null;
if (!at || !o || sender.frameId !== 0 || at.top !== o.top) return { ok: true, offer: null };
return { ok: true, offer: offerView(o) };
}
case 'save':
// From the page's own offer: its tab's offer only.
if (sender.tab?.id == null || sender.frameId !== 0) return { ok: false, error: 'bad_request' };
return save(sender.tab.id);
case 'dismiss-save':
if (sender.tab?.id != null) {
offers.delete(sender.tab.id);
showBadge(sender.tab.id);
}
return { ok: true };
case 'match-tab': { case 'match-tab': {
// From the popup: the logins for the active tab's page. // From the popup: the logins for the active tab's page, and any login offered for saving there.
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); const tab = await activeTab();
const origin = tab && originOf(tab.url); const origin = tab && originOf(tab.url);
if (!origin) return reply({ ok: false, error: 'no_match', tab: tab?.id ?? null }); const offer = tab ? offerView(offerFor(tab.id)) : null;
return reply({ ...(await ask({ op: 'browser_match', origin })), origin, tab: tab.id }); if (!origin) return { ok: false, error: 'no_match', tab: tab?.id ?? null, offer };
return { ...(await ask({ op: 'browser_match', origin, top: origin })), origin, tab: tab.id, offer };
}
case 'totp-tab': {
// From the popup: one login's 2FA code for the active tab's page.
const tab = await activeTab();
const origin = tab && originOf(tab.url);
if (!origin || typeof msg.id !== 'string') return { ok: false, error: 'no_match' };
return ask({ op: 'browser_totp', id: msg.id, origin, top: origin });
}
case 'save-tab': {
const tab = await activeTab();
return tab ? save(tab.id) : { ok: false, error: 'gone' };
}
case 'dismiss-tab': {
const tab = await activeTab();
if (tab) {
offers.delete(tab.id);
showBadge(tab.id);
}
return { ok: true };
} }
default: default:
return reply({ ok: false, error: 'bad_request' }); return { ok: false, error: 'bad_request' };
} }
})(); }
api.runtime.onMessage.addListener((msg, sender, reply) => {
// Only this extension's own pages and content scripts reach here; pages and other extensions cannot.
if (sender.id !== api.runtime.id) return false;
handle(msg, sender).then(reply, () => reply({ ok: false, error: 'bad_request' }));
return true; return true;
}); });
+115 -26
View File
@@ -1,18 +1,25 @@
// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this // Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this
// frame's site, and fills the one the person picks. Nothing is filled without a click. The button and the // frame's site, and fills the one the person picks. Nothing is filled without a click. The button, the list and
// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens. // the save offer live in a closed shadow root, out of the page's reach; logins are asked for only when the list
// opens, and a secret goes only into the field it is for.
(() => { (() => {
const api = globalThis.browser ?? globalThis.chrome;
const SENTENCES = { const SENTENCES = {
not_connected: 'Connect this browser in Custos first: Settings → Browser.', not_connected: 'Connect this browser in Custos first: Settings → Browser.',
not_running: 'Custos is not running. Start it, then try again.', not_running: 'Custos is not running. Start it, then try again.',
not_custos: 'Something other than Custos answered. Nothing was sent.', not_custos: 'Something other than Custos answered. Nothing was sent.',
not_allowed: 'This copy of the extension is not the one Custos knows.',
locked: 'Custos is locked. Unlock it, then try again.', locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.', denied: 'Custos did not allow this browser to use your logins.',
refused: 'Not saved.',
not_found: 'That login is no longer in Custos.', not_found: 'That login is no longer in Custos.',
no_match: 'That login does not belong to this site.', no_match: 'That login does not belong to this site.',
no_totp: 'That login has no 2FA code in Custos.',
no_answer: 'Custos did not answer.', no_answer: 'Custos did not answer.',
gone: 'That offer has expired.',
}; };
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.'; const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' }));
const visible = (el) => { const visible = (el) => {
const r = el.getBoundingClientRect(); const r = el.getBoundingClientRect();
@@ -44,38 +51,51 @@
return { user, pass, otp }; return { user, pass, otp };
} }
// Fields Custos filled and the person has not typed in since: a form sent with them is not offered for saving.
const filledByCustos = new WeakSet();
document.addEventListener('input', (e) => e.isTrusted && filledByCustos.delete(e.target), true);
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
function put(el, value) { function put(el, value) {
if (!el || typeof value !== 'string' || !value) return; if (!el || !el.isConnected || typeof value !== 'string' || !value) return;
el.focus(); el.focus();
setValue.call(el, value); setValue.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true }));
filledByCustos.add(el);
} }
/** Fills login `id` around `near`. Only what the page has fields for is asked for: a 2FA page gets the code only. */
async function fill(id, near) { async function fill(id, near) {
const r = await chrome.runtime.sendMessage({ kind: 'fill', id });
if (!r?.ok) return say(r?.error);
const f = fieldsAround(near); const f = fieldsAround(near);
if (!f.pass && !f.user && f.otp) {
const r = await send({ kind: 'totp', id });
if (!r?.ok) return say(r?.error);
put(f.otp, r.totp);
return null;
}
const r = await send({ kind: 'fill', id });
if (!r?.ok) return say(r?.error);
put(f.user, r.username); put(f.user, r.username);
put(f.pass, r.password); put(f.pass, r.password);
if (f.otp) put(f.otp, r.totp); if (f.otp) put(f.otp, r.totp);
return null; return null;
} }
// ---- the button and the list ---- // ---- the button, the list and the save offer ----
const host = document.createElement('custos-fill'); const host = document.createElement('custos-fill');
const root = host.attachShadow({ mode: 'closed' }); const root = host.attachShadow({ mode: 'closed' });
root.innerHTML = ` root.innerHTML = `
<style> <style>
:host { all: initial; } :host { all: initial; }
.chip, .menu { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; } .chip, .menu, .offer { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
.chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d; .chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d;
cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); } cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
.chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; } .chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; }
.menu { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px; .menu, .offer { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px;
background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); } background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); }
.offer { top: 12px; right: 12px; padding: 10px 12px; }
.head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; } .head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none; button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none;
color: inherit; text-align: left; cursor: pointer; font: inherit; } color: inherit; text-align: left; cursor: pointer; font: inherit; }
@@ -83,6 +103,10 @@
.title { font-weight: 600; } .title { font-weight: 600; }
.user { color: #9aa3b1; font-size: 12px; } .user { color: #9aa3b1; font-size: 12px; }
.note { padding: 6px 8px; color: #c9d1dc; } .note { padding: 6px 8px; color: #c9d1dc; }
.row { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }
.row button { padding: 5px 12px; border: 1px solid #3a404b; border-radius: 7px; background: #1d2128; color: inherit;
font: inherit; cursor: pointer; }
.row button.primary { border-color: #c9a96e; }
[hidden] { display: none !important; } [hidden] { display: none !important; }
</style> </style>
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden> <button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
@@ -90,11 +114,16 @@
fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none" fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none"
stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg> stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button> </button>
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>`; <div class="menu" role="menu" aria-label="Custos logins" hidden></div>
<div class="offer" role="dialog" aria-label="Save in Custos" hidden></div>`;
const chip = root.querySelector('.chip'); const chip = root.querySelector('.chip');
const menu = root.querySelector('.menu'); const menu = root.querySelector('.menu');
const offerBox = root.querySelector('.offer');
let field = null; let field = null;
const attach = () => host.isConnected || document.documentElement.append(host);
const el = (tag, props) => Object.assign(document.createElement(tag), props);
function place() { function place() {
if (!field || !field.isConnected) return hide(); if (!field || !field.isConnected) return hide();
const r = field.getBoundingClientRect(); const r = field.getBoundingClientRect();
@@ -111,48 +140,48 @@
} }
function note(text) { function note(text) {
menu.replaceChildren(Object.assign(document.createElement('div'), { className: 'note', textContent: text })); menu.replaceChildren(el('div', { className: 'note', textContent: text }));
menu.hidden = false; menu.hidden = false;
} }
async function open() { async function open() {
const target = field; const target = field;
note('Asking Custos…'); note('Asking Custos…');
const r = await chrome.runtime.sendMessage({ kind: 'match' }); const r = await send({ kind: 'match' });
if (field !== target) return; if (field !== target) return;
if (!r?.ok) return note(say(r?.error)); if (!r?.ok) return note(say(r?.error));
if (!r.logins.length) return note('Custos has no login for this site.'); if (!r.logins.length) return note('Custos has no login for this site.');
const head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' });
const items = r.logins.map((l) => { const items = r.logins.map((l) => {
const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' }); const b = el('button', { className: 'login', type: 'button' });
b.setAttribute('role', 'menuitem'); b.setAttribute('role', 'menuitem');
b.append( b.append(
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }), el('span', { className: 'title', textContent: l.title }),
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }), el('span', { className: 'user', textContent: (l.username || '—') + (l.totp ? ' · 2FA' : '') }),
); );
b.addEventListener('click', async () => { b.addEventListener('click', async (e) => {
if (!e.isTrusted) return;
const why = await fill(l.id, target); const why = await fill(l.id, target);
if (why) note(why); if (why) note(why);
else hide(); else hide();
}); });
return b; return b;
}); });
menu.replaceChildren(head, ...items); menu.replaceChildren(el('div', { className: 'head', textContent: 'Custos' }), ...items);
items[0]?.focus(); items[0]?.focus();
} }
chip.addEventListener('click', () => (menu.hidden ? void open() : (menu.hidden = true))); chip.addEventListener('click', (e) => e.isTrusted && (menu.hidden ? void open() : (menu.hidden = true)));
// A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it. // A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it.
host.addEventListener('mousedown', (e) => e.preventDefault()); host.addEventListener('mousedown', (e) => e.preventDefault());
document.addEventListener( document.addEventListener(
'focusin', 'focusin',
(e) => { (e) => {
const el = e.target; const t = e.target;
if (!(el instanceof HTMLInputElement) || !visible(el)) return; if (!(t instanceof HTMLInputElement) || !visible(t)) return;
if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return; if (t.type !== 'password' && !isOtp(t) && !(isText(t) && fieldsAround(t).pass) && !isUserName(t)) return;
if (!host.isConnected) document.documentElement.append(host); attach();
field = el; field = t;
menu.hidden = true; menu.hidden = true;
chip.hidden = false; chip.hidden = false;
place(); place();
@@ -164,9 +193,69 @@
window.addEventListener('scroll', place, true); window.addEventListener('scroll', place, true);
window.addEventListener('resize', place); window.addEventListener('resize', place);
// The popup's choice, in the top frame: fill the page's login form. // ---- saving a login the person typed ----
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
if (sender.id !== chrome.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false; function showOffer(offer) {
if (!offer || window.top !== window) return;
attach();
const yes = el('button', { type: 'button', className: 'primary', textContent: 'Save in Custos' });
const no = el('button', { type: 'button', textContent: 'Not now' });
yes.addEventListener('click', async (e) => {
if (!e.isTrusted) return;
offerBox.replaceChildren(el('div', { className: 'note', textContent: 'Answer in Custos…' }));
const r = await send({ kind: 'save' });
const done = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error);
offerBox.replaceChildren(el('div', { className: 'note', textContent: done }));
setTimeout(() => (offerBox.hidden = true), 2500);
});
no.addEventListener('click', (e) => {
if (!e.isTrusted) return;
void send({ kind: 'dismiss-save' });
offerBox.hidden = true;
});
offerBox.replaceChildren(
el('div', { className: 'head', textContent: 'Custos' }),
el('div', { className: 'note', textContent: `Save the login${offer.username ? ` of ${offer.username}` : ''} for ${offer.host}?` }),
Object.assign(el('div', { className: 'row' }), {}),
);
offerBox.lastChild.append(no, yes);
offerBox.hidden = false;
}
/** A form is being sent: if it has a password the person typed (not one Custos filled), offer to save it. */
function sent(form) {
const scope = form ? [...form.querySelectorAll('input')] : [...document.querySelectorAll('input')];
const pass = scope.find((i) => i.type === 'password' && visible(i) && i.value);
if (!pass || filledByCustos.has(pass)) return;
const user = usernameFor(pass);
// Read once, handed to the background in memory, and not kept here.
void send({ kind: 'offer-save', username: user?.value ?? '', password: pass.value }).then((r) => r?.ok && showOffer(r.offer));
}
document.addEventListener('submit', (e) => e.isTrusted && sent(e.target instanceof HTMLFormElement ? e.target : null), true);
// Pages that sign in by script never send a form: a click on their button, or Enter in the password, counts.
document.addEventListener(
'click',
(e) => {
if (!e.isTrusted) return;
const b = e.target instanceof Element ? e.target.closest('button, input[type=submit]') : null;
if (!b || b.form?.querySelector('input[type=password]') == null || (b.type && b.type !== 'submit')) return;
sent(b.form);
},
true,
);
document.addEventListener(
'keydown',
(e) => e.isTrusted && e.key === 'Enter' && e.target instanceof HTMLInputElement && e.target.type === 'password' && !e.target.form && sent(null),
true,
);
// After the sign-in page went away: the next page of the same site shows the offer.
if (window.top === window) void send({ kind: 'pending-save' }).then((r) => r?.ok && showOffer(r.offer));
// ---- the popup's choice, in the top frame: fill the page's login form, or only its 2FA field ----
api.runtime.onMessage.addListener((msg, sender, reply) => {
if (sender.id !== api.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false;
fill(msg.id, null).then((why) => reply({ ok: !why, error: why })); fill(msg.id, null).then((why) => reply({ ok: !why, error: why }));
return true; return true;
}); });
@@ -2,14 +2,19 @@
"manifest_version": 3, "manifest_version": 3,
"name": "Custos", "name": "Custos",
"short_name": "Custos", "short_name": "Custos",
"description": "Fills your logins from the Custos on this computer, only into the site they belong to.", "description": "Fills your logins from the Custos on this computer, only into the site they belong to, and offers to save new ones.",
"version": "0.15.0",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB", "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
"minimum_chrome_version": "116", "minimum_chrome_version": "116",
"permissions": [ "permissions": [
"nativeMessaging", "nativeMessaging",
"activeTab" "activeTab"
], ],
"host_permissions": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"background": { "background": {
"service_worker": "background.js" "service_worker": "background.js"
}, },
+54
View File
@@ -0,0 +1,54 @@
{
"manifest_version": 3,
"name": "Custos",
"short_name": "Custos",
"description": "Fills your logins from the Custos on this computer, only into the site they belong to, and offers to save new ones.",
"browser_specific_settings": {
"gecko": {
"id": "custos@marek-novak.cz",
"strict_min_version": "140.0",
"data_collection_permissions": {
"required": [
"none"
]
}
}
},
"permissions": [
"nativeMessaging",
"activeTab"
],
"host_permissions": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"background": {
"scripts": [
"background.js"
]
},
"action": {
"default_title": "Custos",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"js": [
"content.js"
],
"all_frames": true,
"run_at": "document_idle"
}
],
"content_security_policy": {
"extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'"
}
}
+53
View File
@@ -69,9 +69,62 @@ main {
color: var(--muted); color: var(--muted);
font-size: 12px; font-size: 12px;
} }
.logins li {
display: flex;
align-items: center;
gap: 6px;
}
.logins button.login {
flex: 1;
min-width: 0;
}
.logins button.code {
display: block;
width: auto;
flex: none;
padding: 4px 8px;
border: 1px solid var(--line);
color: var(--accent);
font-variant-numeric: tabular-nums;
letter-spacing: 0.08em;
}
.offer {
margin: 4px 4px 10px;
padding: 10px;
border: 1px solid #c9a96e;
border-radius: 8px;
}
.offer p {
margin: 0 0 8px;
}
.buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.buttons button {
padding: 5px 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel);
color: inherit;
font: inherit;
cursor: pointer;
}
.buttons button.primary {
border-color: #c9a96e;
}
footer { footer {
display: grid;
gap: 2px;
padding: 8px 14px 12px; padding: 8px 14px 12px;
border-top: 1px solid var(--line); border-top: 1px solid var(--line);
color: var(--muted); color: var(--muted);
font-size: 12px; font-size: 12px;
} }
.code-line {
font-variant-numeric: tabular-nums;
}
[hidden] {
display: none !important;
}
+11 -1
View File
@@ -12,9 +12,19 @@
<span id="site" class="site"></span> <span id="site" class="site"></span>
</header> </header>
<main> <main>
<section id="offer" class="offer" hidden>
<p id="offer-text"></p>
<div id="offer-buttons" class="buttons">
<button id="offer-dismiss" type="button">Not now</button>
<button id="offer-save" type="button" class="primary">Save in Custos</button>
</div>
</section>
<p id="note" class="note">Asking Custos…</p> <p id="note" class="note">Asking Custos…</p>
<ul id="logins" class="logins" aria-label="Logins for this site"></ul> <ul id="logins" class="logins" aria-label="Logins for this site"></ul>
</main> </main>
<footer>Only logins saved for this site are offered here.</footer> <footer>
<span>Only logins saved for this site are offered here.</span>
<span id="code" class="code-line"></span>
</footer>
</body> </body>
</html> </html>
+72 -24
View File
@@ -1,50 +1,98 @@
// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form // The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form
// (the top frame's content script asks for the secrets itself, so they go only where they belong). // (the top frame's content script asks for the secrets itself, so they go only where they belong). A login with
// 2FA can show its current code here. A login the page just sent can be saved in Custos. The footer shows this
// connection's match code, the one Custos shows on its card.
const api = globalThis.browser ?? globalThis.chrome;
const SENTENCES = { const SENTENCES = {
not_connected: 'Connect this browser in Custos first: Settings → Browser.', not_connected: 'Connect this browser in Custos first: Settings → Browser.',
not_running: 'Custos is not running. Start it, then try again.', not_running: 'Custos is not running. Start it, then try again.',
not_custos: 'Something other than Custos answered. Nothing was sent.', not_custos: 'Something other than Custos answered. Nothing was sent.',
not_allowed: 'This copy of the extension is not the one Custos knows.',
locked: 'Custos is locked. Unlock it, then try again.', locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.', denied: 'Custos did not allow this browser to use your logins.',
refused: 'Not saved.',
not_found: 'That login is no longer in Custos.', not_found: 'That login is no longer in Custos.',
no_match: 'Custos fills only web pages (https, or this computer).', no_match: 'Custos fills only web pages (https, or this computer).',
no_totp: 'That login has no 2FA code in Custos.',
no_answer: 'Custos did not answer.', no_answer: 'Custos did not answer.',
gone: 'That offer has expired.',
}; };
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.'; const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const note = document.getElementById('note'); const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' }));
const list = document.getElementById('logins'); const $ = (id) => document.getElementById(id);
const el = (tag, props) => Object.assign(document.createElement(tag), props);
const note = $('note');
const list = $('logins');
function tell(text) {
note.hidden = false;
note.textContent = text;
}
/** The 2FA code, shown until it changes; then the next one is asked for. */
async function showCode(id, out) {
const r = await send({ kind: 'totp-tab', id });
if (!r?.ok) {
out.textContent = say(r?.error);
return;
}
out.textContent = `${r.totp.slice(0, 3)} ${r.totp.slice(3)}`;
out.title = `Changes in ${r.remaining} s`;
setTimeout(() => out.isConnected && showCode(id, out), Math.max(1, r.remaining) * 1000);
}
function offer(o) {
if (!o) return;
const box = $('offer');
box.hidden = false;
$('offer-text').textContent = `Save the login${o.username ? ` of ${o.username}` : ''} for ${o.host}?`;
$('offer-save').addEventListener('click', async () => {
$('offer-text').textContent = 'Answer in Custos…';
const r = await send({ kind: 'save-tab' });
$('offer-text').textContent = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error);
$('offer-buttons').hidden = true;
});
$('offer-dismiss').addEventListener('click', async () => {
await send({ kind: 'dismiss-tab' });
box.hidden = true;
});
}
async function show() { async function show() {
const r = await chrome.runtime.sendMessage({ kind: 'match-tab' }); const r = await send({ kind: 'match-tab' });
if (r?.origin) document.getElementById('site').textContent = new URL(r.origin).host; if (r?.origin) $('site').textContent = new URL(r.origin).host;
if (!r?.ok) { offer(r?.offer);
note.textContent = say(r?.error); if (!r?.ok) return tell(say(r?.error));
return; if (!r.logins.length) return tell('Custos has no login for this site.');
}
if (!r.logins.length) {
note.textContent = 'Custos has no login for this site.';
return;
}
note.hidden = true; note.hidden = true;
for (const l of r.logins) { for (const l of r.logins) {
const li = document.createElement('li'); const li = el('li', {});
const b = Object.assign(document.createElement('button'), { type: 'button' }); const b = el('button', { type: 'button', className: 'login' });
b.append( b.append(el('span', { className: 'title', textContent: l.title }), el('span', { className: 'user', textContent: l.username || '—' }));
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
);
b.addEventListener('click', async () => { b.addEventListener('click', async () => {
const done = await chrome.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 }).catch(() => null); const done = await Promise.resolve(api.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 })).catch(() => null);
if (done?.ok) window.close(); if (done?.ok) window.close();
else { else tell(done?.error ?? 'This page has no login form Custos can fill.');
note.hidden = false;
note.textContent = done?.error ?? 'This page has no login form Custos can fill.';
}
}); });
li.append(b); li.append(b);
if (l.totp) {
const code = el('button', { type: 'button', className: 'code', textContent: '2FA code' });
code.addEventListener('click', () => {
code.disabled = true;
code.textContent = '…';
void showCode(l.id, code);
});
li.append(code);
}
list.append(li); list.append(li);
} }
list.querySelector('button')?.focus(); list.querySelector('button')?.focus();
} }
async function connection() {
const r = await send({ kind: 'status' });
if (r?.ok && typeof r.code === 'string') $('code').textContent = `Connection ${r.code.slice(0, 3)} ${r.code.slice(3)}`;
}
void show(); void show();
void connection();
+141
View File
@@ -0,0 +1,141 @@
// Tests of the extension's background script against a fake browser (docs/BROWSER.md, "Tests"):
//
// node tools/extension-test.mjs
//
// The background is the extension's one gate to Custos: what it sends to the host must come from the browser's
// own view of the sender, never from the message; other extensions and odd frames get nothing; a login offered for
// saving never comes back out of it.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const code = fs.readFileSync(path.join(root, 'extension', 'background.js'), 'utf8');
const ID = 'custos-test-id';
/** A fresh background with a fake API. `host(req)` answers the native host's requests. */
function background(host) {
const sent = [];
let listener = null;
const port = {
onMessage: { addListener: (f) => (port.deliver = f) },
onDisconnect: { addListener: () => {} },
postMessage: (m) => {
sent.push(m);
queueMicrotask(() => port.deliver({ ...host(m), seq: m.seq }));
},
};
const tabs = [{ id: 1, url: 'https://github.com/login', active: true }];
const api = {
runtime: { id: ID, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } },
tabs: { query: async () => tabs, onRemoved: { addListener: () => {} } },
action: { setBadgeText: async () => {}, setBadgeBackgroundColor: async () => {} },
};
vm.runInNewContext(code, { chrome: api, URL, setTimeout, Promise, queueMicrotask, console });
const call = (msg, sender) =>
new Promise((resolve) => {
// Answers are made in the background's realm: compared as plain JSON.
const kept = listener(msg, { id: ID, ...sender }, (v) => resolve(JSON.parse(JSON.stringify(v))));
if (kept !== true) resolve('ignored');
});
return { call, sent, tabs };
}
const tab = (url) => ({ id: 1, url });
const top = (url) => ({ url, frameId: 0, tab: tab(url) });
const frame = (url, pageUrl) => ({ url, frameId: 7, tab: tab(pageUrl) });
const tests = [];
const test = (name, f) => tests.push([name, f]);
test('another extension, or a page, is not answered at all', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
for (const id of ['someone-else', undefined, '']) {
assert.equal(await b.call({ kind: 'match' }, { ...top('https://github.com/'), id }), 'ignored');
assert.equal(await b.call({ kind: 'fill', id: 'a' }, { ...top('https://github.com/'), id }), 'ignored');
}
assert.equal(b.sent.length, 0);
});
test('the origins come from the browser, never from the message', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match', origin: 'https://bank.cz', top: 'https://bank.cz' }, top('https://github.com/login?x=1'));
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_match', 'https://github.com', 'https://github.com']]);
});
test('a frame asks with its own origin and its page’s', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match' }, frame('https://evil.net/ad', 'https://github.com/'));
await b.call({ kind: 'fill', id: 'x' }, frame('https://github.com/login', 'https://evil.net/'));
assert.deepEqual(
b.sent.map((m) => [m.op, m.origin, m.top]),
[
['browser_match', 'https://evil.net', 'https://github.com'],
['browser_fill', 'https://github.com', 'https://evil.net'],
],
);
});
test('sandboxed, blank, script and file frames get nothing, and nothing is asked', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
const odd = [
{ ...frame('https://github.com/login', 'https://evil.net/'), origin: 'null' },
{ ...top('https://github.com/'), origin: 'https://evil.net' },
frame('about:blank', 'https://github.com/'),
top('javascript:alert(1)'),
top('file:///C:/x.html'),
top('data:text/html,<input type=password>'),
{ url: 'https://github.com/', frameId: 3 },
];
for (const s of odd) {
assert.deepEqual(await b.call({ kind: 'match' }, s), { ok: false, error: 'no_match' }, JSON.stringify(s));
assert.deepEqual(await b.call({ kind: 'fill', id: 'a' }, s), { ok: false, error: 'no_match' });
}
assert.equal(b.sent.length, 0);
});
test('a locked Custos answers nothing but locked', async () => {
const b = background(() => ({ ok: false, error: 'locked' }));
const r = await b.call({ kind: 'fill', id: 'a' }, top('https://github.com/'));
assert.deepEqual(r, { ok: false, error: 'locked', seq: 1 });
});
test('a login offered for saving never comes back out, and goes only to Custos', async () => {
const b = background((m) => (m.op === 'browser_save' ? { ok: true, saved: 'new' } : { ok: true, code: '123456' }));
const at = top('https://github.com/login');
const offered = await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at);
assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark' } });
// Another page of the site in the same tab sees the offer, without the password; a frame or another site does not.
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark' } });
assert.deepEqual(await b.call({ kind: 'pending-save' }, frame('https://github.com/x', 'https://github.com/')), { ok: true, offer: null });
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://evil.net/')), { ok: true, offer: null });
const popup = await b.call({ kind: 'match-tab' }, { url: `chrome-extension://${ID}/popup.html` });
assert.ok(!JSON.stringify(popup).includes('hunter2'), 'the popup never sees the password');
// A frame cannot save; the top page can, once.
assert.deepEqual(await b.call({ kind: 'save' }, frame('https://github.com/x', 'https://github.com/')), { ok: false, error: 'bad_request' });
const saved = await b.call({ kind: 'save' }, top('https://github.com/home'));
assert.equal(saved.saved, 'new');
const req = b.sent.find((m) => m.op === 'browser_save');
assert.deepEqual([req.origin, req.top, req.username, req.password], ['https://github.com', 'https://github.com', 'mark', 'hunter2-secret']);
assert.deepEqual(await b.call({ kind: 'save' }, top('https://github.com/home')), { ok: false, error: 'gone' });
});
test('an offer needs a password, from a web page', async () => {
const b = background(() => ({ ok: true }));
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: '' }, top('https://github.com/'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'p' }, top('about:blank'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'x'.repeat(4097) }, top('https://a.cz/'))).ok, false);
});
let failed = 0;
for (const [name, f] of tests) {
try {
await f();
console.log(`ok ${name}`);
} catch (e) {
failed++;
console.log(`FAIL ${name}\n${e.stack}`);
}
}
console.log(`${tests.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
+87
View File
@@ -0,0 +1,87 @@
// Builds the browser extension for each browser from the one source in extension/ (docs/BROWSER.md):
//
// node tools/extension.mjs [--out <dir>] [--zip]
//
// writes <out>/firefox/ and <out>/chromium/ (default out: target/extension), each with its manifest.json (the
// browser's manifest.<browser>.json, with the workspace version) and the shared scripts and popup. With --zip
// also custos-<browser>-<version>.zip next to them, reproducible (fixed order and times): the Firefox one is what
// AMO signs, the Chromium one what the Edge and Chrome stores take.
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const arg = (name) => {
const i = process.argv.indexOf(name);
return i > 0 ? process.argv[i + 1] : null;
};
const out = path.resolve(arg('--out') ?? path.join(root, 'target', 'extension'));
const zip = process.argv.includes('--zip');
const cargo = fs.readFileSync(path.join(root, 'Cargo.toml'), 'utf8');
const version = /\[workspace\.package\][^[]*?version = "([^"]+)"/s.exec(cargo)?.[1];
if (!version) throw new Error('no workspace version in Cargo.toml');
const SHARED = ['background.js', 'content.js', 'popup.html', 'popup.js', 'popup.css'];
const BROWSERS = ['firefox', 'chromium'];
/** A zip of `files` ([name, bytes]), deflated, with a fixed time: the same input gives the same bytes. */
function zipOf(files) {
const parts = [];
const central = [];
let offset = 0;
const time = 0, date = (2026 - 1980) << 9 | 1 << 5 | 1; // 2026-01-01 00:00
for (const [name, data] of files) {
const n = Buffer.from(name, 'utf8');
const packed = zlib.deflateRawSync(data, { level: 9 });
const crc = zlib.crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 names
local.writeUInt16LE(8, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(n.length, 26);
parts.push(local, n, packed);
const c = Buffer.alloc(46);
c.writeUInt32LE(0x02014b50, 0);
c.writeUInt16LE(20, 4);
c.writeUInt16LE(20, 6);
c.writeUInt16LE(0x0800, 8);
c.writeUInt16LE(8, 10);
c.writeUInt16LE(time, 12);
c.writeUInt16LE(date, 14);
c.writeUInt32LE(crc, 16);
c.writeUInt32LE(packed.length, 20);
c.writeUInt32LE(data.length, 24);
c.writeUInt16LE(n.length, 28);
c.writeUInt32LE(offset, 42);
central.push(c, n);
offset += 30 + n.length + packed.length;
}
const dir = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(dir.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, dir, end]);
}
for (const browser of BROWSERS) {
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'extension', `manifest.${browser}.json`), 'utf8'));
const withVersion = { manifest_version: manifest.manifest_version, name: manifest.name, version, ...manifest };
const files = [['manifest.json', Buffer.from(JSON.stringify(withVersion, null, 2) + '\n')]];
for (const f of SHARED) files.push([f, fs.readFileSync(path.join(root, 'extension', f))]);
const dir = path.join(out, browser);
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(dir, { recursive: true });
for (const [name, data] of files) fs.writeFileSync(path.join(dir, name), data);
if (zip) fs.writeFileSync(path.join(out, `custos-${browser}-${version}.zip`), zipOf(files));
console.log(`${browser}: ${dir}${zip ? ` (+ custos-${browser}-${version}.zip)` : ''}`);
}