commit 3693732aac7e3199f93c361931013369f148a92b Author: Anish Lakhwara Date: Mon Sep 19 08:13:50 2022 +1000 holy moly we're almost there diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..b8d9a688 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,114 @@ +# Changelog + +## [v0.10.0](https://github.com/divnix/devos/tree/v0.10.0) (2021-05-24) + +**Implemented enhancements:** + +- Providing an interface to nixpkgs.config [\#237](https://github.com/divnix/devos/issues/237) +- Making the user available in profiles [\#230](https://github.com/divnix/devos/issues/230) +- copy evaluation store paths to iso [\#195](https://github.com/divnix/devos/issues/195) +- Extract custom system builds from devosSystem out of lib [\#170](https://github.com/divnix/devos/issues/170) +- Allow setting of channel host-wide [\#117](https://github.com/divnix/devos/issues/117) +- alacritty: CSIu support [\#51](https://github.com/divnix/devos/issues/51) + +**Fixed bugs:** + +- Cachix timeouts + how to disable nrdxp cachix \(if needed\) [\#294](https://github.com/divnix/devos/issues/294) +- default.nix flake-compat is broken [\#285](https://github.com/divnix/devos/issues/285) +- All suites return "attribute missing" [\#282](https://github.com/divnix/devos/issues/282) +- nix is built two times [\#203](https://github.com/divnix/devos/issues/203) +- fix lib docs [\#166](https://github.com/divnix/devos/issues/166) + +**Closed issues:** + +- eliminate userFlakeNixOS [\#257](https://github.com/divnix/devos/issues/257) +- devos-as-library [\#214](https://github.com/divnix/devos/issues/214) + +**Merged pull requests:** + +- Update evalArgs to match the new planned API [\#239](https://github.com/divnix/devos/pull/239) + +## [v0.9.0](https://github.com/divnix/devos/tree/v0.9.0) (2021-04-19) + +**Implemented enhancements:** + +- pin inputs into iso live registry [\#190](https://github.com/divnix/devos/issues/190) +- Pass 'self' to lib [\#169](https://github.com/divnix/devos/issues/169) +- doc: quickstart "ISO. What next?" [\#167](https://github.com/divnix/devos/issues/167) +- Integrate Android AOSP putting mobile under control [\#149](https://github.com/divnix/devos/issues/149) +- Inoculate host identity on first use [\#132](https://github.com/divnix/devos/issues/132) +- kubenix support [\#130](https://github.com/divnix/devos/issues/130) +- Improve Home Manager support: profiles/suites, modules, extern, flake outputs [\#119](https://github.com/divnix/devos/issues/119) +- Local CA \(between hosts\) [\#104](https://github.com/divnix/devos/issues/104) +- Q5: git annex for machine state [\#68](https://github.com/divnix/devos/issues/68) +- name space ./pkgs overlays [\#60](https://github.com/divnix/devos/issues/60) +- remap global keys easily [\#57](https://github.com/divnix/devos/issues/57) +- make pass state part of this repo's structure [\#56](https://github.com/divnix/devos/issues/56) +- Incorporate ./shells [\#38](https://github.com/divnix/devos/issues/38) +- Encrypt with \(r\)age [\#37](https://github.com/divnix/devos/issues/37) + +**Fixed bugs:** + +- `pathsToImportedAttrs` does not accept directories [\#221](https://github.com/divnix/devos/issues/221) +- Cachix caches aren't added to the configuration [\#208](https://github.com/divnix/devos/issues/208) +- Issues with current changelog workflow [\#205](https://github.com/divnix/devos/issues/205) +- iso: systemd service startup [\#194](https://github.com/divnix/devos/issues/194) +- Help adding easy-hls-nix to devos [\#174](https://github.com/divnix/devos/issues/174) +- `flk update` fails because of obsolete flag [\#159](https://github.com/divnix/devos/issues/159) +- Expected that not all packages are exported? [\#151](https://github.com/divnix/devos/issues/151) +- Segmentation fault when generating iso [\#150](https://github.com/divnix/devos/issues/150) + +**Documentation:** + +- doc: split iso [\#193](https://github.com/divnix/devos/issues/193) +- lib: can depend on pkgs \(a la nixpkgs\#pkgs/pkgs-lib\) [\#147](https://github.com/divnix/devos/pull/147) + +**Closed issues:** + +- FRRouting router implementation [\#154](https://github.com/divnix/devos/issues/154) +- ARM aarch64 Support [\#72](https://github.com/divnix/devos/issues/72) + +## [v0.8.0](https://github.com/divnix/devos/tree/v0.8.0) (2021-03-02) + +**Implemented enhancements:** + +- semi automatic update for /pkgs [\#118](https://github.com/divnix/devos/issues/118) +- Home-manager external modules from flakes [\#106](https://github.com/divnix/devos/issues/106) + +**Fixed bugs:** + +- My emacsGcc overlay is not working [\#146](https://github.com/divnix/devos/issues/146) +- local flake registry freezes branches [\#142](https://github.com/divnix/devos/issues/142) +- nixos-option no longer works after collect garbage [\#138](https://github.com/divnix/devos/issues/138) +- Profiles imports are brittle, causing failure if imported twice [\#136](https://github.com/divnix/devos/issues/136) + +## [0.7.0](https://github.com/divnix/devos/tree/0.7.0) (2021-02-20) + +**Implemented enhancements:** + +- add zoxide [\#53](https://github.com/divnix/devos/issues/53) +- Multiarch support? [\#17](https://github.com/divnix/devos/issues/17) +- initial multiArch support [\#18](https://github.com/divnix/devos/pull/18) + +**Fixed bugs:** + +- Missing shebang from flk.sh [\#131](https://github.com/divnix/devos/issues/131) +- Rename Meta Issue [\#128](https://github.com/divnix/devos/issues/128) +- specialisations break the `system` argument [\#46](https://github.com/divnix/devos/issues/46) +- Revert "Add extraArgs to lib.nixosSystem call to add system args." [\#47](https://github.com/divnix/devos/pull/47) + +**Documentation:** + +- update home-manager urls [\#62](https://github.com/divnix/devos/pull/62) + +**Closed issues:** + +- add github action for cachix build ci [\#59](https://github.com/divnix/devos/issues/59) + +## [12052020](https://github.com/divnix/devos/tree/12052020) (2020-12-06) + +## [07092020](https://github.com/divnix/devos/tree/07092020) (2020-07-09) + + + +\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..c9b44cb8 --- /dev/null +++ b/COPYING @@ -0,0 +1,18 @@ +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..e5edc638 --- /dev/null +++ b/README.md @@ -0,0 +1,93 @@ +[![NixOS](https://img.shields.io/badge/NixOS-unstable-blue.svg?style=flat&logo=NixOS&logoColor=white)](https://nixos.org) +[![MIT License](https://img.shields.io/github/license/divnix/devos)][mit] + +> #### ⚠ Advisory ⚠ +> Do you remember how you got here? Where were you going? What were you leaving behind? +> Are you sure you want to go down this rabbit hole, Alice? + +## Getting Started +This is my personal deployment hub. I configure all my personal servers from this repo. Good luck if you're looking to graft this. +You'll probably want to run some `install.sh` that will configure the base NixOS system. Some of them aren't in a good state. +From there you can either install the host you want with `sudo nixos-rebuild switch --flake .#` or enter the cockpit with `nix develop` and deploy servers remotely through `deploy` + + +## Personal dotfiles + + +

+ + + +

+ +------ + +| | | +|----------------|----------------------------------------------------------| +| **Shell:** | bash / elvish | +| **DM:** | lightdm + lightdm-mini-greeter | +| **WM:** | bspwm + polybar | +| **Editor:** | nvim | +| **Terminal:** | kitty | +| **Launcher:** | rofi | +| **Browser:** | firefox | +| **GTK Theme:** | [Ant Dracula](https://github.com/EliverLara/Ant-Dracula) | + +----- + + +### Status: Beta +The volcanic rock still shifts below this structure. It has not solidified and cannot yet be considered `home` +You should not expect landmarks here. +Learn to adopt Chaos. + +## Shoulders +Summoning is powerful magic, and cannot be created in isolation. It stands on the [shoulders of the +following giants][giants]: + +### :onion: — like the layers of an onion +- [`divnix/digga`][digga] +- [`gytis-ivaskevicius/flake-utils-plus`][fup] +- [`numtide/flake-utils`][fu] +- [`numtide/devshell`][devshell] +- [`serokell/deploy-rs`][deploy] +- [`berberman/nvfetcher`][nvfetcher] +- [`NixOS/nixpkgs`][nixpkgs] +- Agenix +- direnv + +:heart: + +### But Why? +The future is more uncertain than ever. Make dependable what you can, in whatever way you know how. +Stop doing it by yourself, unless we learn to work with one another will we be able to grow long term solutions. + +Managing servers by hand sucks, k8s doesn't allow me to transitively deploy all my configuration to multiple personal machines, and ansible wasn't good enough. + +You probably don't want to use nixOS, I'm a masocist + +### Grafts +https://github.com/hlissner/dotfiles + +# License +DevOS is licensed under the [MIT License][mit]. + +[community]: https://github.com/divnix/devos/tree/community +[core]: https://github.com/divnix/devos +[deploy]: https://github.com/serokell/deploy-rs +[devshell]: https://github.com/numtide/devshell +[digga]: https://github.com/divnix/digga +[dotfiles]: https://github.com/hlissner/dotfiles +[flake-doc]: https://github.com/NixOS/nix/blob/master/src/nix/flake.md +[flakes]: https://nixos.wiki/wiki/Flakes +[fu]: https://github.com/numtide/flake-utils +[fup]: https://github.com/gytis-ivaskevicius/flake-utils-plus +[giants]: https://en.wikipedia.org/wiki/Standing_on_the_shoulders_of_giants +[home-manager]: https://nix-community.github.io/home-manager +[mit]: https://mit-license.org +[mk-flake]: https://github.com/divnix/digga/tree/master/src/mkFlake +[nix]: https://nixos.org/manual/nix/stable +[nixos]: https://nixos.org/manual/nixos/stable +[nixpkgs]: https://github.com/NixOS/nixpkgs +[nvfetcher]: https://github.com/berberman/nvfetcher + diff --git a/bors.toml b/bors.toml new file mode 100644 index 00000000..6703d416 --- /dev/null +++ b/bors.toml @@ -0,0 +1,5 @@ +status = [ "check" ] + +required_approvals = 1 + +up_to_date_approvals = true diff --git a/default.nix b/default.nix new file mode 100644 index 00000000..0e6bdee2 --- /dev/null +++ b/default.nix @@ -0,0 +1,31 @@ +let + inherit (default.inputs.nixos) lib; + + default = (import ./lib/compat).defaultNix; + + ciSystems = [ + "aarch64-linux" + "i686-linux" + "x86_64-linux" + ]; + + filterSystems = lib.filterAttrs + (system: _: lib.elem system ciSystems); + + recurseIntoAttrsRecursive = lib.mapAttrs (_: v: + if lib.isAttrs v + then recurseIntoAttrsRecursive (lib.recurseIntoAttrs v) + else v + ); + + systemOutputs = lib.filterAttrs + (name: set: lib.isAttrs set + && lib.any + (system: set ? ${system} && name != "legacyPackages") + ciSystems + ) + default.outputs; + + ciDrvs = lib.mapAttrs (_: system: filterSystems system) systemOutputs; +in +(recurseIntoAttrsRecursive ciDrvs) // { shell = import ./shell.nix; } diff --git a/doc/.gitignore b/doc/.gitignore new file mode 100644 index 00000000..7585238e --- /dev/null +++ b/doc/.gitignore @@ -0,0 +1 @@ +book diff --git a/doc/CONTRIBUTING.md b/doc/CONTRIBUTING.md new file mode 100644 index 00000000..8574daea --- /dev/null +++ b/doc/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Pull Requests + +## TL;DR; +- **Target Branch**: `main` +- **Merge Policy**: [`bors`][bors] is alwyas right (→ `bors try`) +- **Docs**: every changeset is expected to contain doc updates +- **Commit Msg**: be a poet! Comprehensive and explanatory commit messages + should cover the motivation and use case in an easily understandable manner + even when read after a few months. +- **Test Driven Development**: please default to test driven development where possible. + +### Within the Devshell (`nix develop`) +- **Hooks**: please `git commit` within the devshell +- **Fail Early**: please run from within the devshell on your local machine: + - `nix flake check` + +[bors]: https://bors.tech + diff --git a/doc/SUMMARY.md b/doc/SUMMARY.md new file mode 100644 index 00000000..1d7bafe9 --- /dev/null +++ b/doc/SUMMARY.md @@ -0,0 +1,28 @@ +# Summary + +- [Introduction](../README.md) +- [Quick Start](./start/index.md) + - [ISO](./start/iso.md) + - [Bootstrapping](./start/bootstrapping.md) + - [From NixOS](./start/from-nixos.md) +- [Key Concepts](./concepts/index.md) + - [Hosts](./concepts/hosts.md) + - [Overrides](./concepts/overrides.md) + - [Profiles](./concepts/profiles.md) + - [Suites](./concepts/suites.md) + - [Users](./concepts/users.md) +- [Outputs](./outputs/index.md) + - [Modules](./outputs/modules.md) + - [Overlays](./outputs/overlays.md) + - [Packages](./outputs/pkgs.md) +- [Concerns]() + - [Secrets](./secrets.md) + - [Tests](./tests.md) +- [Helper Script – `bud`](./bud/index.md) + - [get](./bud/get.md) +- [Integrations](./integrations/index.md) + - [Cachix](./integrations/cachix.md) + - [Deploy RS](./integrations/deploy.md) + - [NvFetcher](./integrations/nvfetcher.md) + - [Hercules CI](./integrations/hercules.md) +- [Contributing](./CONTRIBUTING.md) diff --git a/doc/book.toml b/doc/book.toml new file mode 100644 index 00000000..373d26fd --- /dev/null +++ b/doc/book.toml @@ -0,0 +1,6 @@ +[book] +authors = ["Timothy DeHerrera"] +language = "en" +multilingual = false +src = "." +title = "devos docs" diff --git a/doc/bud/get.md b/doc/bud/get.md new file mode 100644 index 00000000..12263df0 --- /dev/null +++ b/doc/bud/get.md @@ -0,0 +1,10 @@ +# get +The `get` subcommand is useful for getting a bare copy of devos without the +git history. + +## Usage +```sh +bud get DEST-DIR +``` + +If DEST-DIR is ommitted, it defaults to _./devos_. diff --git a/doc/bud/index.md b/doc/bud/index.md new file mode 100644 index 00000000..7b985792 --- /dev/null +++ b/doc/bud/index.md @@ -0,0 +1,24 @@ +# [`bud`][bud] command +The template incudes a convenient script for managing your system called [`bud`][bud]. + +It is a portable and highly composable system control tool that work anywhere on your host +or in the flake's devshell. + +Although it comes with some predefined standard helpers, +it is very extensible and you are encouraged to write your own script snippets +to ease your workflows. An example is the bud module for a `get` command that +comes included with `devos`. + +While writing scripts you can convenientely access smart environment variables +that can tell the current architecture, user or host name, among others, regardless +wether you invoke `bud` within the devshell or as the system-wide installed `bud`. + +For details, please review the [bud repo][bud]. + +## Usage +```sh +bud help +``` + + +[bud]: https://github.com/divnix/bud diff --git a/doc/concepts/hosts.md b/doc/concepts/hosts.md new file mode 100644 index 00000000..1c3c3fa0 --- /dev/null +++ b/doc/concepts/hosts.md @@ -0,0 +1,62 @@ +# Hosts + +Nix flakes contain an output called `nixosConfigurations` declaring an +attribute set of valid NixOS systems. To simplify the management and creation +of these hosts, devos automatically imports every _.nix_ file inside this +directory to the mentioned attribute set, applying the projects defaults to +each. The only hard requirement is that the file contain a valid NixOS module. + +As an example, a file `hosts/system.nix` or `hosts/system/default.nix` will +be available via the flake output `nixosConfigurations.system`. You can have +as many hosts as you want and all of them will be automatically imported based +on their name. + +For each host, the configuration automatically sets the `networking.hostName` +attribute to the folder name or name of the file minus the _.nix_ extension. This +is for convenience, since `nixos-rebuild` automatically searches for a configuration +matching the current systems hostname if one is not specified explicitly. + +You can set channels, systems, and add extra modules to each host by editing the +`nixos.hosts` argument in flake.nix. This is the perfect place to import +host specific modules from external sources, such as the +[nixos-hardware][nixos-hardware] repository. + +It is recommended that the host modules only contain configuration information +specific to a particular piece of hardware. Anything reusable across machines +is best saved for [profile modules](./profiles.md). + +This is a good place to import sets of profiles, called [suites](./suites.md), +that you intend to use on your machine. + + +## Example + +flake.nix: +```nix +{ + nixos = { + imports = [ (devos.lib.importHosts ./hosts) ]; + hosts = { + librem = { + channelName = "latest"; + modules = [ nixos-hardware.nixosModules.purism-librem-13v3 ]; + }; + }; + }; +} +``` + +hosts/librem.nix: +```nix +{ suites, ... }: +{ + imports = suites.laptop; + + boot.loader.systemd-boot.enable = true; + boot.loader.efi.canTouchEfiVariables = true; + + fileSystems."/" = { device = "/dev/disk/by-label/nixos"; }; +} +``` + +[nixos-hardware]: https://github.com/NixOS/nixos-hardware diff --git a/doc/concepts/index.md b/doc/concepts/index.md new file mode 100644 index 00000000..618292cb --- /dev/null +++ b/doc/concepts/index.md @@ -0,0 +1,10 @@ +# Key Concepts + +Key concepts are derived from [digga][digga]. Please refer to its +[docs][digga-docs] for more details. + +This section is dedicated to helping you develop a more hands on +understanding of them them. + +[digga-docs]: https://digga.divnix.com +[digga]: https://github.com/divnix/digga diff --git a/doc/concepts/overrides.md b/doc/concepts/overrides.md new file mode 100644 index 00000000..610fde04 --- /dev/null +++ b/doc/concepts/overrides.md @@ -0,0 +1,42 @@ +# Overrides +Each NixOS host follows one channel. But many times it is useful to get packages +or modules from different channels. + +## Packages +You can make use of `overlays/overrides.nix` to override specific packages in the +default channel to be pulled from other channels. That file is simply an example +of how any overlay can get `channels` as their first argument. + +You can add overlays to any channel to override packages from other channels. + +Pulling the manix package from the `latest` channel: +```nix +channels: final: prev: { + __dontExport = true; + inherit (pkgs.latest) manix; +} +``` + +It is recommended to set the `__dontExport` property for override specific +overlays. `overlays/overrides.nix` is the best place to consolidate all package +overrides and the property is already set for you. + +## Modules + +You can also pull modules from other channels. All modules have access to the +`modulesPath` for each channel as `ModulesPath`. And you can use +`disabledModules` to remove modules from the current channel. + +To pull zsh module from the `latest` channel this code can be placed in any module, whether its your host file, a profile, or a module in ./modules etc: +```nix +{ latestModulesPath }: +{ + imports = [ "${latestModulesPath}/programs/zsh/zsh.nix" ]; + disabledModules = [ "programs/zsh/zsh.nix" ]; +} +``` + +> ##### _Note:_ +> Sometimes a modules name will change from one branch to another. + +[nixpkgs-modules]: https://github.com/NixOS/nixpkgs/tree/master/nixos/modules diff --git a/doc/concepts/profiles.md b/doc/concepts/profiles.md new file mode 100644 index 00000000..a5eda3e2 --- /dev/null +++ b/doc/concepts/profiles.md @@ -0,0 +1,67 @@ +# Profiles + +Profiles are a convenient shorthand for the [_definition_][definition] of +[options][options] in contrast to their [_declaration_][declaration]. They're +built into the NixOS module system for a reason: to elegantly provide a clear +separation of concerns. + +## Creation +Profiles are created with the `rakeLeaves` function which recursively collects +`.nix` files from within a folder. The recursion stops at folders with a `default.nix` +in them. You end up with an attribute set with leaves(paths to profiles) or +nodes(attrsets leading to more nodes or leaves). + +A profile is used for quick modularization of [interelated bits](./profiles.md#subprofiles). + +> ##### _Notes:_ +> * For _declaring_ module options, there's the [modules](../outputs/modules.md) directory. +> * This directory takes inspiration from +> [upstream](https://github.com/NixOS/nixpkgs/tree/master/nixos/modules/profiles) +> . + +### Nested profiles +Profiles can be nested in attribute sets due to the recursive nature of `rakeLeaves`. +This can be useful to have a set of profiles created for a specific purpose. It is +sometimes useful to have a `common` profile that has high level concerns related +to all its sister profiles. + +### Example + +profiles/develop/common.nix: +```nix +{ + imports = [ ./zsh ]; + # some generic development concerns ... +} +``` + +profiles/develop/zsh.nix: +```nix +{ ... }: +{ + programs.zsh.enable = true; + # zsh specific options ... +} +``` + +The examples above will end up with a profiles set like this: +```nix +{ + develop = { + common = ./profiles/develop/common.nix; + zsh = ./profiles/develop/zsh.nix; + }; +} +``` + +## Conclusion +Profiles are the most important concept in DevOS. They allow us to keep our +Nix expressions self contained and modular. This way we can maximize reuse +across hosts while minimizing boilerplate. Remember, anything machine +specific belongs in your [host](hosts.md) files instead. + +[definition]: https://nixos.org/manual/nixos/stable/index.html#sec-option-definitions +[declaration]: https://nixos.org/manual/nixos/stable/index.html#sec-option-declarations +[options]: https://nixos.org/manual/nixos/stable/index.html#sec-writing-modules +[spec]: https://github.com/divnix/devos/tree/core/lib/devos/mkProfileAttrs.nix +[config]: https://nixos.wiki/wiki/Module#structure diff --git a/doc/concepts/suites.md b/doc/concepts/suites.md new file mode 100644 index 00000000..42a3db82 --- /dev/null +++ b/doc/concepts/suites.md @@ -0,0 +1,25 @@ +# Suites +Suites provide a mechanism for users to easily combine and name collecitons of +profiles. + +`suites` are defined in the `importables` argument in either the `home` or `nixos` +namespace. They are a special case of an `importable` which get passed as a special +argument (one that can be use in an `imports` line) to your hosts. All lists defined +in `suites` are flattened and type-checked as paths. + +## Definition +```nix +rec { + workstation = [ profiles.develop profiles.graphical users.nixos ]; + mobileWS = workstation ++ [ profiles.laptop ]; +} +``` + +## Usage +`hosts/my-laptop.nix`: +```nix +{ suites, ... }: +{ + imports = suites.mobileWS; +} +``` diff --git a/doc/concepts/users.md b/doc/concepts/users.md new file mode 100644 index 00000000..12bf5622 --- /dev/null +++ b/doc/concepts/users.md @@ -0,0 +1,77 @@ +> ##### _Note:_ +> This section and its semantics need a conceptiual rework. +> Since recently [portable home configurations][portableuser] +> that are not bound to any specific host are a thing. + +# Users + +Users are a special case of [profiles](profiles.md) that define system +users and [home-manager][home-manager] configurations. For your convenience, +home manager is wired in by default so all you have to worry about is declaring +your users. For a fully fleshed out example, check out the developers personal +[branch](https://github.com/divnix/devos/tree/nrd/users/nrd/default.nix). + +## Basic Usage +`users/myuser/default.nix`: +```nix +{ ... }: +{ + users.users.myuser = { + isNormalUser = true; + }; + + home-manager.users.myuser = { + programs.mpv.enable = true; + }; +} + +``` + +## Home Manager +Home Manager support follows the same principles as regular nixos configurations, +it even gets its own namespace in your `flake.nix` as `home`. + +All modules defined in [user modules][modules-list] will be imported to +Home Manager. +User profiles can be collected in a similar fashion as system ones into a `suites` +argument that gets passed to your home-manager users. + +### Example +```nix +{ + home-manager.users.nixos = { suites, ... }: { + imports = suites.base; + }; +} +``` + + +## External Usage +You can easily use the defined home-manager configurations outside of NixOS +using the `homeConfigurations` flake output. The [flk](../flk/index.md) helper +script makes this even easier. + +This is great for keeping your environment consistent across Unix systems, +including OSX. + +### From within the projects devshell: +```sh +# builds the nixos user defined in the NixOS host +flk home NixOS nixos + +# build and activate +flk home NixOS nixos switch +``` + +### Manually from outside the project: +```sh +# build +nix build "github:divnix/devos#homeConfigurations.nixos@NixOS.home.activationPackage" + +# activate +./result/activate && unlink result +``` + +[home-manager]: https://nix-community.github.io/home-manager +[modules-list]: https://github.com/divnix/devos/tree/core/users/modules/module-list.nix +[portableuser]: https://digga.divnix.com/api-reference-home.html#homeusers diff --git a/doc/integrations/cachix.md b/doc/integrations/cachix.md new file mode 100644 index 00000000..b0254594 --- /dev/null +++ b/doc/integrations/cachix.md @@ -0,0 +1,17 @@ +# Cachix +The system will automatically pull a cachix.nix at the root if one exists. +This is usually created automatically by a `sudo cachix use`. If you're more +inclined to keep the root clean, you can drop any generated files in the +`cachix` directory into the `profiles/cachix` directory without further +modification. + +For example, to add your own cache, assuming the template lives in /etc/nixos, +by simply running `sudo cachix use yourcache`. Then, optionally, move +`cachix/yourcache.nix` to `profiles/cachix/yourcache.nix` + +These caches are only added to the system after a `nixos-rebuild switch`, so it +is recommended to call `cachix use nrdxp` before the initial deployment, as it +will save a lot of build time. + +In the future, users will be able to skip this step once the ability to define +the nix.conf within the flake is fully fleshed out upstream. diff --git a/doc/integrations/deploy.md b/doc/integrations/deploy.md new file mode 100644 index 00000000..29032108 --- /dev/null +++ b/doc/integrations/deploy.md @@ -0,0 +1,49 @@ +# deploy-rs +[Deploy-rs][d-rs] is a tool for managing NixOS remote machines. It was +chosen for devos after the author experienced some frustrations with the +stateful nature of nixops' db. It was also designed from scratch to support +flake based deployments, and so is an excellent tool for the job. + +By default, all the [hosts](../concepts/hosts.md) are also available as deploy-rs nodes, +configured with the hostname set to `networking.hostName`; overridable via +the command line. + +## Usage + +Just add your ssh key to the host: +```nix +{ ... }: +{ + users.users.${sshUser}.openssh.authorizedKeys.keyFiles = [ + ../secrets/path/to/key.pub + ]; +} +``` + +And the private key to your user: +```nix +{ ... }: +{ + home-manager.users.${sshUser}.programs.ssh = { + enable = true; + + matchBlocks = { + ${host} = { + host = hostName; + identityFile = ../secrets/path/to/key; + extraOptions = { AddKeysToAgent = "yes"; }; + }; + }; + } +} +``` + +And run the deployment: +```sh +deploy "flk#hostName" --hostname host.example.com +``` + +> ##### _Note:_ +> Your user will need **passwordless** sudo access + +[d-rs]: https://github.com/serokell/deploy-rs diff --git a/doc/integrations/hercules.md b/doc/integrations/hercules.md new file mode 100644 index 00000000..aa0185e4 --- /dev/null +++ b/doc/integrations/hercules.md @@ -0,0 +1,36 @@ +# Hercules CI +If you start adding your own packages and configurations, you'll probably have +at least a few binary artifacts. With hercules we can build every package in +our configuration automatically, on every commit. Additionally, we can have it +upload all our build artifacts to a binary cache like [cachix][cachix]. + +This will work whether your copy is a fork, or a bare template, as long as your +repo is hosted on GitHub. + +## Setup +Just head over to [hercules-ci.com](https://hercules-ci.com) to make an account. + +Then follow the docs to set up an [agent][agent], if you want to deploy to a +binary cache (and of course you do), be sure _not_ to skip the +[binary-caches.json][cache]. + +## Ready to Use +The repo is already set up with the proper _default.nix_ file, building all +declared packages, checks, profiles and shells. So you can see if something +breaks, and never build the same package twice! + +If you want to get fancy, you could even have hercules +[deploy your configuration](https://docs.hercules-ci.com/hercules-ci-effects/guide/deploy-a-nixos-machine/)! + +> ##### _Note:_ +> Hercules doesn't have access to anything encrypted in the +> [secrets folder](../../secrets), so none of your secrets will accidentally get +> pushed to a cache by mistake. +> +> You could pull all your secrets via your user, and then exclude it from +> [allUsers](https://github.com/nrdxp/devos/blob/nrd/suites/default.nix#L17) +> to keep checks passing. + +[agent]: https://docs.hercules-ci.com/hercules-ci/getting-started/#github +[cache]: https://docs.hercules-ci.com/hercules-ci/getting-started/deploy/nixos/#_3_configure_a_binary_cache +[cachix]: https://cachix.org diff --git a/doc/integrations/index.md b/doc/integrations/index.md new file mode 100644 index 00000000..5ea739ec --- /dev/null +++ b/doc/integrations/index.md @@ -0,0 +1,5 @@ +# Integrations +This section explores some of the optional tools included with devos to provide +a solution to common concerns such as ci and remote deployment. An effort is +made to choose tools that treat nix, and where possible flakes, as first class +citizens. diff --git a/doc/integrations/nvfetcher.md b/doc/integrations/nvfetcher.md new file mode 100644 index 00000000..4670657e --- /dev/null +++ b/doc/integrations/nvfetcher.md @@ -0,0 +1,43 @@ +# nvfetcher +[NvFetcher][nvf] is a workflow companion for updating nix sources. + +You can specify an origin source and an update configuration, and +nvfetcher can for example track updates to a specific branch and +automatically update your nix sources configuration on each run +to the tip of that branch. + +All package source declaration is done in [sources.toml][sources.toml]. + +From within the devshell of this repo, run `nvfetcher`, a wrapped +version of `nvfetcher` that knows where to find and place its files +and commit the results. + +## Usage + +Statically fetching (not tracking) a particular tag from a github repo: +```toml +[manix] +src.manual = "v0.6.3" +fetch.github = "mlvzk/manix" +``` + +Tracking the latest github _release_ from a github repo: +```toml +[manix] +src.github = "mlvzk/manix" # responsible for tracking +fetch.github = "mlvzk/manix" # responsible for fetching +``` + +Tracking the latest commit of a git repository and fetch from a git repo: +```toml +[manix] +src.git = "https://github.com/mlvzk/manix.git" # responsible for tracking +fetch.git = "https://github.com/mlvzk/manix.git" # responsible for fetching +``` + +> ##### _Note:_ +> Please refer to the [NvFetcher Readme][nvf-readme] for more options. + +[nvf]: https://github.com/berberman/nvfetcher +[nvf-readme]: https://github.com/berberman/nvfetcher#readme +[sources.toml]: https://github.com/divnix/devos/tree/core/pkgs/sources.toml diff --git a/doc/outputs/index.md b/doc/outputs/index.md new file mode 100644 index 00000000..36207188 --- /dev/null +++ b/doc/outputs/index.md @@ -0,0 +1,3 @@ +# Layout +Each of the following sections is a directory whose contents are output to the +outside world via the flake's outputs. Check each chapter for details. diff --git a/doc/outputs/modules.md b/doc/outputs/modules.md new file mode 100644 index 00000000..f698e9f6 --- /dev/null +++ b/doc/outputs/modules.md @@ -0,0 +1,79 @@ +# Modules +The modules directory is a replica of nixpkg's NixOS [modules][nixpkgs-modules] +, and follows the same semantics. This allows for trivial upstreaming into +nixpkgs proper once your module is sufficiently stable. + +All modules linked in _module-list.nix_ are automatically exported via +`nixosModules.`, and imported into all [hosts](../concepts/hosts.md). + + +> ##### _Note:_ +> This is reserved for declaring brand new module options. If you just want to +> declare a coherent configuration of already existing and related NixOS options +> , use [profiles](../concepts/profiles.md) instead. + +## Semantics +In case you've never written a module for nixpkgs before, here is a brief +outline of the process. + +### Declaration +modules/services/service-category/my-service.nix: +```nix +{ config, lib, ... }: +let + cfg = config.services.myService; +in +{ + options.services.myService = { + enable = lib.mkEnableOption "Description of my new service."; + + # additional options ... + }; + + config = lib.mkIf cfg.enable { + # implementation ... + }; +} +``` + +### Import +modules/module-list.nix: +```nix +[ + ./services/service-category/my-service.nix +] +``` + +## Usage + +### Internal +profiles/profile-category/my-profile.nix: +```nix +{ ... }: +{ + services.MyService.enable = true; +} +``` + +### External +flake.nix: +```nix +{ + # inputs omitted + + outputs = { self, devos, nixpkgs, ... }: { + nixosConfigurations.myConfig = nixpkgs.lib.nixosSystem { + system = "..."; + + modules = [ + devos.nixosModules.my-service + ({ ... }: { + services.MyService.enable = true; + }) + ]; + }; + }; +} +``` + +[nixpkgs-modules]: https://github.com/NixOS/nixpkgs/tree/master/nixos/modules diff --git a/doc/outputs/overlays.md b/doc/outputs/overlays.md new file mode 100644 index 00000000..f463d1a7 --- /dev/null +++ b/doc/outputs/overlays.md @@ -0,0 +1,25 @@ +# Overlays +Writing overlays is a common occurence when using a NixOS system. Therefore, +we want to keep the process as simple and straightforward as possible. + +Any _.nix_ files declared in this directory will be assumed to be a valid +overlay, and will be automatically imported into all [hosts](../concepts/hosts.md), and +exported via `overlays./` _as well as_ +`packages..` (for valid systems), so all you have to do is +write it. + +## Example +overlays/kakoune.nix: +```nix +final: prev: { + kakoune = prev.kakoune.override { + configure.plugins = with final.kakounePlugins; [ + (kak-fzf.override { fzf = final.skim; }) + kak-auto-pairs + kak-buffers + kak-powerline + kak-vertical-selection + ]; + }; +} +``` diff --git a/doc/outputs/pkgs.md b/doc/outputs/pkgs.md new file mode 100644 index 00000000..4de93a8d --- /dev/null +++ b/doc/outputs/pkgs.md @@ -0,0 +1,109 @@ +# Packages +Similar to [modules](./modules.md), the pkgs directory mirrors the upstream +[nixpkgs/pkgs][pkgs], and for the same reason; if you ever want to upstream +your package, it's as simple as dropping it into the nixpkgs/pkgs directory. + +The only minor difference is that, instead of adding the `callPackage` call to +`all-packages.nix`, you just add it the the _default.nix_ in this directory, +which is defined as a simple overlay. + +All the packages are exported via `packages..`, for all +the supported systems listed in the package's `meta.platforms` attribute. + +And, as usual, every package in the overlay is also available to any NixOS +[host](../concepts/hosts.md). + +Another convenient difference is that it is possible to use +[nvfetcher](https://github.com/berberman/nvfetcher) to keep packages up to +date. +This is best understood by the simple example below. + +## Example +It is possible to specify sources separately to keep them up to date semi +automatically. +The basic rules are specified in pkgs/sources.toml: +```toml +# nvfetcher.toml +[libinih] +src.github = "benhoyt/inih" +fetch.github = "benhoyt/inih" +``` +After changes to this file as well as to update the packages specified in there run +nvfetcher (for more details see [nvfetcher](https://github.com/berberman/nvfetcher)). + +The pkgs overlay is managed in +pkgs/default.nix: +```nix +final: prev: { + # keep sources first, this makes sources available to the pkgs + sources = prev.callPackage (import ./_sources/generated.nix) { }; + + # then, call packages with `final.callPackage` + libinih = prev.callPackage ./development/libraries/libinih { }; +} +``` + +Lastly the example package is in +pkgs/development/libraries/libinih/default.nix: +```nix +{ stdenv, meson, ninja, lib, sources, ... }: +stdenv.mkDerivation { + pname = "libinih"; + + # version will resolve to the latest available on gitub + inherit (sources.libinih) version src; + + buildInputs = [ meson ninja ]; + + # ... +} +``` + + +## Migration from flake based approach +Previous to nvfetcher it was possible to manage sources via a pkgs/flake.nix, the main changes from there are that sources where in the attribute "srcs" (now "sources") and the contents of the sources where slightly different. +In order to switch to the new system, rewrite pkgs/flake.nix to a pkgs/sources.toml file using the documentation of nvfetcher, +add the line that calls the sources at the beginning of pkgs/default.nix, and +accomodate the small changes in the packages as can be seen from the example. + +The example package looked like: + +pkgs/flake.nix: +```nix +{ + description = "Package sources"; + + inputs = { + libinih.url = "github:benhoyt/inih/r53"; + libinih.flake = false; + }; +} +``` + +pkgs/default.nix: +```nix +final: prev: { + # then, call packages with `final.callPackage` + libinih = prev.callPackage ./development/libraries/libinih { }; +} +``` + +pkgs/development/libraries/libinih/default.nix: +```nix +{ stdenv, meson, ninja, lib, srcs, ... }: +let inherit (srcs) libinih; in +stdenv.mkDerivation { + pname = "libinih"; + + # version will resolve to 53, as specified in the flake.nix file + inherit (libinih) version; + + src = libinih; + + buildInputs = [ meson ninja ]; + + # ... +} +``` + +[pkgs]: https://github.com/NixOS/nixpkgs/tree/master/pkgs diff --git a/doc/secrets.md b/doc/secrets.md new file mode 100644 index 00000000..6afe2f6a --- /dev/null +++ b/doc/secrets.md @@ -0,0 +1,110 @@ +# Secrets +Secrets are managed using [git-crypt][git-crypt] and [agenix][agenix] +so you can keep your flake in a public repository like GitHub without +exposing your password or other sensitive data. + +By default, everything in the secrets folder is automatically encrypted. Just +be sure to run `git-crypt init` before putting anything in here. + +## Agenix +Currently, there is [no mechanism][secrets-issue] in nix itself to deploy secrets +within the nix store because it is world-readable. + +Most NixOS modules have the ability to set options to files in the system, outside +the nix store, that contain sensitive information. You can use [agenix][agenix] +to easily setup those secret files declaratively. + +[agenix][agenix] encrypts secrets and stores them as .age files in your repository. +Age files are encrypted with multiple ssh public keys, so any host or user with a +matching ssh private key can read the data. The [age module][age module] will add those +encrypted files to the nix store and decrypt them on activation to `/run/secrets`. + +### Setup +All hosts must have openssh enabled, this is done by default in the core profile. + +You need to populate your `secrets/secrets.nix` with the proper ssh public keys. +Be extra careful to make sure you only add public keys, you should never share a +private key!! + +secrets/secrets.nix: +```nix +let + system = ""; + user = ""; + allKeys = [ system user ]; +in +``` + +On most systems, you can get your systems ssh public key from `/etc/ssh/ssh_host_ed25519_key.pub`. If +this file doesn't exist you likely need to enable openssh and rebuild your system. + +Your users ssh public key is probably stored in `~/.ssh/id_ed25519.pub` or +`~/.ssh/id_rsa.pub`. If you haven't generated a ssh key yet, be sure do so: +```sh +ssh-keygen -t ed25519 +``` + +> ##### _Note:_ +> The underlying tool used by agenix, rage, doesn't work well with password protected +> ssh keys. So if you have lots of secrets you might have to type in your password many +> times. + + +### Secrets +You will need the `agenix` command to create secrets. DevOS conveniently provides that +in the devShell, so just run `nix develop` whenever you want to edit secrets. Make sure +to always run `agenix` while in the `secrets/` folder, so it can pick up your `secrets.nix`. + +To create secrets, simply add lines to your `secrets/secrets.nix`: +``` +let + ... + allKeys = [ system user ]; +in +{ + "secret.age".publicKeys = allKeys; +} +``` +That would tell agenix to create a `secret.age` file that is encrypted with the `system` +and `user` ssh public key. + +Then go into the `secrets` folder and run: +```sh +agenix -e secret.age +``` +This will create the `secret.age`, if it doesn't already exist, and allow you to edit it. + +If you ever change the `publicKeys` entry of any secret make sure to rekey the secrets: +```sh +agenix --rekey +``` + +### Usage +Once you have your secret file encrypted and ready to use, you can utilize the [age module][age module] +to ensure that your secrets end up in `/run/secrets`. + +In any profile that uses a NixOS module that requires a secret you can enable a particular secret like so: + +```nix +{ self, ... }: +{ + age.secrets.mysecret.file = "${self}/secrets/mysecret.age"; +} +``` + + +Then you can just pass the path `/run/secrets/mysecret` to the module. + +You can make use of the many options provided by the age module to customize where and how +secrets get decrypted. You can learn about them by looking at the +[age module][age module]. + + +> ##### _Note:_ +> You can take a look at the [agenix repository][agenix] for more information +> about the tool. + +[git-crypt]: https://github.com/AGWA/git-crypt +[agenix]: https://github.com/ryantm/agenix +[age module]: https://github.com/ryantm/agenix/blob/master/modules/age.nix +[secrets-issue]: https://github.com/NixOS/nix/issues/8 diff --git a/doc/start/bootstrapping.md b/doc/start/bootstrapping.md new file mode 100644 index 00000000..f4c5190e --- /dev/null +++ b/doc/start/bootstrapping.md @@ -0,0 +1,102 @@ +# Bootstrapping + +This will help you boostrap a bare host with the help of the +[bespoke iso](./iso.md) live installer. + +_Note: nothing prevents you from remotely executing the boostrapping +process. See below._ + +Once your target host has booted into the live iso, you need to partion +and format your disk according to the [official manual][manual]. + +## Mount partitions + +Then properly mount the formatted partitions at `/mnt`, so that you can +install your system to those new partitions. + +Mount `nixos` partition to `/mnt` and — for UEFI — `boot` +partition to `/mnt/boot`: + +```console +$ mount /dev/disk/by-label/nixos /mnt +$ mkdir -p /mnt/boot && mount /dev/disk/by-label/boot /mnt/boot # UEFI only +$ swapon /dev/disk/by-label/swap +``` + +Add some extra space to the store. In the iso, it's running on a tmpfs +off your RAM: +```console +$ mkdir -p /mnt/tmpstore/{work,store} +$ mount -t overlay overlay -olowerdir=/nix/store,upperdir=/mnt/tmpstore/store,workdir=/mnt/tmpstore/work /nix/store +``` + +## Install + +Install off of a copy of devos from the time the iso was built: + +```console +$ cd /iso/devos +$ nixos-install --flake .#NixOS +``` + +## Notes of interest + +### Remote access to the live installer + +The iso live installer comes preconfigured with a network configuration +which announces it's hostname via [MulticastDNS][mDNS] as `hostname.local`, +that is `bootstrap.local` in the [iso example](./iso). + +In the rare case that [MulticastDNS][mDNS] is not availabe or turned off +in your network, there is a static link-local IPv6 address configured to +`fe80::47`(mnemonic from the letter's position in the english alphabet: +`n=14 i=9 x=24; 47 = n+i+x`). + +Provided that you have added your public key to the authorized keys of the +`root` user _(hint: [`deploy-rs`](../integrations/deploy.md) needs passwordless +sudo access)_: + +```nix +{ ... }: +{ + users.users.root.openssh.authorizedKeys.keyFiles = [ + ../secrets/path/to/key.pub + ]; +} +``` + +You can then ssh into the live installer through one of the +following options: + +```console +ssh root@bootstrap.local + +ssh root@fe80::47%eno1 # where eno1 is your network interface on which you are linked to the target +``` + +_Note: the [static link-local IPv6 address][staticLLA] and [MulticastDNS][mDNS] is only +configured on the live installer. If you wish to enable [MulticastDNS][mDNS] +for your environment, you ought to configure that in a regular [profile](../concepts/profiles.md)._ + +### EUI-64 LLA & Host Identity + +The iso's IPv6 Link Local Address (LLA) is configured with a static 64-bit Extended +Unique Identifiers (EUI-64) that is derived from the host interface's Message +Authentication Code (MAC) address. + +After a little while (a few seconds), you can remotely discover this unique and host +specific address over [NDP][NDP] for example with: + +```console +ip -6 neigh show # also shows fe80::47 +``` + +***This LLA is stable for the host, unless you need to swap that particular network card.*** +Under this reservation, though, you may use this EUI-64 to wire up a specific +(cryptographic) host identity. + + +[manual]: https://nixos.org/manual/nixos/stable/index.html#sec-installation-partitioning +[mDNS]: https://en.wikipedia.org/wiki/Multicast_DNS +[NDP]: https://en.wikipedia.org/wiki/Neighbor_Discovery_Protocol +[staticLLA]: https://tools.ietf.org/html/rfc7404 diff --git a/doc/start/from-nixos.md b/doc/start/from-nixos.md new file mode 100644 index 00000000..0e1d48cb --- /dev/null +++ b/doc/start/from-nixos.md @@ -0,0 +1,54 @@ +# From NixOS + +## Generate Configuration +Assuming you're happy with your existing partition layout, you can generate a +basic NixOS configuration for your system using: +```sh +flk up +``` + +This will make a new file `hosts/up-$(hostname).nix`, which you can edit to +your liking. + +You must then add a host to `nixos.hosts` in flake.nix: +```nix +{ + nixos.hosts = { + modules = hosts/NixOS.nix; + }; +} +``` + +Make sure your `i18n.defaultLocale` and `time.timeZone` are set properly for +your region. Keep in mind that `networking.hostName` will be automatically +set to the name of your host; + +Now might be a good time to read the docs on [suites](../concepts/suites.md) and +[profiles](../concepts/profiles.md) and add or create any that you need. + +> ##### _Note:_ +> While the `up` sub-command is provided as a convenience to quickly set up and +> install a "fresh" NixOS system on current hardware, committing these files is +> discouraged. +> +> They are placed in the git staging area automatically because they would be +> invisible to the flake otherwise, but it is best to move what you need from +> them directly into a host module of your own making, and commit that instead. +# Installation + +Once you're ready to deploy `hosts/my-host.nix`: +```sh +flk my-host switch +``` + + +This calls `nixos-rebuild` with sudo to build and install your configuration. + +> ##### _Notes:_ +> - Instead of `switch`, you can pass `build`, `test`, `boot`, etc just as with +> `nixos-rebuild`. +> +> - It is convenient to have the template living at `/etc/nixos` so you can +> simply `sudo nixos-rebuild switch` from anywhere on the system, but it is +> not required. + diff --git a/doc/start/index.md b/doc/start/index.md new file mode 100644 index 00000000..f3f1127f --- /dev/null +++ b/doc/start/index.md @@ -0,0 +1,41 @@ +# Quick Start +The only dependency is nix, so make sure you have it [installed][install-nix]. + +## Get the Template +Here is a snippet that will get you the template without the git history: +```sh +nix-shell -p cachix --run "cachix use nrdxp" + +nix-shell https://github.com/divnix/devos/archive/core.tar.gz -A shell \ + --run "flk get core" + +cd flk + +nix-shell + +git init +git add . +git commit -m init +``` + +This will place you in a new folder named `flk` with git initialized, and a +nix-shell that provides all the dependencies, including the unstable nix +version required. + +In addition, the [binary cache](../integrations/cachix.md) is added for faster deployment. + +> ##### _Notes:_ +> - Flakes ignore files that have not been added to git, so be sure to stage new +> files before building the system. +> - You can choose to simply clone the repo with git if you want to follow +> upstream changes. +> - If the `nix-shell -p cachix --run "cachix use nrdxp"` line doesn't work +> you can try with sudo: `sudo nix-shell -p cachix --run "cachix use nrdxp"` + +## Next Steps: +- [Make installable ISO](./iso.md) +- [Bootstrap Host](./bootstrapping.md) +- [Already on NixOS](./from-nixos.md) + + +[install-nix]: https://nixos.org/manual/nix/stable/#sect-multi-user-installation diff --git a/doc/start/iso.md b/doc/start/iso.md new file mode 100644 index 00000000..76af1c6e --- /dev/null +++ b/doc/start/iso.md @@ -0,0 +1,22 @@ +# ISO + +Making and writing an installable iso for `hosts/bootstrap.nix` is as simple as: +```sh +bud build bootstrap bootstrapIso +sudo -E $(which bud) burn +``` + +This works for any host. + +## ISO image nix store & cache + +The iso image holds the store to the live environment and _also_ acts as a binary cache +to the installer. To considerably speed up things, the image already includes all flake +`inputs` as well as the `devshell` closures. + +While you _could_ provision any machine with a single stick, a custom-made iso for +the host you want to install DevOS to, maximises those local cache hits. + +For hosts that don't differ too much, a single usb stick might be ok, whereas when +there are bigger differences, a custom-made usb stick will be considerably faster. + diff --git a/doc/tests.md b/doc/tests.md new file mode 100644 index 00000000..1d7b65e2 --- /dev/null +++ b/doc/tests.md @@ -0,0 +1,33 @@ +# Testing + +Testing is always an important aspect of any software development project, and +NixOS offers some incredibly powerful tools to write tests for your +configuration, and, optionally, run them in +[CI](./integrations/hercules.md). + +## Unit Tests +Unit tests can be created from regular derivations, and they can do +almost anything you can imagine. By convention, it is best to test your +packages during their [check phase][check]. All packages and their tests will +be built during CI. + +## Integration Tests +All your profiles defined in suites will be tested in a NixOS VM. + +You can write integration tests for one or more NixOS VMs that can, +optionally, be networked together, and yes, it's as awesome as it sounds! + +Be sure to use the `mkTest` function from digga, `digga.lib.pkgs-lib.mkTest` +which wraps the official [testing-python][testing-python] function to ensure +that the system is setup exactly as it is for a bare DevOS system. There are +already great resources for learning how to use these tests effectively, +including the official [docs][test-doc], a fantastic [blog post][test-blog], +and the examples in [nixpkgs][nixos-tests]. + +[test-doc]: https://nixos.org/manual/nixos/stable/index.html#sec-nixos-tests +[test-blog]: https://www.haskellforall.com/2020/11/how-to-use-nixos-for-lightweight.html +[default]: https://github.com/divnix/devos/tree/core/tests/default.nix +[run-test]: https://github.com/NixOS/nixpkgs/blob/6571462647d7316aff8b8597ecdf5922547bf365/lib/debug.nix#L154-L166 +[nixos-tests]: https://github.com/NixOS/nixpkgs/tree/master/nixos/tests +[testing-python]: https://github.com/NixOS/nixpkgs/tree/master/nixos/lib/testing-python.nix +[check]: https://nixos.org/manual/nixpkgs/stable/#ssec-check-phase diff --git a/doc/theme/highlight.js b/doc/theme/highlight.js new file mode 100644 index 00000000..f4fd4fae --- /dev/null +++ b/doc/theme/highlight.js @@ -0,0 +1,6 @@ +/* + Highlight.js 10.1.2 (edd73d24) + License: BSD-3-Clause + Copyright (c) 2006-2020, Ivan Sagalaev +*/ +var hljs=function(){"use strict";function e(n){Object.freeze(n);var t="function"==typeof n;return Object.getOwnPropertyNames(n).forEach((function(r){!Object.hasOwnProperty.call(n,r)||null===n[r]||"object"!=typeof n[r]&&"function"!=typeof n[r]||t&&("caller"===r||"callee"===r||"arguments"===r)||Object.isFrozen(n[r])||e(n[r])})),n}class n{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data}ignoreMatch(){this.ignore=!0}}function t(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...n){var t={};for(const n in e)t[n]=e[n];return n.forEach((function(e){for(const n in e)t[n]=e[n]})),t}function a(e){return e.nodeName.toLowerCase()}var i=Object.freeze({__proto__:null,escapeHTML:t,inherit:r,nodeStream:function(e){var n=[];return function e(t,r){for(var i=t.firstChild;i;i=i.nextSibling)3===i.nodeType?r+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:r,node:i}),r=e(i,r),a(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:r,node:i}));return r}(e,0),n},mergeStreams:function(e,n,r){var i=0,s="",o=[];function l(){return e.length&&n.length?e[0].offset!==n[0].offset?e[0].offset"}function u(e){s+=""}function d(e){("start"===e.event?c:u)(e.node)}for(;e.length||n.length;){var g=l();if(s+=t(r.substring(i,g[0].offset)),i=g[0].offset,g===e){o.reverse().forEach(u);do{d(g.splice(0,1)[0]),g=l()}while(g===e&&g.length&&g[0].offset===i);o.reverse().forEach(c)}else"start"===g[0].event?o.push(g[0].node):o.pop(),d(g.splice(0,1)[0])}return s+t(r.substr(i))}});const s="",o=e=>!!e.kind;class l{constructor(e,n){this.buffer="",this.classPrefix=n.classPrefix,e.walk(this)}addText(e){this.buffer+=t(e)}openNode(e){if(!o(e))return;let n=e.kind;e.sublanguage||(n=`${this.classPrefix}${n}`),this.span(n)}closeNode(e){o(e)&&(this.buffer+=s)}value(){return this.buffer}span(e){this.buffer+=``}}class c{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const n={kind:e,children:[]};this.add(n),this.stack.push(n)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,n){return"string"==typeof n?e.addText(n):n.children&&(e.openNode(n),n.children.forEach(n=>this._walk(e,n)),e.closeNode(n)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{c._collapse(e)}))}}class u extends c{constructor(e){super(),this.options=e}addKeyword(e,n){""!==e&&(this.openNode(n),this.addText(e),this.closeNode())}addText(e){""!==e&&this.add(e)}addSublanguage(e,n){const t=e.root;t.kind=n,t.sublanguage=!0,this.add(t)}toHTML(){return new l(this,this.options).value()}finalize(){return!0}}function d(e){return e?"string"==typeof e?e:e.source:null}const g="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",h={begin:"\\\\[\\s\\S]",relevance:0},f={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[h]},p={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[h]},b={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},m=function(e,n,t={}){var a=r({className:"comment",begin:e,end:n,contains:[]},t);return a.contains.push(b),a.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),a},v=m("//","$"),x=m("/\\*","\\*/"),E=m("#","$");var _=Object.freeze({__proto__:null,IDENT_RE:"[a-zA-Z]\\w*",UNDERSCORE_IDENT_RE:"[a-zA-Z_]\\w*",NUMBER_RE:"\\b\\d+(\\.\\d+)?",C_NUMBER_RE:g,BINARY_NUMBER_RE:"\\b(0b[01]+)",RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const n=/^#![ ]*\//;return e.binary&&(e.begin=function(...e){return e.map(e=>d(e)).join("")}(n,/.*\b/,e.binary,/\b.*/)),r({className:"meta",begin:n,end:/$/,relevance:0,"on:begin":(e,n)=>{0!==e.index&&n.ignoreMatch()}},e)},BACKSLASH_ESCAPE:h,APOS_STRING_MODE:f,QUOTE_STRING_MODE:p,PHRASAL_WORDS_MODE:b,COMMENT:m,C_LINE_COMMENT_MODE:v,C_BLOCK_COMMENT_MODE:x,HASH_COMMENT_MODE:E,NUMBER_MODE:{className:"number",begin:"\\b\\d+(\\.\\d+)?",relevance:0},C_NUMBER_MODE:{className:"number",begin:g,relevance:0},BINARY_NUMBER_MODE:{className:"number",begin:"\\b(0b[01]+)",relevance:0},CSS_NUMBER_MODE:{className:"number",begin:"\\b\\d+(\\.\\d+)?(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},REGEXP_MODE:{begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[h,{begin:/\[/,end:/\]/,relevance:0,contains:[h]}]}]},TITLE_MODE:{className:"title",begin:"[a-zA-Z]\\w*",relevance:0},UNDERSCORE_TITLE_MODE:{className:"title",begin:"[a-zA-Z_]\\w*",relevance:0},METHOD_GUARD:{begin:"\\.\\s*[a-zA-Z_]\\w*",relevance:0},END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,n)=>{n.data._beginMatch=e[1]},"on:end":(e,n)=>{n.data._beginMatch!==e[1]&&n.ignoreMatch()}})}}),N="of and for in not or if then".split(" ");function w(e,n){return n?+n:function(e){return N.includes(e.toLowerCase())}(e)?0:1}const R=t,y=r,{nodeStream:O,mergeStreams:k}=i,M=Symbol("nomatch");return function(t){var a=[],i=Object.create(null),s=Object.create(null),o=[],l=!0,c=/(^(<[^>]+>|\t|)+|\n)/gm,g="Could not find the language '{}', did you forget to load/include a language module?";const h={disableAutodetect:!0,name:"Plain text",contains:[]};var f={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:u};function p(e){return f.noHighlightRe.test(e)}function b(e,n,t,r){var a={code:n,language:e};S("before:highlight",a);var i=a.result?a.result:m(a.language,a.code,t,r);return i.code=a.code,S("after:highlight",i),i}function m(e,t,a,s){var o=t;function c(e,n){var t=E.case_insensitive?n[0].toLowerCase():n[0];return Object.prototype.hasOwnProperty.call(e.keywords,t)&&e.keywords[t]}function u(){null!=y.subLanguage?function(){if(""!==A){var e=null;if("string"==typeof y.subLanguage){if(!i[y.subLanguage])return void k.addText(A);e=m(y.subLanguage,A,!0,O[y.subLanguage]),O[y.subLanguage]=e.top}else e=v(A,y.subLanguage.length?y.subLanguage:null);y.relevance>0&&(I+=e.relevance),k.addSublanguage(e.emitter,e.language)}}():function(){if(!y.keywords)return void k.addText(A);let e=0;y.keywordPatternRe.lastIndex=0;let n=y.keywordPatternRe.exec(A),t="";for(;n;){t+=A.substring(e,n.index);const r=c(y,n);if(r){const[e,a]=r;k.addText(t),t="",I+=a,k.addKeyword(n[0],e)}else t+=n[0];e=y.keywordPatternRe.lastIndex,n=y.keywordPatternRe.exec(A)}t+=A.substr(e),k.addText(t)}(),A=""}function h(e){return e.className&&k.openNode(e.className),y=Object.create(e,{parent:{value:y}})}function p(e){return 0===y.matcher.regexIndex?(A+=e[0],1):(L=!0,0)}var b={};function x(t,r){var i=r&&r[0];if(A+=t,null==i)return u(),0;if("begin"===b.type&&"end"===r.type&&b.index===r.index&&""===i){if(A+=o.slice(r.index,r.index+1),!l){const n=Error("0 width match regex");throw n.languageName=e,n.badRule=b.rule,n}return 1}if(b=r,"begin"===r.type)return function(e){var t=e[0],r=e.rule;const a=new n(r),i=[r.__beforeBegin,r["on:begin"]];for(const n of i)if(n&&(n(e,a),a.ignore))return p(t);return r&&r.endSameAsBegin&&(r.endRe=RegExp(t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")),r.skip?A+=t:(r.excludeBegin&&(A+=t),u(),r.returnBegin||r.excludeBegin||(A=t)),h(r),r.returnBegin?0:t.length}(r);if("illegal"===r.type&&!a){const e=Error('Illegal lexeme "'+i+'" for mode "'+(y.className||"")+'"');throw e.mode=y,e}if("end"===r.type){var s=function(e){var t=e[0],r=o.substr(e.index),a=function e(t,r,a){let i=function(e,n){var t=e&&e.exec(n);return t&&0===t.index}(t.endRe,a);if(i){if(t["on:end"]){const e=new n(t);t["on:end"](r,e),e.ignore&&(i=!1)}if(i){for(;t.endsParent&&t.parent;)t=t.parent;return t}}if(t.endsWithParent)return e(t.parent,r,a)}(y,e,r);if(!a)return M;var i=y;i.skip?A+=t:(i.returnEnd||i.excludeEnd||(A+=t),u(),i.excludeEnd&&(A=t));do{y.className&&k.closeNode(),y.skip||y.subLanguage||(I+=y.relevance),y=y.parent}while(y!==a.parent);return a.starts&&(a.endSameAsBegin&&(a.starts.endRe=a.endRe),h(a.starts)),i.returnEnd?0:t.length}(r);if(s!==M)return s}if("illegal"===r.type&&""===i)return 1;if(B>1e5&&B>3*r.index)throw Error("potential infinite loop, way more iterations than matches");return A+=i,i.length}var E=T(e);if(!E)throw console.error(g.replace("{}",e)),Error('Unknown language: "'+e+'"');var _=function(e){function n(n,t){return RegExp(d(n),"m"+(e.case_insensitive?"i":"")+(t?"g":""))}class t{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,n){n.position=this.position++,this.matchIndexes[this.matchAt]=n,this.regexes.push([n,e]),this.matchAt+=function(e){return RegExp(e.toString()+"|").exec("").length-1}(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=n(function(e,n="|"){for(var t=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./,r=0,a="",i=0;i0&&(a+=n),a+="(";o.length>0;){var l=t.exec(o);if(null==l){a+=o;break}a+=o.substring(0,l.index),o=o.substring(l.index+l[0].length),"\\"===l[0][0]&&l[1]?a+="\\"+(+l[1]+s):(a+=l[0],"("===l[0]&&r++)}a+=")"}return a}(e),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const n=this.matcherRe.exec(e);if(!n)return null;const t=n.findIndex((e,n)=>n>0&&void 0!==e),r=this.matchIndexes[t];return n.splice(0,t),Object.assign(n,r)}}class a{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const n=new t;return this.rules.slice(e).forEach(([e,t])=>n.addRule(e,t)),n.compile(),this.multiRegexes[e]=n,n}considerAll(){this.regexIndex=0}addRule(e,n){this.rules.push([e,n]),"begin"===n.type&&this.count++}exec(e){const n=this.getMatcher(this.regexIndex);n.lastIndex=this.lastIndex;const t=n.exec(e);return t&&(this.regexIndex+=t.position+1,this.regexIndex===this.count&&(this.regexIndex=0)),t}}function i(e,n){const t=e.input[e.index-1],r=e.input[e.index+e[0].length];"."!==t&&"."!==r||n.ignoreMatch()}if(e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return function t(s,o){const l=s;if(s.compiled)return l;s.compiled=!0,s.__beforeBegin=null,s.keywords=s.keywords||s.beginKeywords;let c=null;if("object"==typeof s.keywords&&(c=s.keywords.$pattern,delete s.keywords.$pattern),s.keywords&&(s.keywords=function(e,n){var t={};return"string"==typeof e?r("keyword",e):Object.keys(e).forEach((function(n){r(n,e[n])})),t;function r(e,r){n&&(r=r.toLowerCase()),r.split(" ").forEach((function(n){var r=n.split("|");t[r[0]]=[e,w(r[0],r[1])]}))}}(s.keywords,e.case_insensitive)),s.lexemes&&c)throw Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return l.keywordPatternRe=n(s.lexemes||c||/\w+/,!0),o&&(s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?=\\b|\\s)",s.__beforeBegin=i),s.begin||(s.begin=/\B|\b/),l.beginRe=n(s.begin),s.endSameAsBegin&&(s.end=s.begin),s.end||s.endsWithParent||(s.end=/\B|\b/),s.end&&(l.endRe=n(s.end)),l.terminator_end=d(s.end)||"",s.endsWithParent&&o.terminator_end&&(l.terminator_end+=(s.end?"|":"")+o.terminator_end)),s.illegal&&(l.illegalRe=n(s.illegal)),void 0===s.relevance&&(s.relevance=1),s.contains||(s.contains=[]),s.contains=[].concat(...s.contains.map((function(e){return function(e){return e.variants&&!e.cached_variants&&(e.cached_variants=e.variants.map((function(n){return r(e,{variants:null},n)}))),e.cached_variants?e.cached_variants:function e(n){return!!n&&(n.endsWithParent||e(n.starts))}(e)?r(e,{starts:e.starts?r(e.starts):null}):Object.isFrozen(e)?r(e):e}("self"===e?s:e)}))),s.contains.forEach((function(e){t(e,l)})),s.starts&&t(s.starts,o),l.matcher=function(e){const n=new a;return e.contains.forEach(e=>n.addRule(e.begin,{rule:e,type:"begin"})),e.terminator_end&&n.addRule(e.terminator_end,{type:"end"}),e.illegal&&n.addRule(e.illegal,{type:"illegal"}),n}(l),l}(e)}(E),N="",y=s||_,O={},k=new f.__emitter(f);!function(){for(var e=[],n=y;n!==E;n=n.parent)n.className&&e.unshift(n.className);e.forEach(e=>k.openNode(e))}();var A="",I=0,S=0,B=0,L=!1;try{for(y.matcher.considerAll();;){B++,L?L=!1:(y.matcher.lastIndex=S,y.matcher.considerAll());const e=y.matcher.exec(o);if(!e)break;const n=x(o.substring(S,e.index),e);S=e.index+n}return x(o.substr(S)),k.closeAllNodes(),k.finalize(),N=k.toHTML(),{relevance:I,value:N,language:e,illegal:!1,emitter:k,top:y}}catch(n){if(n.message&&n.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:n.message,context:o.slice(S-100,S+100),mode:n.mode},sofar:N,relevance:0,value:R(o),emitter:k};if(l)return{illegal:!1,relevance:0,value:R(o),emitter:k,language:e,top:y,errorRaised:n};throw n}}function v(e,n){n=n||f.languages||Object.keys(i);var t=function(e){const n={relevance:0,emitter:new f.__emitter(f),value:R(e),illegal:!1,top:h};return n.emitter.addText(e),n}(e),r=t;return n.filter(T).filter(I).forEach((function(n){var a=m(n,e,!1);a.language=n,a.relevance>r.relevance&&(r=a),a.relevance>t.relevance&&(r=t,t=a)})),r.language&&(t.second_best=r),t}function x(e){return f.tabReplace||f.useBR?e.replace(c,e=>"\n"===e?f.useBR?"
":e:f.tabReplace?e.replace(/\t/g,f.tabReplace):e):e}function E(e){let n=null;const t=function(e){var n=e.className+" ";n+=e.parentNode?e.parentNode.className:"";const t=f.languageDetectRe.exec(n);if(t){var r=T(t[1]);return r||(console.warn(g.replace("{}",t[1])),console.warn("Falling back to no-highlight mode for this block.",e)),r?t[1]:"no-highlight"}return n.split(/\s+/).find(e=>p(e)||T(e))}(e);if(p(t))return;S("before:highlightBlock",{block:e,language:t}),f.useBR?(n=document.createElement("div")).innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n"):n=e;const r=n.textContent,a=t?b(t,r,!0):v(r),i=O(n);if(i.length){const e=document.createElement("div");e.innerHTML=a.value,a.value=k(i,O(e),r)}a.value=x(a.value),S("after:highlightBlock",{block:e,result:a}),e.innerHTML=a.value,e.className=function(e,n,t){var r=n?s[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),e.includes(r)||a.push(r),a.join(" ").trim()}(e.className,t,a.language),e.result={language:a.language,re:a.relevance,relavance:a.relevance},a.second_best&&(e.second_best={language:a.second_best.language,re:a.second_best.relevance,relavance:a.second_best.relevance})}const N=()=>{if(!N.called){N.called=!0;var e=document.querySelectorAll("pre code");a.forEach.call(e,E)}};function T(e){return e=(e||"").toLowerCase(),i[e]||i[s[e]]}function A(e,{languageName:n}){"string"==typeof e&&(e=[e]),e.forEach(e=>{s[e]=n})}function I(e){var n=T(e);return n&&!n.disableAutodetect}function S(e,n){var t=e;o.forEach((function(e){e[t]&&e[t](n)}))}Object.assign(t,{highlight:b,highlightAuto:v,fixMarkup:x,highlightBlock:E,configure:function(e){f=y(f,e)},initHighlighting:N,initHighlightingOnLoad:function(){window.addEventListener("DOMContentLoaded",N,!1)},registerLanguage:function(e,n){var r=null;try{r=n(t)}catch(n){if(console.error("Language definition for '{}' could not be registered.".replace("{}",e)),!l)throw n;console.error(n),r=h}r.name||(r.name=e),i[e]=r,r.rawDefinition=n.bind(null,t),r.aliases&&A(r.aliases,{languageName:e})},listLanguages:function(){return Object.keys(i)},getLanguage:T,registerAliases:A,requireLanguage:function(e){var n=T(e);if(n)return n;throw Error("The '{}' language is required, but not loaded.".replace("{}",e))},autoDetection:I,inherit:y,addPlugin:function(e){o.push(e)}}),t.debugMode=function(){l=!1},t.safeMode=function(){l=!0},t.versionString="10.1.2";for(const n in _)"object"==typeof _[n]&&e(_[n]);return Object.assign(t,_),t}({})}();"object"==typeof exports&&"undefined"!=typeof module&&(module.exports=hljs);hljs.registerLanguage("xml",function(){"use strict";return function(e){var n={className:"symbol",begin:"&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;"},a={begin:"\\s",contains:[{className:"meta-keyword",begin:"#?[a-z_][a-z1-9_-]+",illegal:"\\n"}]},s=e.inherit(a,{begin:"\\(",end:"\\)"}),t=e.inherit(e.APOS_STRING_MODE,{className:"meta-string"}),i=e.inherit(e.QUOTE_STRING_MODE,{className:"meta-string"}),c={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin:"",relevance:10,contains:[a,i,t,s,{begin:"\\[",end:"\\]",contains:[{className:"meta",begin:"",contains:[a,s,i,t]}]}]},e.COMMENT("\x3c!--","--\x3e",{relevance:10}),{begin:"<\\!\\[CDATA\\[",end:"\\]\\]>",relevance:10},n,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:")",end:">",keywords:{name:"style"},contains:[c],starts:{end:"",returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:")",end:">",keywords:{name:"script"},contains:[c],starts:{end:"<\/script>",returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:"",contains:[{className:"name",begin:/[^\/><\s]+/,relevance:0},c]}]}}}());hljs.registerLanguage("markdown",function(){"use strict";return function(n){const e={begin:"<",end:">",subLanguage:"xml",relevance:0},a={begin:"\\[.+?\\][\\(\\[].*?[\\)\\]]",returnBegin:!0,contains:[{className:"string",begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0,relevance:0},{className:"link",begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}],relevance:10},i={className:"strong",contains:[],variants:[{begin:/_{2}/,end:/_{2}/},{begin:/\*{2}/,end:/\*{2}/}]},s={className:"emphasis",contains:[],variants:[{begin:/\*(?!\*)/,end:/\*/},{begin:/_(?!_)/,end:/_/,relevance:0}]};i.contains.push(s),s.contains.push(i);var c=[e,a];return i.contains=i.contains.concat(c),s.contains=s.contains.concat(c),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:c=c.concat(i,s)},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:c}]}]},e,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},i,s,{className:"quote",begin:"^>\\s+",contains:c,end:"$"},{className:"code",variants:[{begin:"(`{3,})(.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})(.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},a,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]}]}}}());hljs.registerLanguage("perl",function(){"use strict";return function(e){var n={$pattern:/[\w.]+/,keyword:"getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qq fileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmget sub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedir ioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when"},t={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:n},s={begin:"->{",end:"}"},r={variants:[{begin:/\$\d/},{begin:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{begin:/[\$%@][^\s\w{]/,relevance:0}]},i=[e.BACKSLASH_ESCAPE,t,r],a=[r,e.HASH_COMMENT_MODE,e.COMMENT("^\\=\\w","\\=cut",{endsWithParent:!0}),s,{className:"string",contains:i,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*\\<",end:"\\>",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:"{\\w+}",contains:[],relevance:0},{begin:"-?\\w+\\s*\\=\\>",contains:[],relevance:0}]},{className:"number",begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",begin:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",relevance:10},{className:"regexp",begin:"(m|qr)?/",end:"/[a-z]*",contains:[e.BACKSLASH_ESCAPE],relevance:0}]},{className:"function",beginKeywords:"sub",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return t.contains=a,s.contains=a,{name:"Perl",aliases:["pl","pm"],keywords:n,contains:a}}}());hljs.registerLanguage("plaintext",function(){"use strict";return function(t){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}}());hljs.registerLanguage("ini",function(){"use strict";function e(e){return e?"string"==typeof e?e:e.source:null}function n(...n){return n.map(n=>e(n)).join("")}return function(a){var s={className:"number",relevance:0,variants:[{begin:/([\+\-]+)?[\d]+_[\d_]+/},{begin:a.NUMBER_RE}]},i=a.COMMENT();i.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];var t={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)}/}]},r={className:"literal",begin:/\bon|off|true|false|yes|no\b/},l={className:"string",contains:[a.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},c={begin:/\[/,end:/\]/,contains:[i,r,t,l,s,"self"],relevance:0},g="("+[/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/].map(n=>e(n)).join("|")+")";return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[i,{className:"section",begin:/\[+/,end:/\]+/},{begin:n(g,"(\\s*\\.\\s*",g,")*",n("(?=",/\s*=\s*[^#\s]/,")")),className:"attr",starts:{end:/$/,contains:[i,c,r,t,l,s]}}]}}}());hljs.registerLanguage("json",function(){"use strict";return function(n){var e={literal:"true false null"},i=[n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE],t=[n.QUOTE_STRING_MODE,n.C_NUMBER_MODE],a={end:",",endsWithParent:!0,excludeEnd:!0,contains:t,keywords:e},l={begin:"{",end:"}",contains:[{className:"attr",begin:/"/,end:/"/,contains:[n.BACKSLASH_ESCAPE],illegal:"\\n"},n.inherit(a,{begin:/:/})].concat(i),illegal:"\\S"},s={begin:"\\[",end:"\\]",contains:[n.inherit(a)],illegal:"\\S"};return t.push(l,s),i.forEach((function(n){t.push(n)})),{name:"JSON",contains:t,keywords:e,illegal:"\\S"}}}());hljs.registerLanguage("ruby",function(){"use strict";return function(e){var n="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",a={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},s={className:"doctag",begin:"@[A-Za-z]+"},i={begin:"#<",end:">"},r=[e.COMMENT("#","$",{contains:[s]}),e.COMMENT("^\\=begin","^\\=end",{contains:[s],relevance:10}),e.COMMENT("^__END__","\\n$")],c={className:"subst",begin:"#\\{",end:"}",keywords:a},t={className:"string",contains:[e.BACKSLASH_ESCAPE,c],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:"%[qQwWx]?\\(",end:"\\)"},{begin:"%[qQwWx]?\\[",end:"\\]"},{begin:"%[qQwWx]?{",end:"}"},{begin:"%[qQwWx]?<",end:">"},{begin:"%[qQwWx]?/",end:"/"},{begin:"%[qQwWx]?%",end:"%"},{begin:"%[qQwWx]?-",end:"-"},{begin:"%[qQwWx]?\\|",end:"\\|"},{begin:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{begin:/<<[-~]?'?(\w+)(?:.|\n)*?\n\s*\1\b/,returnBegin:!0,contains:[{begin:/<<[-~]?'?/},e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,c]})]}]},b={className:"params",begin:"\\(",end:"\\)",endsParent:!0,keywords:a},d=[t,i,{className:"class",beginKeywords:"class module",end:"$|;",illegal:/=/,contains:[e.inherit(e.TITLE_MODE,{begin:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{begin:"<\\s*",contains:[{begin:"("+e.IDENT_RE+"::)?"+e.IDENT_RE}]}].concat(r)},{className:"function",beginKeywords:"def",end:"$|;",contains:[e.inherit(e.TITLE_MODE,{begin:n}),b].concat(r)},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(\\!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[t,{begin:n}],relevance:0},{className:"number",begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{begin:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{className:"params",begin:/\|/,end:/\|/,keywords:a},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[i,{className:"regexp",contains:[e.BACKSLASH_ESCAPE,c],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:"%r{",end:"}[a-z]*"},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(r),relevance:0}].concat(r);c.contains=d,b.contains=d;var g=[{begin:/^\s*=>/,starts:{end:"$",contains:d}},{className:"meta",begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+>|(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>)",starts:{end:"$",contains:d}}];return{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:a,illegal:/\/\*/,contains:r.concat(g).concat(d)}}}());hljs.registerLanguage("yaml",function(){"use strict";return function(e){var n="true false yes no null",a="[\\w#;/?:@&=+$,.~*\\'()[\\]]+",s={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:"{{",end:"}}"},{begin:"%{",end:"}"}]}]},i=e.inherit(s,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),l={end:",",endsWithParent:!0,excludeEnd:!0,contains:[],keywords:n,relevance:0},t={begin:"{",end:"}",contains:[l],illegal:"\\n",relevance:0},g={begin:"\\[",end:"\\]",contains:[l],illegal:"\\n",relevance:0},b=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---s*$",relevance:10},{className:"string",begin:"[\\|>]([0-9]?[+-])?[ ]*\\n( *)[\\S ]+\\n(\\2[\\S ]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+a},{className:"type",begin:"!<"+a+">"},{className:"type",begin:"!"+a},{className:"type",begin:"!!"+a},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"\\-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:n,keywords:{literal:n}},{className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},{className:"number",begin:e.C_NUMBER_RE+"\\b"},t,g,s],c=[...b];return c.pop(),c.push(i),l.contains=c,{name:"YAML",case_insensitive:!0,aliases:["yml","YAML"],contains:b}}}());hljs.registerLanguage("haskell",function(){"use strict";return function(e){var n={variants:[e.COMMENT("--","$"),e.COMMENT("{-","-}",{contains:["self"]})]},i={className:"meta",begin:"{-#",end:"#-}"},a={className:"meta",begin:"^#",end:"$"},s={className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},l={begin:"\\(",end:"\\)",illegal:'"',contains:[i,a,{className:"type",begin:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TITLE_MODE,{begin:"[_a-z][\\w']*"}),n]};return{name:"Haskell",aliases:["hs"],keywords:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",contains:[{beginKeywords:"module",end:"where",keywords:"module where",contains:[l,n],illegal:"\\W\\.|;"},{begin:"\\bimport\\b",end:"$",keywords:"import qualified as hiding",contains:[l,n],illegal:"\\W\\.|;"},{className:"class",begin:"^(\\s*)?(class|instance)\\b",end:"where",keywords:"class family instance where",contains:[s,l,n]},{className:"class",begin:"\\b(data|(new)?type)\\b",end:"$",keywords:"data family type newtype deriving",contains:[i,s,l,{begin:"{",end:"}",contains:l.contains},n]},{beginKeywords:"default",end:"$",contains:[s,l,n]},{beginKeywords:"infix infixl infixr",end:"$",contains:[e.C_NUMBER_MODE,n]},{begin:"\\bforeign\\b",end:"$",keywords:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",contains:[s,e.QUOTE_STRING_MODE,n]},{className:"meta",begin:"#!\\/usr\\/bin\\/env runhaskell",end:"$"},i,a,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,s,e.inherit(e.TITLE_MODE,{begin:"^[_a-z][\\w']*"}),n,{begin:"->|<-"}]}}}());hljs.registerLanguage("nix",function(){"use strict";return function(e){var n={keyword:"rec with let in inherit assert if else then",literal:"true false or and null",built_in:"import abort baseNameOf dirOf isNull builtins map removeAttrs throw toString derivation"},i={className:"subst",begin:/\$\{/,end:/}/,keywords:n},t={className:"string",contains:[i],variants:[{begin:"''",end:"''"},{begin:'"',end:'"'}]},s=[e.NUMBER_MODE,e.HASH_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t,{begin:/[a-zA-Z0-9-_]+(\s*=)/,returnBegin:!0,relevance:0,contains:[{className:"attr",begin:/\S+/}]}];return i.contains=s,{name:"Nix",aliases:["nixos"],keywords:n,contains:s}}}());hljs.registerLanguage("bash",function(){"use strict";return function(e){const s={};Object.assign(s,{className:"variable",variants:[{begin:/\$[\w\d#@][\w\d_]*/},{begin:/\$\{/,end:/\}/,contains:[{begin:/:-/,contains:[s]}]}]});const t={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},n={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,t]};t.contains.push(n);const a={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,s]},i=e.SHEBANG({binary:"(fish|bash|zsh|sh|csh|ksh|tcsh|dash|scsh)",relevance:10}),c={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b-?[a-z\._]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},contains:[i,e.SHEBANG(),c,a,e.HASH_COMMENT_MODE,n,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},s]}}}());hljs.registerLanguage("shell",function(){"use strict";return function(s){return{name:"Shell Session",aliases:["console"],contains:[{className:"meta",begin:"^\\s{0,3}[/\\w\\d\\[\\]()@-]*[>%$#]",starts:{end:"$",subLanguage:"bash"}}]}}}());hljs.registerLanguage("python",function(){"use strict";return function(e){var n={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10",built_in:"Ellipsis NotImplemented",literal:"False None True"},a={className:"meta",begin:/^(>>>|\.\.\.) /},i={className:"subst",begin:/\{/,end:/\}/,keywords:n,illegal:/#/},s={begin:/\{\{/,relevance:0},r={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/(u|b)?r?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/(u|b)?r?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/(fr|rf|f)'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a,s,i]},{begin:/(fr|rf|f)"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a,s,i]},{begin:/(u|r|ur)'/,end:/'/,relevance:10},{begin:/(u|r|ur)"/,end:/"/,relevance:10},{begin:/(b|br)'/,end:/'/},{begin:/(b|br)"/,end:/"/},{begin:/(fr|rf|f)'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,i]},{begin:/(fr|rf|f)"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,i]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l={className:"number",relevance:0,variants:[{begin:e.BINARY_NUMBER_RE+"[lLjJ]?"},{begin:"\\b(0o[0-7]+)[lLjJ]?"},{begin:e.C_NUMBER_RE+"[lLjJ]?"}]},t={className:"params",variants:[{begin:/\(\s*\)/,skip:!0,className:null},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,contains:["self",a,l,r,e.HASH_COMMENT_MODE]}]};return i.contains=[r,l,a],{name:"Python",aliases:["py","gyp","ipython"],keywords:n,illegal:/(<\/|->|\?)|=>/,contains:[a,l,{beginKeywords:"if",relevance:0},r,e.HASH_COMMENT_MODE,{variants:[{className:"function",beginKeywords:"def"},{className:"class",beginKeywords:"class"}],end:/:/,illegal:/[${=;\n,]/,contains:[e.UNDERSCORE_TITLE_MODE,t,{begin:/->/,endsWithParent:!0,keywords:"None"}]},{className:"meta",begin:/^[\t ]*@/,end:/$/},{begin:/\b(print|exec)\(/}]}}}()); diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..dfd8cc18 --- /dev/null +++ b/flake.lock @@ -0,0 +1,925 @@ +{ + "nodes": { + "agenix": { + "inputs": { + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1662241716, + "narHash": "sha256-urqPvSvvGUhkwzTDxUI8N1nsdMysbAfjmBNZaTYBZRU=", + "owner": "ryantm", + "repo": "agenix", + "rev": "c96da5835b76d3d8e8d99a0fec6fe32f8539ee2e", + "type": "github" + }, + "original": { + "owner": "ryantm", + "repo": "agenix", + "type": "github" + } + }, + "basant": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": [ + "nixos" + ], + "poonam": [ + "poonam" + ] + }, + "locked": { + "lastModified": 1657514455, + "narHash": "sha256-rYrofeCRgZyiZMuuwbwbM7ZLNTj04S0l4G/1ZeH0gqI=", + "ref": "main", + "rev": "50f7ee786d9704ecfd67a9fe2eb8f338fc983dc1", + "revCount": 64, + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/basant" + }, + "original": { + "ref": "main", + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/basant" + } + }, + "blank": { + "locked": { + "lastModified": 1625557891, + "narHash": "sha256-O8/MWsPBGhhyPoPLHZAuoZiiHo9q6FLlEeIDEXuj6T4=", + "owner": "divnix", + "repo": "blank", + "rev": "5a5d2684073d9f563072ed07c871d577a6c614a8", + "type": "github" + }, + "original": { + "owner": "divnix", + "repo": "blank", + "type": "github" + } + }, + "darwin": { + "inputs": { + "nixpkgs": "nixpkgs" + }, + "locked": { + "lastModified": 1651916036, + "narHash": "sha256-UuD9keUGm4IuVEV6wdSYbuRm7CwfXE63hVkzKDjVsh4=", + "owner": "LnL7", + "repo": "nix-darwin", + "rev": "2f2bdf658d2b79bada78dc914af99c53cad37cba", + "type": "github" + }, + "original": { + "owner": "LnL7", + "repo": "nix-darwin", + "type": "github" + } + }, + "deploy": { + "inputs": { + "flake-compat": "flake-compat", + "nixpkgs": [ + "nixos" + ], + "utils": "utils" + }, + "locked": { + "lastModified": 1659725433, + "narHash": "sha256-1ZxuK67TL29YLw88vQ18Y2Y6iYg8Jb7I6/HVzmNB6nM=", + "owner": "serokell", + "repo": "deploy-rs", + "rev": "41f15759dd8b638e7b4f299730d94d5aa46ab7eb", + "type": "github" + }, + "original": { + "owner": "serokell", + "repo": "deploy-rs", + "type": "github" + } + }, + "devshell": { + "inputs": { + "flake-utils": "flake-utils_2", + "nixpkgs": "nixpkgs_2" + }, + "locked": { + "lastModified": 1655976588, + "narHash": "sha256-VreHyH6ITkf/1EX/8h15UqhddJnUleb0HgbC3gMkAEQ=", + "owner": "numtide", + "repo": "devshell", + "rev": "899ca4629020592a13a46783587f6e674179d1db", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "devshell", + "type": "github" + } + }, + "digga": { + "inputs": { + "blank": "blank", + "darwin": "darwin", + "deploy": [ + "deploy" + ], + "devshell": "devshell", + "flake-compat": "flake-compat_2", + "flake-utils-plus": "flake-utils-plus", + "home-manager": [ + "home" + ], + "latest": "latest", + "nixlib": [ + "nixos" + ], + "nixpkgs": [ + "nixos" + ], + "nixpkgs-unstable": "nixpkgs-unstable" + }, + "locked": { + "lastModified": 1659622306, + "narHash": "sha256-Kpfm2PNs+kZU0W7qcugoPATLG8I2P7FJFGTgsf1LJiU=", + "owner": "divnix", + "repo": "digga", + "rev": "d1193743a535d7fbbc7f3eda4e51295b10bd4d2c", + "type": "github" + }, + "original": { + "owner": "divnix", + "repo": "digga", + "type": "github" + } + }, + "dirt-samples-src": { + "flake": false, + "locked": { + "lastModified": 1588278411, + "narHash": "sha256-h8vQxRym6QzNLOTZU7A43VCHuG0H77l+BFwXnC0L1CE=", + "owner": "tidalcycles", + "repo": "dirt-samples", + "rev": "66d432418c9a7d82cf049d9246adfa62f46df2a6", + "type": "github" + }, + "original": { + "owner": "tidalcycles", + "ref": "master", + "repo": "dirt-samples", + "type": "github" + } + }, + "eww": { + "inputs": { + "flake-compat": "flake-compat_3", + "nixpkgs": [ + "nixos" + ], + "rust-overlay": [ + "rust-overlay" + ] + }, + "locked": { + "lastModified": 1663061357, + "narHash": "sha256-zMJslerxTcSQ+A8fI4gFcJioRGs+T55343zOtsnEJ3k=", + "owner": "elkowar", + "repo": "eww", + "rev": "52e9603dd8c79cbc267a4733389c1f7e7625b352", + "type": "github" + }, + "original": { + "owner": "elkowar", + "repo": "eww", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1648199409, + "narHash": "sha256-JwPKdC2PoVBkG6E+eWw3j6BMR6sL3COpYWfif7RVb8Y=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "64a525ee38886ab9028e6f61790de0832aa3ef03", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-compat_2": { + "flake": false, + "locked": { + "lastModified": 1650374568, + "narHash": "sha256-Z+s0J8/r907g149rllvwhb4pKi8Wam5ij0st8PwAh+E=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "b4a34015c698c7793d592d66adbab377907a2be8", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-compat_3": { + "flake": false, + "locked": { + "lastModified": 1650374568, + "narHash": "sha256-Z+s0J8/r907g149rllvwhb4pKi8Wam5ij0st8PwAh+E=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "b4a34015c698c7793d592d66adbab377907a2be8", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-compat_4": { + "flake": false, + "locked": { + "lastModified": 1650374568, + "narHash": "sha256-Z+s0J8/r907g149rllvwhb4pKi8Wam5ij0st8PwAh+E=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "b4a34015c698c7793d592d66adbab377907a2be8", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-compat_5": { + "flake": false, + "locked": { + "lastModified": 1648199409, + "narHash": "sha256-JwPKdC2PoVBkG6E+eWw3j6BMR6sL3COpYWfif7RVb8Y=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "64a525ee38886ab9028e6f61790de0832aa3ef03", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-utils": { + "locked": { + "lastModified": 1638122382, + "narHash": "sha256-sQzZzAbvKEqN9s0bzWuYmRaA03v40gaJ4+iL1LXjaeI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "74f7e4319258e287b0f9cb95426c9853b282730b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils-plus": { + "inputs": { + "flake-utils": "flake-utils_3" + }, + "locked": { + "lastModified": 1654029967, + "narHash": "sha256-my3GQ3mQIw/1f6GPV1IhUZrcYQSWh0YJAMPNBjhXJDw=", + "owner": "gytis-ivaskevicius", + "repo": "flake-utils-plus", + "rev": "6271cf3842ff9c8a9af9e3508c547f86bc77d199", + "type": "github" + }, + "original": { + "owner": "gytis-ivaskevicius", + "ref": "refs/pull/120/head", + "repo": "flake-utils-plus", + "type": "github" + } + }, + "flake-utils_2": { + "locked": { + "lastModified": 1642700792, + "narHash": "sha256-XqHrk7hFb+zBvRg6Ghl+AZDq03ov6OshJLiSWOoX5es=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "846b2ae0fc4cc943637d3d1def4454213e203cba", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_3": { + "locked": { + "lastModified": 1644229661, + "narHash": "sha256-1YdnJAsNy69bpcjuoKdOYQX0YxZBiCYZo4Twxerqv7k=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "3cecb5b042f7f209c56ffd8371b2711a290ec797", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_4": { + "locked": { + "lastModified": 1652372896, + "narHash": "sha256-lURGussfF3mGrFPQT3zgW7+RC0pBhbHzco0C7I+ilow=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "0d347c56f6f41de822a4f4c7ff5072f3382db121", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_5": { + "locked": { + "lastModified": 1659877975, + "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_6": { + "locked": { + "lastModified": 1649676176, + "narHash": "sha256-OWKJratjt2RW151VUlJPRALb7OU2S5s+f0vLj4o1bHM=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "a4b154ebbdc88c8498a5c7b01589addc9e9cb678", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_7": { + "locked": { + "lastModified": 1656928814, + "narHash": "sha256-RIFfgBuKz6Hp89yRr7+NR5tzIAbn52h8vT6vXkYjZoM=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "7e2a3b3dfd9af950a856d66b0a7d01e3c18aa249", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "grasp": { + "inputs": { + "flake-utils": "flake-utils_4", + "grasp": "grasp_2", + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1652615971, + "narHash": "sha256-e8fvTQCR/At2jgenuY71WXN13XawYRiMpKiHSGgGSkY=", + "ref": "main", + "rev": "ef605857248ec1b60cece250f98d2964164d48db", + "revCount": 19, + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/grasp.git" + }, + "original": { + "ref": "main", + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/grasp.git" + } + }, + "grasp_2": { + "flake": false, + "locked": { + "lastModified": 1586706168, + "narHash": "sha256-xLkxE24xtTghQpAfAqAsOvsGpz0coACXjNT8bHZhcxM=", + "owner": "karlicoss", + "repo": "grasp", + "rev": "4bc8f011227d1baa18b4e98543561534065490d8", + "type": "github" + }, + "original": { + "owner": "karlicoss", + "repo": "grasp", + "type": "github" + } + }, + "home": { + "inputs": { + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1656169755, + "narHash": "sha256-Nlnm4jeQWEGjYrE6hxi/7HYHjBSZ/E0RtjCYifnNsWk=", + "owner": "nix-community", + "repo": "home-manager", + "rev": "4a3d01fb53f52ac83194081272795aa4612c2381", + "type": "github" + }, + "original": { + "owner": "nix-community", + "ref": "release-22.05", + "repo": "home-manager", + "type": "github" + } + }, + "latest": { + "locked": { + "lastModified": 1657265485, + "narHash": "sha256-PUQ9C7mfi0/BnaAUX2R/PIkoNCb/Jtx9EpnhMBNrO/o=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "b39924fc7764c08ae3b51beef9a3518c414cdb7d", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "latest_2": { + "locked": { + "lastModified": 1663178737, + "narHash": "sha256-ayOtdyoNx6BqJtTYVzdQCDz/YWb67TY/CMGacFCgNQo=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "1158501e7c7cba26d922723cf9f70099995eb755", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "naersk": { + "inputs": { + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1662220400, + "narHash": "sha256-9o2OGQqu4xyLZP9K6kNe1pTHnyPz0Wr3raGYnr9AIgY=", + "owner": "nmattia", + "repo": "naersk", + "rev": "6944160c19cb591eb85bbf9b2f2768a935623ed3", + "type": "github" + }, + "original": { + "owner": "nmattia", + "repo": "naersk", + "type": "github" + } + }, + "neovim-flake": { + "inputs": { + "flake-utils": "flake-utils_5", + "nixpkgs": "nixpkgs_3" + }, + "locked": { + "dir": "contrib", + "lastModified": 1663315670, + "narHash": "sha256-RGoY9o0dN6BhOcjhJxw6XYSxUIDu+tAJl4vp7d9EBSM=", + "owner": "neovim", + "repo": "neovim", + "rev": "0b7a3c173c929085f54a178c9fa852481d5f021e", + "type": "github" + }, + "original": { + "dir": "contrib", + "owner": "neovim", + "repo": "neovim", + "type": "github" + } + }, + "neovim-nightly": { + "inputs": { + "flake-compat": "flake-compat_4", + "neovim-flake": "neovim-flake", + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1663316300, + "narHash": "sha256-QvFH3kiYJP+KTenixYDIp9bx3xyD36UQse3L4qfC6e4=", + "owner": "nix-community", + "repo": "neovim-nightly-overlay", + "rev": "dd84dca0ba386b7e49bae4255279d3c4cde9625c", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "neovim-nightly-overlay", + "type": "github" + } + }, + "nixos": { + "locked": { + "lastModified": 1663433994, + "narHash": "sha256-Bpthhv1PdZRrIFct8KbHACNvOu9bsYAMEaqoH83cvqM=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "17989edb05615c4f61803b9c427d80b84c289c6b", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "release-22.05", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixos-hardware": { + "locked": { + "lastModified": 1663229557, + "narHash": "sha256-1uU4nsDLXKG0AHc/VCsNBAEPkTA/07juYhcEWRb1O1E=", + "owner": "nixos", + "repo": "nixos-hardware", + "rev": "a0df6cd6e199df4a78c833c273781ea92fa62cfb", + "type": "github" + }, + "original": { + "owner": "nixos", + "repo": "nixos-hardware", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1663419078, + "narHash": "sha256-cxEeMnaTGMTeDAvXnZmqcF50qoyJOsQENhYxSnW9ZMs=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "0cfb3c002b61807ca0bab3efe514476bdf2e5478", + "type": "github" + }, + "original": { + "id": "nixpkgs", + "type": "indirect" + } + }, + "nixpkgs-unstable": { + "locked": { + "lastModified": 1657292830, + "narHash": "sha256-ldfVSTveWceDCmW6gf3B4kR6vwmz/XS80y5wsLLHFJU=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "334ec8b503c3981e37a04b817a70e8d026ea9e84", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1663419078, + "narHash": "sha256-cxEeMnaTGMTeDAvXnZmqcF50qoyJOsQENhYxSnW9ZMs=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "0cfb3c002b61807ca0bab3efe514476bdf2e5478", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_3": { + "locked": { + "lastModified": 1663357389, + "narHash": "sha256-oYA2nVRSi6yhCBqS5Vz465Hw+3BQOVFEhfbfy//3vTs=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "da6a05816e7fa5226c3f61e285ef8d9dfc868f3c", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_4": { + "locked": { + "lastModified": 1662446902, + "narHash": "sha256-Dmsd3jSG2ldZUlhFaIwunqgMf14EEK7ylXpw+OPDLxE=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "3bfaf06b12253ddaafe64a67f4ed39b547d41667", + "type": "github" + }, + "original": { + "owner": "nixos", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_5": { + "locked": { + "lastModified": 1663489134, + "narHash": "sha256-YqM45LLzvgBNbvIK0QQa8cY8omKS0+bRUg4JWzEj14w=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "830e228898ac7a66eeafb169dd3df0dc427674d4", + "type": "github" + }, + "original": { + "owner": "nixos", + "repo": "nixpkgs", + "type": "github" + } + }, + "nur": { + "locked": { + "lastModified": 1663393873, + "narHash": "sha256-DtumXhmyA9gpu0+qa5fwvU93qKqtx0AtUFvfazPzz1Y=", + "owner": "nix-community", + "repo": "NUR", + "rev": "ecf7442437f53f0f689df6897c10a7f9a4f6b9ae", + "type": "github" + }, + "original": { + "id": "nur", + "type": "indirect" + } + }, + "nvfetcher": { + "inputs": { + "flake-compat": "flake-compat_5", + "flake-utils": "flake-utils_6", + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1654975372, + "narHash": "sha256-wkNZ16akgKViuZzE/IM+bux4uaJ04KIwUeexH8gBjgw=", + "owner": "berberman", + "repo": "nvfetcher", + "rev": "d4b237c10f14f72f8266b0f658faad822e491e55", + "type": "github" + }, + "original": { + "owner": "berberman", + "repo": "nvfetcher", + "type": "github" + } + }, + "poonam": { + "inputs": { + "nixpkgs": "nixpkgs_4", + "vimwiki-cli": "vimwiki-cli" + }, + "locked": { + "lastModified": 1663038000, + "narHash": "sha256-Uf1aohzvF8nxrKW0Dli7+JfOouu4oGEP/lqRYycSapI=", + "ref": "main", + "rev": "bc78a43646dd833be3c17513d09661610ec2dfb0", + "revCount": 385, + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/kitaab" + }, + "original": { + "ref": "main", + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/kitaab" + } + }, + "root": { + "inputs": { + "agenix": "agenix", + "basant": "basant", + "deploy": "deploy", + "digga": "digga", + "eww": "eww", + "grasp": "grasp", + "home": "home", + "latest": "latest_2", + "naersk": "naersk", + "neovim-nightly": "neovim-nightly", + "nixos": "nixos", + "nixos-hardware": "nixos-hardware", + "nur": "nur", + "nvfetcher": "nvfetcher", + "poonam": "poonam", + "rust-overlay": "rust-overlay", + "tidalcycles": "tidalcycles" + } + }, + "rust-overlay": { + "inputs": { + "flake-utils": "flake-utils_7", + "nixpkgs": [ + "nixos" + ] + }, + "locked": { + "lastModified": 1663383457, + "narHash": "sha256-WoHXGHVmOv883HyH2Rvqh3XJE0Dk2YSZfLJyedSMr4U=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "e4c6adaa5f9293911de5ad50eaf32dbe36819de3", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "superdirt-src": { + "flake": false, + "locked": { + "lastModified": 1611740180, + "narHash": "sha256-GtnqZeMFqFkVhgx2Exu0wY687cHa7mNnVCgjQd6fiIA=", + "owner": "musikinformatik", + "repo": "superdirt", + "rev": "7abb62e89649daa1232b9cbd6427241868abd30e", + "type": "github" + }, + "original": { + "owner": "musikinformatik", + "ref": "master", + "repo": "superdirt", + "type": "github" + } + }, + "tidal-src": { + "flake": false, + "locked": { + "lastModified": 1654350756, + "narHash": "sha256-tONM5SYYBca0orTLH1EUOilSC1FCluWrFt8AetUx+YQ=", + "owner": "tidalcycles", + "repo": "tidal", + "rev": "fda9c1ecb3722698935245e5409ef8ccdfca16c8", + "type": "github" + }, + "original": { + "owner": "tidalcycles", + "ref": "main", + "repo": "tidal", + "type": "github" + } + }, + "tidalcycles": { + "inputs": { + "dirt-samples-src": "dirt-samples-src", + "nixpkgs": [ + "latest" + ], + "superdirt-src": "superdirt-src", + "tidal-src": "tidal-src", + "utils": "utils_2", + "vim-tidal-src": "vim-tidal-src", + "vowel-src": "vowel-src" + }, + "locked": { + "lastModified": 1661670241, + "narHash": "sha256-+5C83z+Sd8ugvMshrXqpca4vv3tQ2D4tYEJ3QY6JVsg=", + "owner": "mitchmindtree", + "repo": "tidalcycles.nix", + "rev": "fefe3d586511e1cfaac79bb83ec0b278bb1b6bad", + "type": "github" + }, + "original": { + "owner": "mitchmindtree", + "repo": "tidalcycles.nix", + "type": "github" + } + }, + "utils": { + "locked": { + "lastModified": 1648297722, + "narHash": "sha256-W+qlPsiZd8F3XkzXOzAoR+mpFqzm3ekQkJNa+PIh1BQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "0f8662f1319ad6abf89b3380dd2722369fc51ade", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "utils_2": { + "locked": { + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "vim-tidal-src": { + "flake": false, + "locked": { + "lastModified": 1661670183, + "narHash": "sha256-HU075U97COak/Xqw+4ifVkEEIgWzGvwRoR3q9LGKl8s=", + "owner": "mitchmindtree", + "repo": "vim-tidal", + "rev": "5c1e70ee3d2b4655b8ccba11422866c496610ca8", + "type": "github" + }, + "original": { + "owner": "mitchmindtree", + "ref": "mitchmindtree", + "repo": "vim-tidal", + "type": "github" + } + }, + "vimwiki-cli": { + "inputs": { + "nixpkgs": "nixpkgs_5" + }, + "locked": { + "lastModified": 1662448409, + "narHash": "sha256-Xd8CuFcEpEQK/TjNBXcp1HqPJCc7LwkMqKa1WiAP1Zc=", + "ref": "main", + "rev": "a73c4695cf116c2e8194a5caa837c2f9e1a7e2fb", + "revCount": 7, + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/vimwiki-cli" + }, + "original": { + "ref": "main", + "type": "git", + "url": "ssh://gitea@git.sealight.xyz/aynish/vimwiki-cli" + } + }, + "vowel-src": { + "flake": false, + "locked": { + "lastModified": 1641306144, + "narHash": "sha256-zfF6cvAGDNYWYsE8dOIo38b+dIymd17Pexg0HiPFbxM=", + "owner": "supercollider-quarks", + "repo": "vowel", + "rev": "ab59caa870201ecf2604b3efdd2196e21a8b5446", + "type": "github" + }, + "original": { + "owner": "supercollider-quarks", + "ref": "master", + "repo": "vowel", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..393afbf0 --- /dev/null +++ b/flake.nix @@ -0,0 +1,185 @@ +{ + description = "A highly structured configuration database."; + + inputs = + { + # Nix + nixos.url = "github:nixos/nixpkgs/release-22.05"; + latest.url = "github:nixos/nixpkgs/nixos-unstable"; + # Community + home.url = "github:nix-community/home-manager/release-22.05"; + home.inputs.nixpkgs.follows = "nixos"; + nixos-hardware.url = "github:nixos/nixos-hardware"; + # Lib + digga.url = "github:divnix/digga"; + digga.inputs.nixpkgs.follows = "nixos"; + digga.inputs.nixlib.follows = "nixos"; + digga.inputs.home-manager.follows = "home"; + digga.inputs.deploy.follows = "deploy"; + nvfetcher.url = "github:berberman/nvfetcher"; + nvfetcher.inputs.nixpkgs.follows = "nixos"; + naersk.url = "github:nmattia/naersk"; + naersk.inputs.nixpkgs.follows = "nixos"; + # Tools + agenix.url = "github:ryantm/agenix"; + agenix.inputs.nixpkgs.follows = "nixos"; + deploy.url = "github:serokell/deploy-rs"; + deploy.inputs.nixpkgs.follows = "nixos"; + # Packages + poonam.url = "git+ssh://gitea@git.sealight.xyz/aynish/kitaab?ref=main"; + basant.url = "git+ssh://gitea@git.sealight.xyz/aynish/basant?ref=main"; + basant.inputs.nixpkgs.follows = "nixos"; + basant.inputs.poonam.follows = "poonam"; + rust-overlay = { + url = "github:oxalica/rust-overlay"; + inputs.nixpkgs.follows = "nixos"; + }; + eww = { + url = "github:elkowar/eww"; + inputs.nixpkgs.follows = "nixos"; + inputs.rust-overlay.follows = "rust-overlay"; + }; + # eww follows rust nightly + # eww.inputs.nixpkgs.follows = "latest"; + grasp.url = "git+ssh://gitea@git.sealight.xyz/aynish/grasp.git?ref=main"; + grasp.inputs.nixpkgs.follows = "nixos"; + tidalcycles.url = "github:mitchmindtree/tidalcycles.nix"; + tidalcycles.inputs.nixpkgs.follows = "latest"; + neovim-nightly.url = "github:nix-community/neovim-nightly-overlay"; + neovim-nightly.inputs.nixpkgs.follows = "nixos"; + # TODO hundred rabbits software + # TODO not quite useful yet, since it needs secrets + # dhyan.url = "git+ssh://gitea@git.sealight.xyz/aynish/dhyan?ref=main"; + # dhyan.inputs.nixpkgs.follows = "nixos"; + }; + + outputs = + { self + , digga + , nixos + , home + , nixos-hardware + , nur + , agenix + , nvfetcher + , deploy + , basant + , grasp + , tidalcycles + , neovim-nightly + , rust-overlay + , eww + , ... + } @ inputs: + digga.lib.mkFlake + { + inherit self inputs; + supportedSystems = [ + "x86_64-linux" + ]; + + channelsConfig = { allowUnfree = true; }; + + channels = { + nixos = { + imports = [ (digga.lib.importOverlays ./overlays) ]; + overlays = [ + nur.overlay + agenix.overlay + nvfetcher.overlay + deploy.overlay + ./pkgs/default.nix + tidalcycles.overlays.default + neovim-nightly.overlay + rust-overlay.overlays.default + eww.overlays.default + ]; + }; + latest = { }; + }; + + lib = import ./lib { lib = digga.lib // nixos.lib; }; + + sharedOverlays = [ + (final: prev: { + __dontExport = true; + lib = prev.lib.extend (lfinal: lprev: { + our = self.lib; + }); + }) + ]; + + nixos = { + hostDefaults = { + system = "x86_64-linux"; + channelName = "nixos"; + imports = [ (digga.lib.importExportableModules ./modules) ]; + modules = [ + { lib.our = self.lib; } + digga.nixosModules.nixConfig + home.nixosModules.home-manager + agenix.nixosModules.age + ]; + }; + + imports = [ (digga.lib.importHosts ./hosts) ]; + hosts = { + /* set host specific properties here */ + curve = { + modules = [ + ]; # nixos-hardware.nixosModules.lenovo-thinkpad + # Yubikey + }; + cube = { + modules = [ basant.nixosModule ]; + }; + box = { + modules = [ + grasp.nixosModule + ]; + }; + # helix = { }; + # work = { }; + }; + importables = rec { + profiles = digga.lib.rakeLeaves ./profiles // { + users = digga.lib.rakeLeaves ./users; + }; + suites = with profiles; rec { + base = [ core users.root users.anish ]; + sealight = [ base server metrics gitea sealight-website backup rss-bridge mount-mossnet matrix ]; # + mossnet = [ base server taskd shaarli dns monitoring nfs rss-bridge gonic headphones radicale seafile syncthing dhyan calibre wallabag ]; # hpi sync.music + cube = [ base site server ]; + graphical = [ base bluetooth music sync.kitaab sync.website sync.cal wifi desktop mimetypes ]; + curve = [ graphical secrets syncthing ]; + work = [ base ]; + }; + }; + }; + + home = { + imports = [ (digga.lib.importExportableModules ./users/modules) ]; + # exportedModules = [ ]; + # modules = [ ]; + importables = rec { + profiles = digga.lib.rakeLeaves ./users/profiles; + suites = with profiles; rec { + hmBase = [ direnv git nvim cli task ]; + gui = [ hmBase firefox desktop email cal ]; + work = [ hmBase firefox ]; + }; + }; + users = { + nixos = { suites, ... }: { imports = suites.hmBase; }; + anish = { suites, ... }: { imports = suites.gui; }; + anishlakhwara = { suites, ... }: { imports = suites.work; }; + }; # digga.lib.importers.rakeLeaves ./users/hm; + }; + + devshell = ./shell; + + homeConfigurations = digga.lib.mkHomeConfigurations self.nixosConfigurations; + + deploy.nodes = digga.lib.mkDeployNodes self.nixosConfigurations { }; + }; +} diff --git a/hosts/bootstrap.nix b/hosts/bootstrap.nix new file mode 100644 index 00000000..d491855d --- /dev/null +++ b/hosts/bootstrap.nix @@ -0,0 +1,18 @@ +{ profiles, ... }: +{ + # build with: `bud build bootstrap bootstrapIso` + # reachable on the local link via ssh root@fe80::47%eno1 + # where 'eno1' is replaced by your own machine's network + # interface that has the local link to the target machine + imports = [ + # profiles.networking + profiles.core + profiles.users.root # make sure to configure ssh keys + profiles.users.nixos + ]; + + boot.loader.systemd-boot.enable = true; + + # will be overridden by the bootstrapIso instrumentation + fileSystems."/" = { device = "/dev/disk/by-label/nixos"; }; +} diff --git a/hosts/box/configuration.nix b/hosts/box/configuration.nix new file mode 100644 index 00000000..fff7bb0e --- /dev/null +++ b/hosts/box/configuration.nix @@ -0,0 +1,95 @@ +# Edit this configuration file to define what should be installed on +# your system. Help is available in the configuration.nix(5) man page +# and in the NixOS manual (accessible by running ‘nixos-help’). + +{ config, pkgs, ... }: + +{ + imports = + [ + # Include the results of the hardware scan. + ./hardware-configuration.nix + ]; + + # Use the GRUB 2 boot loader. + boot.loader.efi.canTouchEfiVariables = false; + boot.loader.efi.efiSysMountPoint = "/boot/efi"; + boot.loader.grub = { + enable = true; + device = "nodev"; + version = 2; + efiSupport = true; + enableCryptodisk = true; + efiInstallAsRemovable = true; + }; + + boot.initrd.secrets = { + "/keyfile0.bin" = /etc/secrets/initrd/keyfile0.bin; + "/keyfile1.bin" = /etc/secrets/initrd/keyfile1.bin; + }; + + boot.initrd.luks.devices = { + "root" = { + #name = "root"; + device = "/dev/disk/by-uuid/f37f3222-47d7-42d8-b400-363320a31853"; # UUID for /dev/nvme01np2 + preLVM = true; + allowDiscards = true; + keyFile = "/keyfile0.bin"; + }; + }; + + # Data mount + # fileSystems."/data" = { + # device = "/dev/disk/by-uuid/3276a297-9ee4-4998-b262-1ed100366c06"; # UUID for /dev/mapper/crypted-data + # encrypted = { + # enable = true; + # label = "crypted-data"; + # blkDev = "/dev/disk/by-uuid/8a317bf4-fe13-4334-a6df-5fe5a5048b5e"; # UUID for /dev/sda1 + # keyFile = "/keyfile1.bin"; + # }; + # }; + + networking.interfaces.enp2s0 = { + ipv4.addresses = [{ + address = "192.168.1.240"; + prefixLength = 24; + }]; + ipv4.routes = [{ address = "192.168.1.0"; prefixLength = 24; via = "192.168.1.1"; }]; + useDHCP = false; + }; + #networking.nameservers = [ "172.16.11.240" ]; + networking.nameservers = [ "192.168.1.1" ]; + networking.defaultGateway = { + address = "192.168.1.1"; + interface = "enp2s0"; + }; + + networking.hostName = "box"; # Define your hostname. + # networking.wireless.enable = true; # Enables wireless support via wpa_supplicant. + + # The global useDHCP flag is deprecated, therefore explicitly set to false here. + # Per-interface useDHCP will be mandatory in the future, so this generated config + # replicates the default behaviour. + networking.useDHCP = false; + networking.interfaces.wlp3s0.useDHCP = true; + + # Set your time zone. + time.timeZone = "Australia/Brisbane"; + + # Enable the OpenSSH daemon. + services.openssh.enable = true; + networking.firewall.allowedTCPPorts = [ 22 ]; + sound.enable = false; + + programs.gnupg.agent.enable = true; + programs.gnupg.agent.pinentryFlavor = "curses"; + programs.gnupg.agent.enableSSHSupport = true; + + # This value determines the NixOS release with which your system is to be + # compatible, in order to avoid breaking some software such as database + # servers. You should change this only after NixOS release notes say you + # should. + system.stateVersion = "19.09"; # Did you read the comment? + +} + diff --git a/hosts/box/default.nix b/hosts/box/default.nix new file mode 100644 index 00000000..469eea2d --- /dev/null +++ b/hosts/box/default.nix @@ -0,0 +1,49 @@ +{ self, pkgs, profiles, suites, ... }: +{ + imports = [ + ./configuration.nix + ] ++ suites.mossnet; + + home-manager.users.anish = { self, suites, ... }: { + imports = [ ] ++ suites.hmBase; + }; + + # For some reason this doesn't work in the profile, but does over here?? + # Something weird in the way I'm importing nixpkgs in the profile or something + services."grasp".enable = true; + services."grasp".path = "/home/anish/kitaab/grasp/grasp.wiki"; + services."grasp".user = "anish"; + + # Backups + age.secrets.borg-password.file = "${self}/secrets/borg-password.age"; + services.postgresqlBackup = { + enable = true; + databases = [ "wallabag" ]; + location = "/var/backup/postgresql"; + }; + mossnet.backup = { + enable = true; + name = "mossnet"; + paths = [ + "/var/lib/taskserver" # taskwarrior + "/var/www/shaarli-config" # sharli + "/var/backup/postgresql" # wallabag + "/var/lib/radicale" # radicale + "/home/anish/usr/drawing" # syncthing + "/home/anish/usr/nonfiction" # syncthing + "/mnt/two/postgres" # sealight postgres backups TODO remove once moved to capsul + ]; + # seafile + }; + + age.secrets.box-wg.file = "${self}/secrets/box-wg.age"; + age.secrets.box-wg.owner = "anish"; + mossnet.wg = { + enable = true; + ips = [ "10.0.69.4/24" ]; + privateKeyFile = "/run/agenix/box-wg"; + }; + services.syncthing.guiAddress = "0.0.0.0:8384"; # public syncthing + + system.stateVersion = "19.09"; +} diff --git a/hosts/box/hardware-configuration.nix b/hosts/box/hardware-configuration.nix new file mode 100644 index 00000000..dd526bfb --- /dev/null +++ b/hosts/box/hardware-configuration.nix @@ -0,0 +1,52 @@ +# Do not modify this file! It was generated by ‘nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ + (modulesPath + "/installer/scan/not-detected.nix") + ]; + + boot.initrd.availableKernelModules = [ "xhci_pci" "ahci" "thunderbolt" "uas" "usb_storage" "sd_mod" ]; + boot.initrd.kernelModules = [ "dm-snapshot" ]; + boot.kernelModules = [ "kvm-intel" ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { + device = "/dev/disk/by-uuid/ade0752d-84d3-4e39-865b-9027ba2d5c67"; + fsType = "ext4"; + }; + + fileSystems."/boot/efi" = + { + device = "/dev/disk/by-uuid/1715-278E"; + fsType = "vfat"; + }; + + fileSystems."/mnt/one" = + { + device = "/dev/disk/by-uuid/0f857c6e-509d-436f-9e78-bc25f1b0d23b"; + fsType = "ext4"; + }; + + fileSystems."/mnt/two" = + { + device = "/dev/disk/by-uuid/5bc894bf-ed87-4c30-aab4-87e154e0cd08"; + fsType = "ext4"; + }; + + fileSystems."/mnt/three" = + { + device = "/dev/disk/by-uuid/0be3ded1-9c8b-40aa-94ca-dc2297d5988e"; + fsType = "ext4"; + }; + + swapDevices = + [{ device = "/dev/disk/by-uuid/b790abb4-ba5f-4476-8f09-b0fc575414aa"; }]; + + powerManagement.cpuFreqGovernor = lib.mkDefault "powersave"; + hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware; +} diff --git a/hosts/cube/configuration.nix b/hosts/cube/configuration.nix new file mode 100644 index 00000000..25907985 --- /dev/null +++ b/hosts/cube/configuration.nix @@ -0,0 +1,34 @@ +{ config, pkgs, ... }: + +{ + imports = + [ + # Include the results of the hardware scan. + ./hardware-configuration.nix + ]; + + boot.loader.grub.enable = true; + boot.loader.grub.version = 2; + boot.loader.grub.device = "/dev/vda"; # or "nodev" for efi only + + networking.hostName = "cube"; # Define your hostname. + time.timeZone = "Australia/Brisbane"; + + networking.useDHCP = false; + networking.interfaces.ens3.useDHCP = true; + i18n.defaultLocale = "en_US.UTF-8"; + + environment.systemPackages = with pkgs; [ + vim + gitAndTools.gitFull + ]; + + # This value determines the NixOS release from which the default + # settings for stateful data, like file locations and database versions + # on your system were taken. It‘s perfectly fine and recommended to leave + # this value at the release version of the first install of this system. + # Before changing this value read the documentation for this option + # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html). + system.stateVersion = "21.11"; # Did you read the comment? +} + diff --git a/hosts/cube/default.nix b/hosts/cube/default.nix new file mode 100644 index 00000000..61ea5af7 --- /dev/null +++ b/hosts/cube/default.nix @@ -0,0 +1,10 @@ +{ profiles, suites, ... }: +{ + imports = [ + ./configuration.nix + ] ++ suites.cube; + + home-manager.users.anish = { self, suites, ... }: { + imports = [ ] ++ suites.hmBase; + }; +} diff --git a/hosts/cube/hardware-configuration.nix b/hosts/cube/hardware-configuration.nix new file mode 100644 index 00000000..323fc578 --- /dev/null +++ b/hosts/cube/hardware-configuration.nix @@ -0,0 +1,29 @@ +# Do not modify this file! It was generated by ‘nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ (modulesPath + "/profiles/qemu-guest.nix") + ]; + + boot.initrd.availableKernelModules = [ "ata_piix" "uhci_hcd" "virtio_pci" "sr_mod" "virtio_blk" ]; + boot.initrd.kernelModules = [ ]; + boot.kernelModules = [ ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { device = "/dev/disk/by-uuid/9233d8be-539f-43c8-9b83-84b5b4d72a93"; + fsType = "ext4"; + }; + + fileSystems."/boot" = + { device = "/dev/disk/by-uuid/E00D-9070"; + fsType = "vfat"; + }; + + swapDevices = [ ]; + + hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware; +} diff --git a/hosts/curve/configuration.nix b/hosts/curve/configuration.nix new file mode 100644 index 00000000..6cf0cbc7 --- /dev/null +++ b/hosts/curve/configuration.nix @@ -0,0 +1,50 @@ +{ + imports = [ ./hardware-configuration.nix ]; + boot.loader.grub.enable = true; + boot.loader.grub.version = 2; + # Define on which hard drive you want to install Grub. + boot.loader.grub.device = "/dev/sda"; # or "nodev" for efi only + + # Minimal list of modules to use the EFI system partition and the YubiKey + boot.initrd.kernelModules = [ "vfat" "nls_cp437" "nls_iso8859-1" "usbhid" ]; + + # Enable support for the YubiKey PBA + boot.initrd.luks.yubikeySupport = true; + + # Configuration to use your Luks device + boot.initrd.luks.devices = { + "crypthome" = { + device = "/dev/sda2"; + preLVM = true; # You may want to set this to false if you need to start a network service first + yubikey = { + slot = 2; + twoFactor = true; # Set to false if you did not set up a user password. + storage = { + device = "/dev/sda1"; + }; + }; + }; + }; + networking.hostName = "curve"; + #networking.wireless.enable = true; # Enables wireless support via wpa_supplicant. + + time.timeZone = "Australia/Brisbane"; + + networking.useDHCP = false; + networking.interfaces.enp0s31f6.useDHCP = true; + networking.interfaces.wlp3s0.useDHCP = true; + networking.wireless.enable = true; + networking.wireless.interfaces = [ "wlp3s0" ]; + networking.wireless.userControlled.enable = true; + + # Select internationalisation properties. + i18n.defaultLocale = "en_US.UTF-8"; + # console = { + # font = "Lat2-Terminus16"; + # keyMap = "us"; + # }; + + sound.enable = true; + + services.xserver.libinput.enable = true; +} diff --git a/hosts/curve/curve.nix b/hosts/curve/curve.nix new file mode 100644 index 00000000..a0ce8ac2 --- /dev/null +++ b/hosts/curve/curve.nix @@ -0,0 +1,16 @@ +{ profiles, suites, ... }: +{ + imports = [ + profiles.core + profiles.users.anish + profiles.hardware.curve # how else to deal with hardware? + ]; + + bud.enable = true; + + # Speed up boot by removing dependency on network + systemd = { + targets.network-online.wantedBy = pkgs.lib.mkForce [ ]; # Normally ["multi-user.target"] + services.NetworkManager-wait-online.wantedBy = pkgs.lib.mkForce [ ]; # Normally ["network-online.target"] + }; +} diff --git a/hosts/curve/default.nix b/hosts/curve/default.nix new file mode 100644 index 00000000..0508ca9d --- /dev/null +++ b/hosts/curve/default.nix @@ -0,0 +1,152 @@ +{ self, profiles, suites, ... }: +{ + imports = [ + ./configuration.nix + profiles.mossnet-hosts + ] ++ suites.curve; + + home-manager.users.anish = { suites, ... }: { + imports = suites.gui; + }; + + programs.gnupg.agent.pinentryFlavor = "gnome3"; + + fileSystems."/mnt/ftp" = { + device = "192.168.1.240:/home/ftp"; + fsType = "nfs"; + options = [ "x-systemd.automount" "noauto" "x-systemd.idle-timeout=600" ]; + }; + + fileSystems."/mnt/tv" = { + device = "192.168.1.240:/mnt/three/tv"; + fsType = "nfs"; + options = [ "x-systemd.automount" "noauto" "x-systemd.idle-timeout=600" ]; + }; + + fileSystems."/mnt/movies" = { + device = "192.168.1.240:/mnt/three/movies"; + fsType = "nfs"; + options = [ "x-systemd.automount" "noauto" "x-systemd.idle-timeout=600" ]; + }; + + boot.supportedFilesystems = [ "ntfs" ]; + + # lazy enable of ports necessary for KDE connect which is installed via cli home profile (for some reason?) + networking.firewall = { + allowedTCPPortRanges = [{ from = 1714; to = 1764; }]; + allowedUDPPortRanges = [{ from = 1714; to = 1764; }]; + }; + + age.secrets.curve-wg.file = "${self}/secrets/curve-wg.age"; + age.secrets.curve-wg.owner = "anish"; + mossnet.wg = { + enable = true; + ips = [ "10.0.69.2/24" ]; + privateKeyFile = "/run/agenix/curve-wg"; + }; + + age.secrets.borg-password.file = "${self}/secrets/borg-password.age"; + mossnet.backup = { + enable = true; + name = "curve"; + paths = [ "/home/anish" ]; + }; + + # enable adb + # TODO move this (it's for KaiOS WebIDE devShell?) + programs.adb.enable = true; + #virtualisation.docker.enable = true; + boot.blacklistedKernelModules = [ "qcserial" ]; + # Used for packer Capsul + users.users.anish.extraGroups = [ "adbusers" "wheel" "plugdev" "libvertd" ]; + virtualisation.libvirtd.enable = true; + hardware.keyboard.zsa.enable = true; + services.udev.extraRules = '' + # Qualcomm EDL + SUBSYSTEMS=="usb", ATTRS{idVendor}=="05c6", ATTRS{idProduct}=="9008", MODE="0666", GROUP="plugdev" + + # Qualcomm Memory Debug + SUBSYSTEMS=="usb", ATTRS{idVendor}=="05c6", ATTRS{idProduct}=="9006", MODE="0666", GROUP="plugdev" + + # Atmel DFU + ### ATmega16U2 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2fef", TAG+="uaccess" + ### ATmega32U2 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ff0", TAG+="uaccess" + ### ATmega16U4 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ff3", TAG+="uaccess" + ### ATmega32U4 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ff4", TAG+="uaccess" + ### AT90USB64 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ff9", TAG+="uaccess" + ### AT90USB162 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ffa", TAG+="uaccess" + ### AT90USB128 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2ffb", TAG+="uaccess" + + # Input Club + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1c11", ATTRS{idProduct}=="b007", TAG+="uaccess" + + # STM32duino + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1eaf", ATTRS{idProduct}=="0003", TAG+="uaccess" + # STM32 DFU + SUBSYSTEMS=="usb", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="df11", TAG+="uaccess" + + # BootloadHID + SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05df", TAG+="uaccess" + + # USBAspLoader + SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05dc", TAG+="uaccess" + + # ModemManager should ignore the following devices + # Atmel SAM-BA (Massdrop) + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="6124", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + + # Caterina (Pro Micro) + ## pid.codes shared PID + ### Keyboardio Atreus 2 Bootloader + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2302", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ## Spark Fun Electronics + ### Pro Micro 3V3/8MHz + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1b4f", ATTRS{idProduct}=="9203", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ### Pro Micro 5V/16MHz + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1b4f", ATTRS{idProduct}=="9205", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ### LilyPad 3V3/8MHz (and some Pro Micro clones) + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1b4f", ATTRS{idProduct}=="9207", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ## Pololu Electronics + ### A-Star 32U4 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="1ffb", ATTRS{idProduct}=="0101", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ## Arduino SA + ### Leonardo + SUBSYSTEMS=="usb", ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0036", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ### Micro + SUBSYSTEMS=="usb", ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0037", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ## Adafruit Industries LLC + ### Feather 32U4 + SUBSYSTEMS=="usb", ATTRS{idVendor}=="239a", ATTRS{idProduct}=="000c", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ### ItsyBitsy 32U4 3V3/8MHz + SUBSYSTEMS=="usb", ATTRS{idVendor}=="239a", ATTRS{idProduct}=="000d", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ### ItsyBitsy 32U4 5V/16MHz + SUBSYSTEMS=="usb", ATTRS{idVendor}=="239a", ATTRS{idProduct}=="000e", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ## dog hunter AG + ### Leonardo + SUBSYSTEMS=="usb", ATTRS{idVendor}=="2a03", ATTRS{idProduct}=="0036", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + ### Micro + SUBSYSTEMS=="usb", ATTRS{idVendor}=="2a03", ATTRS{idProduct}=="0037", TAG+="uaccess", ENV{ID_MM_DEVICE_IGNORE}="1" + + # hid_listen + KERNEL=="hidraw*", MODE="0660", GROUP="plugdev", TAG+="uaccess", TAG+="udev-acl" + + # hid bootloaders + ## QMK HID + SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2067", TAG+="uaccess" + ## PJRC's HalfKay + SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="0478", TAG+="uaccess" + ''; + + # enable wireguard tunnel + # privKey = "/run/secrets/curve-wg"; -> local config + # publicKey = "..."; -> shipped to server config + # IP = "10.0.69.2"; -> shipped to both configs + system.stateVersion = "22.05"; +} diff --git a/hosts/curve/hardware-configuration.nix b/hosts/curve/hardware-configuration.nix new file mode 100644 index 00000000..e855c5b3 --- /dev/null +++ b/hosts/curve/hardware-configuration.nix @@ -0,0 +1,47 @@ +# Do not modify this file! It was generated by ‘nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ (modulesPath + "/installer/scan/not-detected.nix") + ]; + + boot.initrd.availableKernelModules = [ "xhci_pci" "ahci" "usb_storage" "usbhid" "sd_mod" "rtsx_pci_sdmmc" ]; + boot.initrd.kernelModules = [ "dm-snapshot" ]; + boot.kernelModules = [ "kvm-intel" ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { device = "/dev/disk/by-uuid/74ba39ee-35cd-4b87-9ee9-651384fa55bd"; + fsType = "btrfs"; + options = [ "subvol=root" ]; + }; + + fileSystems."/home" = + { device = "/dev/disk/by-uuid/74ba39ee-35cd-4b87-9ee9-651384fa55bd"; + fsType = "btrfs"; + options = [ "subvol=home" ]; + }; + + fileSystems."/boot" = + { device = "/dev/disk/by-uuid/87DA-98E7"; + fsType = "vfat"; + }; + + swapDevices = + [ { device = "/dev/disk/by-uuid/c36e3ba9-8eee-4fbf-837c-7e1cfda33f09"; } + ]; + + # Enables DHCP on each ethernet and wireless interface. In case of scripted networking + # (the default) this is the recommended approach. When using systemd-networkd it's + # still possible to use this option, but it's recommended to use it in conjunction + # with explicit per-interface declarations with `networking.interfaces..useDHCP`. + networking.useDHCP = lib.mkDefault true; + # networking.interfaces.enp0s31f6.useDHCP = lib.mkDefault true; + # networking.interfaces.wlp3s0.useDHCP = lib.mkDefault true; + + powerManagement.cpuFreqGovernor = lib.mkDefault "powersave"; + hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware; +} diff --git a/hosts/curve/hardware.bak b/hosts/curve/hardware.bak new file mode 100644 index 00000000..9b8a0228 --- /dev/null +++ b/hosts/curve/hardware.bak @@ -0,0 +1,38 @@ +# Do not modify this file! It was generated by ‘nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ (modulesPath + "/installer/scan/not-detected.nix") + ]; + + boot.initrd.availableKernelModules = [ "xhci_pci" "ahci" "usbhid" "usb_storage" "sd_mod" "rtsx_pci_sdmmc" ]; + boot.initrd.kernelModules = [ "dm-snapshot" ]; + boot.kernelModules = [ ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { device = "/dev/disk/by-uuid/6ee9d430-1b1b-4e39-bced-606145570a78"; + fsType = "btrfs"; + options = [ "subvol=root" ]; + }; + + fileSystems."/home" = + { device = "/dev/disk/by-uuid/6ee9d430-1b1b-4e39-bced-606145570a78"; + fsType = "btrfs"; + options = [ "subvol=home" ]; + }; + + fileSystems."/boot" = + { device = "/dev/disk/by-uuid/AD0C-92EF"; + fsType = "vfat"; + }; + + swapDevices = + [ { device = "/dev/disk/by-uuid/5486bd9f-6826-4ac7-b09b-8768a35c331f"; } + ]; + + powerManagement.cpuFreqGovernor = lib.mkDefault "powersave"; +} diff --git a/hosts/helix/configuration.nix b/hosts/helix/configuration.nix new file mode 100644 index 00000000..89b803fb --- /dev/null +++ b/hosts/helix/configuration.nix @@ -0,0 +1,36 @@ +{ config, pkgs, ... }: +{ + imports = + [ + # Include the results of the hardware scan. + ./hardware-configuration.nix + ]; + + # Use the GRUB 2 boot loader. + boot.loader.grub.enable = true; + boot.loader.grub.version = 2; + boot.loader.grub.device = "/dev/vda"; # or "nodev" for efi only + + networking.hostName = "helix"; # Define your hostname. + + networking.useDHCP = false; + networking.interfaces.ens3.useDHCP = true; + + # Configure network proxy if necessary + # networking.proxy.default = "http://user:password@proxy:port/"; + # networking.proxy.noProxy = "127.0.0.1,localhost,internal.domain"; + + # Enable the OpenSSH daemon. + services.openssh.enable = true; + services.openssh.passwordAuthentication = false; + services.openssh.permitRootLogin = "no"; + sound.enable = false; + + # Define a user account. Don't forget to set a password with ‘passwd’. + # This value determines the NixOS release with which your system is to be + # compatible, in order to avoid breaking some software such as database + # servers. You should change this only after NixOS release notes say you + # should. + system.stateVersion = "22.05"; # Did you read the comment? +} + diff --git a/hosts/helix/default.nix b/hosts/helix/default.nix new file mode 100644 index 00000000..ce4fddac --- /dev/null +++ b/hosts/helix/default.nix @@ -0,0 +1,35 @@ +{ self, profiles, suites, ... }: +{ + imports = [ + ./configuration.nix + ] ++ suites.sealight; + + home-manager.users.anish = { self, suites, ... }: { + imports = [ ] ++ suites.hmBase; + }; + + # Capsul specific + users.users.cyberian = { + isNormalUser = true; + extraGroups = [ "wheel" ]; + }; + + mossnet.wg = { + enable = true; + ips = [ "10.0.69.5/24" ]; + privateKeyFile = "/home/anish/wg/wg-priv"; + }; + + # mossnet.backup = { + # enable = false; + # name = "sealight"; + # paths = [ "/var/backup/postgresql" ]; + # }; + + # age.secrets.borg-password.file = "${self}/secrets/borg-password.age"; + # services.postgresqlBackup = { + # enable = false; + # databases = [ "matrix-synapse" "gitea" ]; + # location = "/var/backup/postgresql"; + # }; +} diff --git a/hosts/helix/hardware-configuration.nix b/hosts/helix/hardware-configuration.nix new file mode 100644 index 00000000..a30f4ecc --- /dev/null +++ b/hosts/helix/hardware-configuration.nix @@ -0,0 +1,26 @@ +# Do not modify this file! It was generated by ‘nixos-generate-config’ +# and may be overwritten by future invocations. Please make changes +# to /etc/nixos/configuration.nix instead. +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ + (modulesPath + "/profiles/qemu-guest.nix") + ]; + + boot.initrd.availableKernelModules = [ "ata_piix" "floppy" "virtio_pci" "sr_mod" "virtio_blk" ]; + boot.initrd.kernelModules = [ ]; + boot.kernelModules = [ ]; + boot.extraModulePackages = [ ]; + + fileSystems."/" = + { + device = "/dev/disk/by-uuid/7c560634-d545-41cc-b375-42ce3037fd73"; + fsType = "ext4"; + }; + + swapDevices = [ ]; + + hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware; +} diff --git a/install-encrypted.sh b/install-encrypted.sh new file mode 100755 index 00000000..e044cd56 --- /dev/null +++ b/install-encrypted.sh @@ -0,0 +1,121 @@ +# Setup +# Presumes pre-formatted harddrives +BOOT=/dev/sda1 +DISK=/dev/sda2 + +dd if=/dev/urandom of=./keyfile0.bin bs=1024 count=4 +dd if=/dev/urandom of=./keyfile1.bin bs=1024 count=4 + +echo "Creating LUKS partitions..." +# Enter the passphrase which is used to unlock disk. You will enter this in grub on every boot +cryptsetup luksFormat --type luks1 -c aes-xts-plain64 -s 256 -h sha512 $DISK +# Add a second key which will be used by nixos. You will need to enter the pasphrase from previous step +cryptsetup luksAddKey $DISK keyfile0.bin +cryptsetup luksOpen $DISK crypted-nixos -d keyfile0.bin + +# Create the LVM +echo "Creating LVM partitions..." +pvcreate /dev/mapper/crypted-nixos +vgcreate vg /dev/mapper/crypted-nixos +lvcreate -L 4G -n swap vg +lvcreate -l '100%FREE' -n root vg + +# Format the disks +echo "Formatting disks..." +mkfs.fat -F 32 $BOOT +mkswap -L swap /dev/vg/swap +mkfs.ext4 -L root /dev/vg/root +# mkfs.ext4 -L data /dev/mapper/crypted-data + +echo "Mounting drives..." +mount /dev/vg/root /mnt +mkdir -p /mnt/boot/efi +mount $BOOT /mnt/boot/efi +swapon /dev/vg/swap + +# Copy the keys + +mkdir -p /mnt/etc/secrets/initrd/ +cp keyfile0.bin keyfile1.bin /mnt/etc/secrets/initrd +chmod 000 /mnt/etc/secrets/initrd/keyfile*.bin + +# Generate and edit configuration + +echo "Generating NixOS config..." +nixos-generate-config --root /mnt + +# TODO: neds to get the uuid of each of the disks +# UUID=$(blkid) +echo "Extending NixOS config..." +cat >> /mnt/etc/nixos/configuration.nix <<'endmsg' + boot.loader.efi.canTouchEfiVariables = true; + boot.loader.efi.efiSysMountPoint = "/boot/efi"; + boot.loader.grub = { + enable = true; + device = "nodev"; + version = 2; + efiSupport = true; + enableCryptodisk = true; + }; + + boot.initrd = { + luks.devices."root" = { + # UPDATE ME + device = "/dev/disk/by-uuid/a8b302cf-5296-4a2e-a7ba-707e6fa75123"; # UUID for /dev/nvme01np2 + preLVM = true; + keyFile = "/keyfile0.bin"; + allowDiscards = true; + }; + secrets = { + # Create /mnt/etc/secrets/initrd directory and copy keys to it + "keyfile0.bin" = "/etc/secrets/initrd/keyfile0.bin"; + "keyfile1.bin" = "/etc/secrets/initrd/keyfile1.bin"; + }; + }; + + # Data mount + # This is all wrong for box for now + # fileSystems."/data" = { + # device = "/dev/disk/by-uuid/79630267-5766-4c7d-85a5-1d5f1dcd58ad"; # UUID for /dev/mapper/crypted-data + # encrypted = { + # enable = true; + # label = "crypted-data"; + # blkDev = "/dev/disk/by-uuid/3476cb09-b3c4-4301-9ec9-84f60f32828a"; # UUID for /dev/sda1 + # keyFile = "/keyfile1.bin"; + # }; + # }; + + time.timeZone = "Australia/Brisbane"; + + networking.useDHCP = false; + + nix = { + package = pkgs.nixUnstable; + extraOptions = '' + experimental-features = nix-command flakes + ''; + }; + + users.users.anish = { + isNormalUser = true; + hashedPassword = "MVHHpy9gbe3ow"; + extraGroups = [ "wheel" ]; # Enable ‘sudo’ for the user. + openssh.authorizedKeys.keys = [ "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDM0Zvei46x/yZl/IeBCq6+IYQQ0avulzVyBysF9cPigZMCybWRV7IEU+E3k9t6JrbdbdGfJkcZIWmsWDdKS8W8mBnZpVoT0ffLynu8JQ/TKdGm4Qv6bgUeKNrGsNv0ZPs2CDaGSLj0oJfRF7Ko10tcLP0vW+yujrh+y6TH/vVzJioaV4TGvtCUpn+wEQah9ROwPQLUUofsSWdnRsDJ/gp37zXWs4l5wyjSKtP3O9RZUP7kBekbSqEgSXiTk0oUQSVqIWl9NDiP6onk/gSOjXsR/JPqsSN/XI/c/yj6gyY0f51Ru2D7iBxuMJIJcWV+rU6coIj+ULcQWLzt/7TI8jq5AOOzI/ll4zbL24Eo84Rz+TP9tvMMhDZ0VaMN22AJ8qQEjc5P09tWKsX7Jg39XelyV1jHXncE4yvIE9F4RSCHzWCeKeXakizQNuzSaxTxIExRFYHjNW5bR6+3MTGwVrEIXU+qML+0yFTR86MT+tdY5AreAJQLwbog79O1NupeXJE= anish@curve" ]; + }; + security.sudo.wheelNeedsPassword = false; # needed for deploy-rs + + services.openssh.enable = true; + + # This value determines the NixOS release from which the default + # settings for stateful data, like file locations and database versions + # on your system were taken. It‘s perfectly fine and recommended to leave + # this value at the release version of the first install of this system. + # Before changing this value read the documentation for this option + # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html). + system.stateVersion = "21.05"; # Did you read the comment? +} + +endmsg + + +# sudo nixos-install diff --git a/install-simple.sh b/install-simple.sh new file mode 100644 index 00000000..fa6f7695 --- /dev/null +++ b/install-simple.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash + +# partition the files yourself sorry + +sudo fatlabel /dev/vda1 NIXBOOT +sudo mkfs.ext4 /dev/vda2 -L NIXROOT +sudo mount /dev/disk/by-label/NIXROOT /mnt +sudo mkdir -p /mnt/boot +sudo mount /dev/disk/by-label/NIXBOOT /mnt/boot + +sudo nixos-generate-config --root /mnt +cat > /mnt/etc/nixos/configuration.nix <<'endmsg' +{ config, pkgs, ... }: + +{ + imports = + [ # Include the results of the hardware scan. + ./hardware-configuration.nix + ]; + + boot.loader.grub.enable = true; + boot.loader.grub.version = 2; + # Define on which hard drive you want to install Grub. + boot.loader.grub.device = "/dev/vda"; # or "nodev" for efi only + + # Enable Flakes + nix = { + package = pkgs.nixUnstable; + extraOptions = '' + experimental-features = nix-command flakes + ''; + }; + + time.timeZone = "Australia/Brisbane"; + + networking.useDHCP = false; + networking.interfaces.ens3.useDHCP = true; # TODO you probably want to change this + + i18n.defaultLocale = "en_US.UTF-8"; + + users.users.anish = { + isNormalUser = true; + hashedPassword = "MVHHpy9gbe3ow"; + extraGroups = [ "wheel" ]; # Enable ‘sudo’ for the user. + openssh.authorizedKeys.keys = [ "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDM0Zvei46x/yZl/IeBCq6+IYQQ0avulzVyBysF9cPigZMCybWRV7IEU+E3k9t6JrbdbdGfJkcZIWmsWDdKS8W8mBnZpVoT0ffLynu8JQ/TKdGm4Qv6bgUeKNrGsNv0ZPs2CDaGSLj0oJfRF7Ko10tcLP0vW+yujrh+y6TH/vVzJioaV4TGvtCUpn+wEQah9ROwPQLUUofsSWdnRsDJ/gp37zXWs4l5wyjSKtP3O9RZUP7kBekbSqEgSXiTk0oUQSVqIWl9NDiP6onk/gSOjXsR/JPqsSN/XI/c/yj6gyY0f51Ru2D7iBxuMJIJcWV+rU6coIj+ULcQWLzt/7TI8jq5AOOzI/ll4zbL24Eo84Rz+TP9tvMMhDZ0VaMN22AJ8qQEjc5P09tWKsX7Jg39XelyV1jHXncE4yvIE9F4RSCHzWCeKeXakizQNuzSaxTxIExRFYHjNW5bR6+3MTGwVrEIXU+qML+0yFTR86MT+tdY5AreAJQLwbog79O1NupeXJE= anish@curve" ]; + }; + security.sudo.wheelNeedsPassword = false; # needed for deploy-rs + + services.openssh.enable = true; + + # This value determines the NixOS release from which the default + # settings for stateful data, like file locations and database versions + # on your system were taken. It‘s perfectly fine and recommended to leave + # this value at the release version of the first install of this system. + # Before changing this value read the documentation for this option + # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html). + system.stateVersion = "21.11"; # Did you read the comment? +} + +endmsg + +sudo nixos-install diff --git a/install-yubikey.sh b/install-yubikey.sh new file mode 100755 index 00000000..2ddac5b9 --- /dev/null +++ b/install-yubikey.sh @@ -0,0 +1,172 @@ +rbtohex() { + ( od -An -vtx1 | tr -d ' \n' ) +} + +hextorb() { + ( tr '[:lower:]' '[:upper:]' | sed -e 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/gI'| xargs printf ) +} + +# Setup +# nix-env -i gcc-wrapper +# nix-env -i yubikey-personalization +# nix-env -i openssl +# Use nix-shell https://github.com/sgillespie/nixos-yubikey-luks/archive/master.tar.gz + +# Compile correct version of OpenSSL key derivation +cc -O3 -I$(nix-build "" --no-build-output -A openssl.dev)/include -L$(nix-build "" --no-build-output -A openssl.out)/lib $(nix eval "(with import {}; pkgs.path)")/nixos/modules/system/boot/pbkdf2-sha512.c -o ./pbkdf2-sha512 -lcrypto + +# Yubikey Setup +SLOT=2 +ykpersonalize -"$SLOT" -ochal-resp -ochal-hmac +SALT_LENGTH=16 +salt="$(dd if=/dev/random bs=1 count=$SALT_LENGTH 2>/dev/null | rbtohex)" +k_user=PASSWORDCHANGEMEPLAEASES +challenge="$(echo -n $salt | openssl dgst -binary -sha512 | rbtohex)" +response="$(ykchalresp -2 -x $challenge 2>/dev/null)" + +# Setup LUKS device +KEY_LENGTH=512 +ITERATIONS=1000000 +k_luks="$(echo -n $k_user | ./pbkdf2-sha512 $(($KEY_LENGTH / 8)) $ITERATIONS $response | rbtohex)" + +EFI_PART=/dev/sda1 +LUKS_PART=/dev/sda2 +EFI_MNT=/boot/ +mkdir -p "$EFI_MNT" +mkfs.fat -F 32 -n boot "$EFI_PART" +mount "$EFI_PART" "$EFI_MNT" +STORAGE=/crypt-storage/default +mkdir -p "$(dirname $EFI_MNT$STORAGE)" +echo -ne "$salt\n$ITERATIONS" > $EFI_MNT$STORAGE +CIPHER=aes-xts-plain64 +HASH=sha512 +echo -n "$k_luks" | hextorb | cryptsetup luksFormat --cipher="$CIPHER" --key-size="$KEY_LENGTH" --hash="$HASH" --key-file=- "$LUKS_PART" +umount "$EFI_MNT" + +# LVM Setup +LUKSROOT=crypthome +echo -n "$k_luks" | hextorb | cryptsetup luksOpen $LUKS_PART $LUKSROOT --key-file=- +pvcreate "/dev/mapper/$LUKSROOT" +VGNAME=partitions +vgcreate "$VGNAME" "/dev/mapper/$LUKSROOT" +lvcreate -L 2G -n swap "$VGNAME" +FSROOT=fsroot +lvcreate -l 100%FREE -n "$FSROOT" "$VGNAME" + +vgchange -ay +mkswap -L swap /dev/partitions/swap + +# BTRFS Setup +mkfs.btrfs -L "$FSROOT" "/dev/partitions/$FSROOT" + +# incase the above breaks +#mkdir /mnt-root +#touch /mnt-root/nix-store.squashfs + +mount "/dev/partitions/$FSROOT" /mnt +cd /mnt +btrfs subvolume create root +btrfs subvolume create home +cd +umount /mnt +mount -o subvol=root "/dev/partitions/$FSROOT" /mnt +mkdir /mnt/home +mount -o subvol=home "/dev/partitions/$FSROOT" /mnt/home +mkdir /mnt/boot +mount "$EFI_PART" /mnt/boot + +swapon /dev/partitions/swap + +# Install NixOS +nixos-generate-config --root /mnt + +# Change the config +cat > /mnt/etc/nixos/configuration.nix <<'endmsg' +{ config, pkgs, ... }: + +{ + imports = + [ # Include the results of the hardware scan. + ./hardware-configuration.nix + ]; + + boot.loader.grub.enable = true; + boot.loader.grub.version = 2; + # Define on which hard drive you want to install Grub. + boot.loader.grub.device = "/dev/sda"; # or "nodev" for efi only + + # Minimal list of modules to use the EFI system partition and the YubiKey + boot.initrd.kernelModules = [ "vfat" "nls_cp437" "nls_iso8859-1" "usbhid" ]; + + # Enable support for the YubiKey PBA + boot.initrd.luks.yubikeySupport = true; + + # Configuration to use your Luks device + boot.initrd.luks.devices = { + "crypthome" = { + device = "/dev/sda2"; + preLVM = true; # You may want to set this to false if you need to start a network service first + yubikey = { + slot = 2; + twoFactor = true; # Set to false if you did not set up a user password. + storage = { + device = "/dev/sda1"; + }; + }; + }; + }; + + # Enable Flakes + nix = { + package = pkgs.nixUnstable; + extraOptions = '' + experimental-features = nix-command flakes + ''; + }; + + networking.hostName = "curve"; # Define your hostname. + networking.wireless.enable = true; # Enables wireless support via wpa_supplicant. + + time.timeZone = "Australia/Brisbane"; + + networking.useDHCP = false; + networking.interfaces.enp0s31f6.useDHCP = true; + networking.interfaces.wlp3s0.useDHCP = true; + + # Select internationalisation properties. + i18n.defaultLocale = "en_US.UTF-8"; + # console = { + # font = "Lat2-Terminus16"; + # keyMap = "us"; + # }; + + services.xserver.layout = "us,dvorak"; + + sound.enable = true; + hardware.pulseaudio.enable = true; + + services.xserver.libinput.enable = true; + + # Hmmm maybe somewhere else? + users.users.anish = { + isNormalUser = true; + extraGroups = [ "wheel" ]; + }; + + # Enable the OpenSSH daemon. + # services.openssh.enable = true; + + # This value determines the NixOS release from which the default + # settings for stateful data, like file locations and database versions + # on your system were taken. It‘s perfectly fine and recommended to leave + # this value at the release version of the first install of this system. + # Before changing this value read the documentation for this option + # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html). + system.stateVersion = "21.05"; # Did you read the comment? +} + +endmsg + +cd /mnt +nixos-install --root /mnt +passwd diff --git a/lib/compat/default.nix b/lib/compat/default.nix new file mode 100644 index 00000000..9d0c2837 --- /dev/null +++ b/lib/compat/default.nix @@ -0,0 +1,14 @@ +let + rev = "e7e5d481a0e15dcd459396e55327749989e04ce0"; + flake = (import + ( + fetchTarball { + url = "https://github.com/edolstra/flake-compat/archive/${rev}.tar.gz"; + sha256 = "0zd3x46fswh5n6faq4x2kkpy6p3c6j593xbdlbsl40ppkclwc80x"; + } + ) + { + src = ../../.; + }); +in +flake diff --git a/lib/compat/nixos/default.nix b/lib/compat/nixos/default.nix new file mode 100644 index 00000000..e4e0e68a --- /dev/null +++ b/lib/compat/nixos/default.nix @@ -0,0 +1,10 @@ +{ ... }: +let + inherit (default.inputs.nixos) lib; + + host = configs.${hostname} or configs.NixOS; + configs = default.nixosConfigurations; + default = (import ../.).defaultNix; + hostname = lib.fileContents /etc/hostname; +in +host diff --git a/lib/default.nix b/lib/default.nix new file mode 100644 index 00000000..2356e1f0 --- /dev/null +++ b/lib/default.nix @@ -0,0 +1,2 @@ +{ lib }: +lib.makeExtensible (self: { }) diff --git a/modules/backup.nix b/modules/backup.nix new file mode 100644 index 00000000..3980262d --- /dev/null +++ b/modules/backup.nix @@ -0,0 +1,53 @@ +# TODO: +# This currently works on a per host basis, and the host file has to define all the locations it wants to back up. +# Ideally, this would create a job for each profile instead, so the backup strategy is included in the profile regardless of host +{ config, lib, pkgs, ... }: +with lib; +let + cfg = config.mossnet.backup; +in +{ + options = { + mossnet.backup = { + enable = mkEnableOption "Backup module using borg for Anish's computer nursery"; + name = lib.mkOption { + type = types.str; + default = { }; + example = literalExample '' + mossnet + ''; + description = '' + name for the backup operator + ''; + }; + paths = lib.mkOption { + type = with types; listOf str; + default = { }; + example = literalExample '' + [ "/home/anish/usr" ]; + ''; + description = '' + A list of folders to backup + ''; + }; + }; + }; + + config = mkIf cfg.enable { + services.borgbackup.jobs = { + "${cfg.name}" = { + paths = cfg.paths; + doInit = true; + repo = "20779@hk-s020.rsync.net:${cfg.name}"; + encryption = { + mode = "repokey-blake2"; + passCommand = "cat /run/agenix/borg-password"; + }; + environment = { BORG_RSH = "ssh -i /root/borg/borg-key"; }; # YOU NEED TO PUT THIS HERE MANUALLY + compression = "auto,lzma"; + startAt = "daily"; + extraArgs = "--remote-path=borg1"; + }; + }; + }; +} diff --git a/modules/gonic.nix b/modules/gonic.nix new file mode 100644 index 00000000..f3a32fca --- /dev/null +++ b/modules/gonic.nix @@ -0,0 +1,109 @@ +{ config, lib, pkgs, ... }: + +with lib; + +let + cfg = config.services.gonic; + configFile = "/etc/gonic/config"; + dataFolder = "/var/lib/gonic"; +in { + options = { + + services.gonic = { + enable = mkEnableOption "Gonic music server and streamer"; + + settings = lib.mkOption { + type = types.str; + default = {}; + example = literalExample '' + music-path + podcast-path + cache-path + ''; + description = '' + Configuration for Gonic, see for supported values. + ''; + }; + + user = mkOption { + type = types.str; + default = "gonic"; + description = "User account under which gonic runs."; + }; + + group = mkOption { + type = types.str; + default = "gonic"; + description = "Group account under which gonic runs."; + }; + + }; + }; + + config = mkIf cfg.enable { + + environment.etc."gonic/config".text = cfg.settings; + + systemd.services.gonic = { + description = "gonic Music Server and Streamer compatible with Subsonic/Airsonic"; + after = [ "remote-fs.target" "network.target" ]; + wantedBy = [ "multi-user.target" ]; + environment = { + #GONIC_MUSIC_PATH + #GONIC_PODCAST_PATH + #GONIC_CACHE_PATH + #GONIC_DB_PATH + GONIC_SCAN_INTERVAL="800"; + #... + }; + serviceConfig = { + ExecStart = "${pkgs.gonic}/bin/gonic -config-path /etc/gonic/config"; + WorkingDirectory = dataFolder; + TimeoutStopSec = "20"; + KillMode = "process"; + Restart = "on-failure"; + RestartSec = "10"; + User = cfg.user; + Group = cfg.group; + DevicePolicy = "closed"; + NoNewPrivileges= " yes"; + PrivateTmp = "yes"; + PrivateUsers = "yes"; + ProtectControlGroups = "yes"; + ProtectKernelModules = "yes"; + ProtectKernelTunables = "yes"; + RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6"; + RestrictNamespaces = "yes"; + RestrictRealtime = "yes"; + SystemCallFilter = "~@clock @debug @module @mount @obsolete @privileged @reboot @setuid @swap"; + ReadWritePaths = dataFolder; + StateDirectory = baseNameOf dataFolder; + }; + }; + + users.users = optionalAttrs (cfg.user == "gonic") ({ + gonic = { + description = "gonic service user"; + name = cfg.user; + group = cfg.group; + isSystemUser = true; + }; + }); + + users.groups = optionalAttrs (cfg.group == "gonic") ({ + gonic = {}; + }); + + services.nginx.virtualHosts."music.mossnet.lan" = { + enableACME = false; + forceSSL = false; + + locations."/" = { + extraConfig = '' + proxy_pass http://localhost:4747/; + proxy_set_header X-Forwarded-Host $host; + ''; + }; + }; + }; +} diff --git a/modules/heisenbridge.nix.bak b/modules/heisenbridge.nix.bak new file mode 100644 index 00000000..3a74bb47 --- /dev/null +++ b/modules/heisenbridge.nix.bak @@ -0,0 +1,112 @@ +{ config, lib, pkgs, ... }: with lib; let + cfg = config.services.heisenbridge; + + heisenbridgeAppserviceConfig = { + id = "heisenbridge"; + url = "http://${cfg.listenAddress}:${toString cfg.listenPort}"; + as_token = cfg.appServiceToken; + hs_token = cfg.homeserverToken; + rate_limited = false; + sender_localpart = cfg.senderLocalpart; + namespaces = { + users = [{ regex = "@irc_.*"; exclusive = true; }]; + aliases = [ ]; + rooms = [ ]; + }; + }; + + heisenbridgeConfigYaml = pkgs.writeText "heisenbridge.yaml" ( + generators.toYAML { } heisenbridgeAppserviceConfig); +in +{ + options = { + services.heisenbridge = { + enable = mkEnableOption "heisenbridge, a bouncer-style Matrix IRC bridge."; + identd.enable = mkEnableOption "identd for heisenbridge" // { + default = true; + }; + homeserver = mkOption { + type = types.str; + default = "http://localhost:8008"; + description = "The URL of the Matrix homeserver."; + }; + listenAddress = mkOption { + type = types.str; + default = "127.0.0.1"; + description = "The address for heisenbridge to listen on."; + }; + listenPort = mkOption { + type = types.int; + default = 9898; + description = "The port for heisenbridge to listen on."; + }; + senderLocalpart = mkOption { + type = types.str; + default = "heisenbridge"; + description = "The localpart of the heisenbridge admin bot's username."; + }; + ownerId = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + The owner MXID (for example, @user:homeserver) of the bridge. If + unspecified, the first talking local user will claim the bridge. + ''; + }; + appServiceToken = mkOption { + type = types.str; + description = '' + This is the token that the app service should use as its access_token + when using the Client-Server API. This can be anything you want. + ''; + }; + homeserverToken = mkOption { + type = types.str; + description = '' + This is the token that the homeserver will use when sending requests + to the app service. This can be anything you want. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + meta.maintainers = [ maintainers.sumnerevans ]; + + services.matrix-synapse.app_service_config_files = [ + heisenbridgeConfigYaml + ]; + + # Create a user for heisenbridge. + users.users.heisenbridge = { + group = "heisenbridge"; + isSystemUser = true; + }; + users.groups.heisenbridge = { }; + + # Open ports for identd. + networking.firewall.allowedTCPPorts = mkIf cfg.identd.enable [ 113 ]; + + systemd.services.heisenbridge = { + description = "Heisenbridge Matrix IRC bridge"; + after = [ "matrix-synapse.service" ]; + wantedBy = [ "multi-user.target" ]; + serviceConfig = { + ExecStart = '' + ${pkgs.heisenbridge}/bin/heisenbridge \ + --config ${heisenbridgeConfigYaml} \ + --verbose --verbose \ + --listen-address ${cfg.listenAddress} \ + --listen-port ${toString cfg.listenPort} \ + --uid heisenbridge \ + --gid heisenbridge \ + ${optionalString cfg.identd.enable "--identd"} \ + ${optionalString (cfg.ownerId != null) "--owner ${cfg.ownerId}"} \ + ${cfg.homeserver} + ''; + Restart = "on-failure"; + }; + }; + }; +} + diff --git a/modules/hm-system-defaults.nix b/modules/hm-system-defaults.nix new file mode 100644 index 00000000..7b442a61 --- /dev/null +++ b/modules/hm-system-defaults.nix @@ -0,0 +1,11 @@ +{ config, ... }: { + home-manager.sharedModules = [ + { + home.sessionVariables = { + inherit (config.environment.sessionVariables) NIX_PATH; + }; + xdg.configFile."nix/registry.json".text = + config.environment.etc."nix/registry.json".text; + } + ]; +} diff --git a/modules/nix-path.nix b/modules/nix-path.nix new file mode 100644 index 00000000..273f67a6 --- /dev/null +++ b/modules/nix-path.nix @@ -0,0 +1,7 @@ +{ channel, inputs, ... }: { + nix.nixPath = [ + "nixpkgs=${channel.input}" + "nixos-config=${../lib/compat/nixos}" + "home-manager=${inputs.home}" + ]; +} diff --git a/modules/wallabag.nix b/modules/wallabag.nix new file mode 100644 index 00000000..0c7c922c --- /dev/null +++ b/modules/wallabag.nix @@ -0,0 +1,200 @@ +{ config, options, lib, pkgs, ... }: + +with lib; +let + cfg = config.services.wallabag; + + poolName = "wallabag"; + + configFile = pkgs.writeTextFile { + name = "wallabag-config"; + text = cfg.conf; + destination = "/config/parameters.yml"; + }; + + appDir = pkgs.buildEnv { + name = "wallabag-app-dir"; + ignoreCollisions = true; + checkCollisionContents = false; + paths = [ configFile "${cfg.package}/app" ]; + }; + +in +{ + + options = { + + services.wallabag = { + enable = mkEnableOption "wallabag"; + + user = mkOption { + type = types.str; + default = "nginx"; + description = '' + User account under which both the update daemon and the web-application run. + ''; + }; + + dataDir = mkOption { + type = types.path; + default = "/var/lib/wallabag"; + description = '' + Data directory. + ''; + }; + + package = mkOption { + type = types.package; + default = pkgs.wallabag; + description = '' + Wallabag package to use. + ''; + }; + + hostName = mkOption { + type = types.str; + description = '' + Name of the nginx virtualhost to use and setup. + ''; + }; + + poolConfig = mkOption { + type = types.lines; + default = '' + pm = dynamic + pm.max_children = 75 + pm.start_servers = 1 + pm.min_spare_servers = 1 + pm.max_spare_servers = 20 + pm.max_requests = 500 + catch_workers_output = 1 + ''; + description = '' + Options for wallabag's PHP pool. See the documentation on php-fpm.conf for details on configuration directives. + ''; + }; + + conf = mkOption { + type = types.str; + description = '' + Contents of the wallabag configuration file (parameters.yml) + ''; + }; + }; + }; + + + config = mkIf cfg.enable { + + services.phpfpm.pools."${poolName}" = { + user = "${cfg.user}"; + group = "nginx"; + phpPackage = pkgs.php74; + settings = { + "listen.owner" = "nginx"; + "listen.group" = "nginx"; + "listen.mode" = "0600"; + "user" = "${cfg.user}"; + "group" = "nginx"; + "env[WALLABAG_DATA]" = "${cfg.dataDir}"; + "pm" = "dynamic"; + "pm.max_children" = "75"; + "pm.min_spare_servers" = "5"; + "pm.max_spare_servers" = "20"; + "pm.max_requests" = "10"; + "catch_workers_output" = "1"; + "php_admin_value[error_log]" = "/var/log/nginx/${poolName}-phpfpm-error.log"; + }; + }; + services.phpfpm.phpOptions = '' + max_execution_time = 120 + ''; + + services.nginx.enable = mkDefault true; + + services.nginx.virtualHosts."${cfg.hostName}" = { + enableACME = false; + forceSSL = false; + root = "${cfg.package}/web"; + + extraConfig = '' + add_header X-Frame-Options SAMEORIGIN; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + ''; + + locations."/" = { + extraConfig = '' + try_files $uri /app.php$is_args$args; + ''; + }; + + locations."/assets".root = "${cfg.dataDir}/web"; + + locations."~ ^/app\\.php(/|$)" = { + extraConfig = '' + fastcgi_pass unix:${config.services.phpfpm.pools."${poolName}".socket}; + fastcgi_split_path_info ^(.+\.php)(/.*)$; + include ${pkgs.nginx}/conf/fastcgi_params; + fastcgi_param SCRIPT_FILENAME ${cfg.package}/web/$fastcgi_script_name; + fastcgi_param DOCUMENT_ROOT ${cfg.package}/web; + fastcgi_read_timeout 120; + internal; + ''; + }; + + locations."~ /(?!app)\\.php$" = { + extraConfig = '' + return 404; + ''; + }; + }; + + systemd.services.wallabag-install = { + description = "Wallabag install service"; + wantedBy = [ "multi-user.target" ]; + before = [ "phpfpm-wallabag.service" ]; + after = [ "mysql.service" "postgresql.service" ]; + path = with pkgs; [ coreutils php74 php74Packages.composer ]; + + serviceConfig = { + User = cfg.user; + Type = "oneshot"; + RemainAfterExit = "yes"; + PermissionsStartOnly = true; + }; + + preStart = '' + mkdir -p "${cfg.dataDir}" + chown ${cfg.user}:nginx "${cfg.dataDir}" + ''; + + script = '' + echo "Setting up wallabag files in ${cfg.dataDir} ..." + cd "${cfg.dataDir}" + + rm -rf var/cache/* + rm -f app + ln -sf ${appDir} app + ln -sf ${cfg.package}/composer.{json,lock} . + + export WALLABAG_DATA="${cfg.dataDir}" + if [ ! -f installed ]; then + echo "Install file not found, installing ..." + php ${cfg.package}/bin/console --env=prod doctrine:database:create --if-not-exists --no-interaction + php ${cfg.package}/bin/console --env=prod doctrine:migrations:migrate --no-interaction + # Until https://github.com/wallabag/wallabag/issues/3662 is fixed + # yes no | php ${cfg.package}/bin/console --env=prod wallabag:install + touch installed + else + php ${cfg.package}/bin/console --env=prod doctrine:migrations:migrate --no-interaction + fi + php ${cfg.package}/bin/console --env=prod cache:clear + ''; + }; + }; + + meta = with stdenv.lib; { + maintainers = with maintainers; [ nadrieril ]; + }; +} diff --git a/modules/wireguard.nix b/modules/wireguard.nix new file mode 100644 index 00000000..5e9e9b52 --- /dev/null +++ b/modules/wireguard.nix @@ -0,0 +1,54 @@ +{ config, lib, pkgs, ... }: +with lib; +let + cfg = config.mossnet.wg; +in +{ + options = { + mossnet.wg = { + enable = mkEnableOption "Gain access to all mossnet systems through wireguard"; + ips = lib.mkOption { + type = with types; listOf str; + default = { }; + example = literalExample '' + [ "10.0.69.2/24" ]; + ''; + description = '' + The IP this machine is allowed to connect to + ''; + }; + privateKeyFile = lib.mkOption { + type = types.path; + default = { }; + example = literalExample '' + /run/agenix/wg-curve + ''; + description = '' + The private ssh key file to use to connect! + Remember set age.secrets.*.file and age.secrets.*.user + ''; + }; + }; + }; + config = mkIf cfg.enable { + networking.firewall.allowedUDPPorts = [ 60990 ]; + networking.wireguard.interfaces = { + wg0 = { + ips = cfg.ips; + listenPort = 60990; # to match firewall allowedUDPPorts (without this wg uses random port numbers) + + privateKeyFile = cfg.privateKeyFile; + peers = [ + # For a client configuration, one peer entry for the server will suffice. + { + publicKey = "c1J4p63rD3IlszugMZiki7UBV3YmDdqa3DU4UejXzAI="; + allowedIPs = [ "10.0.69.0/24" ]; + # Set this to the server IP and port. + endpoint = "149.28.163.78:60990"; # ToDo: route to endpoint not automatically configured https://wiki.archlinux.org/index.php/WireGuard#Loop_routing https://discourse.nixos.org/t/solved-minimal-firewall-setup-for-wireguard-client/7577 + persistentKeepalive = 25; + } + ]; + }; + }; + }; +} diff --git a/mount-crypted.sh b/mount-crypted.sh new file mode 100644 index 00000000..74c416b2 --- /dev/null +++ b/mount-crypted.sh @@ -0,0 +1,8 @@ +key_length=512 +iterations="$(head -n 2 /boot/crypted-storage/default)" +salt="$(head -n 1 /boot/crypted-storage/default)" +chal="$(echo -n $salt | openssl dgst -binary -sha512 | rbtohex)" +resp="$(ykchalresp -2 -x $chal 2>/dev/null)" +user_key="$(read -s)" +luks_key="$(echo -n $user_key | pbkdf2-sha512 $(($key_length / 8)) $iterations $resp | rbtohex)" +echo -n $luks_key | hextorb | sudo cryptsetup luksOpen /dev/sda2 crypted --key-file=- diff --git a/overlays/overrides.nix b/overlays/overrides.nix new file mode 100644 index 00000000..5c3ebd53 --- /dev/null +++ b/overlays/overrides.nix @@ -0,0 +1,31 @@ +channels: final: prev: { + + __dontExport = true; # overrides clutter up actual creations + + inherit (channels.latest) + cachix + dhall + discord + element-desktop + rage + nixpkgs-fmt + qutebrowser + nheko + signal-desktop + tootle + sublime-music + starship; + + + haskellPackages = prev.haskellPackages.override + (old: { + overrides = prev.lib.composeExtensions (old.overrides or (_: _: { })) (hfinal: hprev: + let version = prev.lib.replaceChars [ "." ] [ "" ] prev.ghc.version; + in + { + # same for haskell packages, matching ghc versions + inherit (channels.latest.haskell.packages."ghc${version}") + haskell-language-server; + }); + }); +} diff --git a/overlays/various-flake-fixes.nix b/overlays/various-flake-fixes.nix new file mode 100644 index 00000000..7dbfc18b --- /dev/null +++ b/overlays/various-flake-fixes.nix @@ -0,0 +1,11 @@ +final: prev: { + # Since: https://github.com/NixOS/nixpkgs/pull/126137 + nix-direnv = + if builtins.hasAttr "enableFlakes" prev.nix-direnv.override.__functionArgs + then + prev.nix-direnv.override + { + enableFlakes = true; + } + else prev.nix-direnv; +} diff --git a/pkgs/_sources/generated.nix b/pkgs/_sources/generated.nix new file mode 100644 index 00000000..71be3965 --- /dev/null +++ b/pkgs/_sources/generated.nix @@ -0,0 +1,16 @@ +# This file was generated by nvfetcher, please do not modify it manually. +{ fetchgit, fetchurl }: +{ + manix = { + pname = "manix"; + version = "d08e7ca185445b929f097f8bfb1243a8ef3e10e4"; + src = fetchgit { + url = "https://github.com/mlvzk/manix"; + rev = "d08e7ca185445b929f097f8bfb1243a8ef3e10e4"; + fetchSubmodules = false; + deepClone = false; + leaveDotGit = false; + sha256 = "1b7xi8c2drbwzfz70czddc4j33s7g1alirv12dwl91hbqxifx8qs"; + }; + }; +} diff --git a/pkgs/default.nix b/pkgs/default.nix new file mode 100644 index 00000000..924a2300 --- /dev/null +++ b/pkgs/default.nix @@ -0,0 +1,5 @@ +final: prev: { + # keep sources this first + sources = prev.callPackage (import ./_sources/generated.nix) { }; + # then, call packages with `final.callPackage` +} diff --git a/pkgs/sources.toml b/pkgs/sources.toml new file mode 100644 index 00000000..f7af168e --- /dev/null +++ b/pkgs/sources.toml @@ -0,0 +1,4 @@ +# nvfetcher.toml +[manix] +src.git = "https://github.com/mlvzk/manix" +fetch.github = "mlvzk/manix" diff --git a/pkgs/wallabag.nix b/pkgs/wallabag.nix new file mode 100644 index 00000000..6adfca0d --- /dev/null +++ b/pkgs/wallabag.nix @@ -0,0 +1,98 @@ +{ pkgs, config, lib, ... }: + +{ + services.postgresql = { + enable = true; + + # Ensure the database, user, and permissions always exist + ensureDatabases = [ "wallabag" ]; + ensureUsers = [ + { name = "wallabag"; + ensurePermissions."DATABASE wallabag" = "ALL PRIVILEGES"; + } + ]; + }; + + services.wallabag = { + enable = true; + hostName = "read.mossnet.lan"; + package = pkgs.callPackage ./pkg-wallabag.nix {}; + conf = '' +# This file is a "template" of what your parameters.yml file should look like +parameters: + # Uncomment these settings or manually update your parameters.yml + # to use docker-compose + # + # database_driver: %env.database_driver% + # database_host: %env.database_host% + # database_port: %env.database_port% + # database_name: %env.database_name% + # database_user: %env.database_user% + # database_password: %env.database_password% + + database_driver: pdo_pgsql + database_host: localhost + database_port: ~ + database_name: wallabag + database_user: wallabag + database_password: wallabag + # For SQLite, database_path should be "%kernel.project_dir%/data/db/wallabag.sqlite" + database_path: ~ + database_table_prefix: wallabag_ + database_socket: null + # with PostgreSQL and SQLite, you must set "utf8" + database_charset: utf8 + + domain_name: http://read.mossnet.lan + server_name: "mossnet wallabag instance" + + mailer_transport: smtp + mailer_user: ~ + mailer_password: ~ + mailer_host: 127.0.0.1 + mailer_port: false + mailer_encryption: ~ + mailer_auth_mode: ~ + + locale: en + + # A secret key that's used to generate certain security-related tokens + secret: SAFGOECRIlfal89oe6u0(*^dsaaih961 + + # two factor stuff + twofactor_auth: true + twofactor_sender: no-reply@wallabag.org + + # fosuser stuff + fosuser_registration: true + fosuser_confirmation: true + + # how long the access token should live in seconds for the API + fos_oauth_server_access_token_lifetime: 3600 + # how long the refresh token should life in seconds for the API + fos_oauth_server_refresh_token_lifetime: 1209600 + + from_email: no-reply@wallabag.org + + rss_limit: 50 + + # RabbitMQ processing + rabbitmq_host: localhost + rabbitmq_port: 5672 + rabbitmq_user: guest + rabbitmq_password: guest + rabbitmq_prefetch_count: 10 + + # Redis processing + redis_scheme: tcp + redis_host: localhost + redis_port: 6379 + redis_path: null + redis_password: null + + # sentry logging + sentry_dsn: ~ +''; + }; + # networking.firewall.allowedTCPPorts = [ 8080 ]; +} diff --git a/pkgs/wallabag.patch b/pkgs/wallabag.patch new file mode 100644 index 00000000..243569b4 --- /dev/null +++ b/pkgs/wallabag.patch @@ -0,0 +1,31 @@ +diff --git a/app/AppKernel.php b/app/AppKernel.php +index 347197e..902b558 100644 +--- a/app/AppKernel.php ++++ b/app/AppKernel.php +@@ -69,19 +69,24 @@ class AppKernel extends Kernel + return __DIR__; + } + ++ public function getProjectDir() ++ { ++ return getenv('WALLABAG_DATA') ?: dirname(__DIR__); ++ } ++ + public function getCacheDir() + { +- return dirname(__DIR__) . '/var/cache/' . $this->getEnvironment(); ++ return $this->getProjectDir() . '/var/cache/' . $this->getEnvironment(); + } + + public function getLogDir() + { +- return dirname(__DIR__) . '/var/logs'; ++ return $this->getProjectDir() . '/var/logs'; + } + + public function registerContainerConfiguration(LoaderInterface $loader) + { +- $loader->load($this->getRootDir() . '/config/config_' . $this->getEnvironment() . '.yml'); ++ $loader->load($this->getProjectDir() . '/app/config/config_' . $this->getEnvironment() . '.yml'); + + $loader->load(function ($container) { diff --git a/profiles/backup/default.nix b/profiles/backup/default.nix new file mode 100644 index 00000000..ffcd4415 --- /dev/null +++ b/profiles/backup/default.nix @@ -0,0 +1 @@ +{ } diff --git a/profiles/bluetooth/default.nix b/profiles/bluetooth/default.nix new file mode 100644 index 00000000..b880ef5d --- /dev/null +++ b/profiles/bluetooth/default.nix @@ -0,0 +1,12 @@ +{ pkgs, ... }: + +{ + hardware.bluetooth.enable = true; + services.blueman.enable = true; + # A2DP protocol + hardware.bluetooth.settings = { + General = { + Enable = "Source,Sink,Media,Socket"; + }; + }; +} diff --git a/profiles/borg/default.nix b/profiles/borg/default.nix new file mode 100644 index 00000000..ee9ecb43 --- /dev/null +++ b/profiles/borg/default.nix @@ -0,0 +1,34 @@ +{ + # Assumes the remote borg backup server has already been initialized + # borg init --encryption-key=repokey-blake2 -rsh 'ssh -i /run/keys/id_ed25519_borgbase' 20779@hk-s020.rsync.net: + services.borgbackup.jobs = { + backupTaskwarriorRsync = { + paths = [ "/var/lib/taskserver" ]; + doInit = true; + repo = "20779@hk-s020.rsync.net:taskwarrior"; + encryption = { + mode = "repokey-blake2"; + passCommand = "cat /run/keys/rsync"; + }; + environment = { BORG_RSH = "ssh -i /run/keys/id_ed25519_borgbase"; }; + compression = "auto,lzma"; + startAt = "weekly"; + extraArgs = "--remote-path=borg1"; + }; + }; + services.borgbackup.jobs = { + backupShaarliRsync = { + paths = [ "/var/www/shaarli-config/data/datastore.php" "/var/www/shaarli-config/config" "/var/www/shaarli-config/.json.config" ]; + doInit = true; + repo = "20779@hk-s020.rsync.net:shaarli"; + encryption = { + mode = "repokey-blake2"; + passCommand = "cat /run/keys/rsync"; + }; + environment = { BORG_RSH = "ssh -i /run/keys/id_ed25519_borgbase"; }; + compression = "auto,lzma"; + startAt = "weekly"; + extraArgs = "--remote-path=borg1"; + }; + }; +} diff --git a/profiles/cachix/default.nix b/profiles/cachix/default.nix new file mode 100644 index 00000000..d88a3f75 --- /dev/null +++ b/profiles/cachix/default.nix @@ -0,0 +1,11 @@ +{ pkgs, lib, ... }: +let + folder = ./.; + toImport = name: value: folder + ("/" + name); + filterCaches = key: value: value == "regular" && lib.hasSuffix ".nix" key && key != "default.nix"; + imports = lib.mapAttrsToList toImport (lib.filterAttrs filterCaches (builtins.readDir folder)); +in +{ + inherit imports; + nix.binaryCaches = [ "https://cache.nixos.org/" ]; +} diff --git a/profiles/cachix/nix-community.nix b/profiles/cachix/nix-community.nix new file mode 100644 index 00000000..7e4be286 --- /dev/null +++ b/profiles/cachix/nix-community.nix @@ -0,0 +1,10 @@ +{ + nix = { + binaryCaches = [ + "https://nix-community.cachix.org" + ]; + binaryCachePublicKeys = [ + "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=" + ]; + }; +} diff --git a/profiles/cachix/nrdxp.nix b/profiles/cachix/nrdxp.nix new file mode 100644 index 00000000..bb3b4a59 --- /dev/null +++ b/profiles/cachix/nrdxp.nix @@ -0,0 +1,10 @@ +{ + nix = { + binaryCaches = [ + "https://nrdxp.cachix.org" + ]; + binaryCachePublicKeys = [ + "nrdxp.cachix.org-1:Fc5PSqY2Jm1TrWfm88l6cvGWwz3s93c6IOifQWnhNW4=" + ]; + }; +} diff --git a/profiles/calibre/default.nix b/profiles/calibre/default.nix new file mode 100644 index 00000000..3457e15c --- /dev/null +++ b/profiles/calibre/default.nix @@ -0,0 +1,37 @@ +{ + # Unnecessary at this stage + #services.calibre-web = { + # enable = true; + # listen.port = 8083; + # openFirewall = true; + # # Bug in the module puts this in quotes in the systemd file + # # user = calibre; + # # group = calibre; + # options = { + # calibreLibrary = "/data/books"; + # enableBookUploading = true; + # }; + #}; + + services.calibre-server = { + enable = true; + libraries = [ "/data/books" ]; + # Bug in the module puts this in quotes in the systemd file + # user = calibre; + # group = calibre; + }; + + services.nginx.virtualHosts."books.mossnet.lan" = { + enableACME = false; + forceSSL = false; + + locations."/" = { + extraConfig = '' + proxy_pass http://localhost:8083/; + proxy_set_header X-Forwarded-Host $host; + ''; + }; + }; + + networking.firewall.allowedTCPPorts = [ 8080 ]; +} diff --git a/profiles/core/common.nix b/profiles/core/common.nix new file mode 100644 index 00000000..e7ea3d00 --- /dev/null +++ b/profiles/core/common.nix @@ -0,0 +1,132 @@ +{ config, pkgs, ... }: + +{ +# imports = [ +# ./nvim.nix +# ./unstable.nix +# ]; + + + environment.systemPackages = with pkgs; [ + htop + iftop + wget + curl + exa + bat + fd + ag + viu + w3m + ranger + ripgrep + tcpdump + whois + mtr + file + lsof + atool + inotify-tools + strace + zip + unzip + rsync + tmux + pwgen + glow + gitAndTools.gitFull + dig + wpa_supplicant + #neovim defined in ./nvim.nix + #wofi + #firefox + #fractal + #pinentry_gnome + pass + gcc + less + mpv + zathura + #qmk_firmware + python3 + gdb + #vcv-rack + #xdotool + #neofetch + #calibre + #openvpn + #gimp + xxd + #tilix + kitty + taskwarrior + gnupg + #openjdk + #glslviewer + #filezilla + #signal-desktop + #wire-desktop + #tdesktop + #feedreader + #newsflash + #syncthing + dijo + #kdeconnect + #ssb-patchwork + #gnome3.gnome-tweaks + #gnome3.pomodoro + #gnomeExtensions.gsconnect + #gnomeExtensions.taskwhisperer + #gnome3.networkmanager-openvpn + #python3Packages.youtube-dl + #appimage-run + #home-manager + libreoffice + fontconfig + #hugo + #processing + #nextcloud-client + #zsh-powerlevel10k + powerline-fonts + #supercollider + haskellPackages.tidal + pandoc + ]; + + #programs.bash.enableCompletion = true; + environment.shellAliases = { + "cat": "bat"; + "ls":"exa"; + "grep": "rg"; + }; + + # needed for vcv-rack + #nixpkgs.config.allowUnfree = true; + programs.gnupg.agent.enable = true; + programs.gnupg.agent.pinentryFlavor = "curses"; + programs.gnupg.agent.enableSSHSupport = false; + + #system.copySystemConfiguration = true; + #services.syncthing = { + # enable = true; + # openDefaultPorts = true; + # systemService = true; + # user = "anish"; + # dataDir = "/home/anish/usr/syncthing"; + #}; + + #zsh powerlevel10k + #programs.zsh.enable = true; + #programs.zsh.promptInit = "source ${pkgs.zsh-powerlevel10k}/share/zsh-powerlevel10k/powerlevel10k.zsh-theme"; + #users.users.anish.shell = pkgs.zsh; + + #android + programs.adb.enable = true; + users.users.anish.extraGroups = ["adbusers"]; + + nix.extraOptions = '' + keep-outputs = true + keep-derivations = true + ''; + +} diff --git a/profiles/core/default.nix b/profiles/core/default.nix new file mode 100644 index 00000000..88d626a4 --- /dev/null +++ b/profiles/core/default.nix @@ -0,0 +1,49 @@ +{ self, config, lib, pkgs, ... }: +let inherit (lib) fileContents; +in +{ + imports = [ ../cachix ]; + + nix.systemFeatures = [ "nixos-test" "benchmark" "big-parallel" "kvm" ]; + + fonts = { + fonts = with pkgs; [ powerline-fonts dejavu_fonts ]; + fontconfig.defaultFonts = { + monospace = [ "DejaVu Sans Mono for Powerline" ]; + sansSerif = [ "DejaVu Sans" ]; + }; + }; + + nix = { + autoOptimiseStore = true; + gc.automatic = true; + optimise.automatic = true; + useSandbox = true; + allowedUsers = [ "@wheel" ]; + trustedUsers = [ "root" "@wheel" ]; + extraOptions = '' + min-free = 536870912 + keep-outputs = true + keep-derivations = true + fallback = true + ''; + }; + + environment.systemPackages = with pkgs; [ + pinentry_gnome + cached-nix-shell + ]; + + services.devmon.enable = true; + + # For rage encryption, all hosts need a ssh key pair + services.openssh = { + enable = true; + openFirewall = lib.mkDefault false; + }; + + programs.gnupg.agent.enable = true; + #programs.gnupg.agent.pinentryFlavor = "curses"; + + services.earlyoom.enable = true; +} diff --git a/profiles/core/starship.toml b/profiles/core/starship.toml new file mode 100644 index 00000000..f08a026f --- /dev/null +++ b/profiles/core/starship.toml @@ -0,0 +1,92 @@ +[aws] +symbol = " " + +[character] +success_symbol = "[❯](bold purple)" +vicmd_symbol = "[❮](bold purple)" + +[battery] +full_symbol = " " +charging_symbol = " " +discharging_symbol = " " + +[conda] +symbol = " " + +[directory] +style = "cyan" +read_only = " 🔒" + +[docker_context] +symbol = " " + +[elixir] +symbol = " " + +[elm] +symbol = " " + +[git_branch] +format = "[$symbol$branch]($style) " +symbol = " " +style = "bold dimmed white" + +[git_status] +format = '([「$all_status$ahead_behind」]($style) )' +conflicted = "⚠️" +ahead = "⟫${count} " +behind = "⟪${count}" +diverged = "🔀 " +untracked = "📁 " +stashed = "↪ " +modified = "𝚫 " +staged = "✔ " +renamed = "⇆ " +deleted = "✘ " +style = "bold bright-white" + +[golang] +symbol = " " + +[hg_branch] +symbol = " " + +[java] +symbol = " " + +[julia] +symbol = " " + +[memory_usage] +symbol = " " +disabled = false + +[nim] +symbol = " " + +[nix_shell] +format = '[$symbol$state]($style) ' +symbol = " " +pure_msg = "λ" +impure_msg = "⎔" + +[nodejs] +symbol = " " + +[package] +symbol = " " + +[php] +symbol = " " + +[python] +symbol = " " + +[ruby] +symbol = " " + +[rust] +symbol = " " + +[status] +disabled = false diff --git a/profiles/desktop/battery-low-timer.nix b/profiles/desktop/battery-low-timer.nix new file mode 100644 index 00000000..612e01e7 --- /dev/null +++ b/profiles/desktop/battery-low-timer.nix @@ -0,0 +1,42 @@ +{ pkgs, ... }: + +{ + systemd.services.battery-low = { + serviceConfig.Type = "simple"; + path = [ + pkgs.acpi + pkgs.gawk # I was too lazy to find out where awk lives, it's not coreutils, hopefully it works the same + pkgs.libnotify + ]; + startAt = "*08:00:00"; + script = '' + #!/usr/bin/env bash + if [ `acpi -b | grep "Battery 0" | gawk ' { print ($3)}'` == "Discharging," ] ; then + # Discharging + # Monitor for low battery + rm /tmp/battery-full + if [ `acpi -b | grep "Battery 0" | gawk ' { print ($4)-0}'` -le "15" ] ; then + notify-send -u critical "Battery Low"; + fi + else + # Charging + if [ `acpi -b | grep "Battery 0" | gawk ' { print ($4)-0}'` -ge "94" ] ; then + # Fully charged + if [[ -f /tmp/battery-full ]]; then + touch /tmp/battery-full; + notify-send "Battery Full" + fi + fi + fi + ''; + serviceConfig = { + User = "anish"; + Environment = "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus"; + }; + }; + systemd.timers.battery-low = { + wantedBy = [ "timers.target" ]; + partOf = [ "battery-low.service" ]; + timerConfig.OnCalendar = [ "*:0/5" ]; + }; +} diff --git a/profiles/desktop/default.nix b/profiles/desktop/default.nix new file mode 100644 index 00000000..5b74f204 --- /dev/null +++ b/profiles/desktop/default.nix @@ -0,0 +1,201 @@ +{ config, pkgs, lib, ... }: +let + dracula-gtk = pkgs.fetchFromGitHub { + owner = "dracula"; + repo = "gtk"; + rev = "502f212d83bc67e8f0499574546b99ec6c8e16f9"; + sha256 = "1wx9nzq7cqyvpaq4j60bs8g7gh4jk8qg4016yi4c331l4iw1ymsa"; + }; +in +{ + # TODO modularize + imports = [ ./battery-low-timer.nix ]; + + services = { + gnome.gnome-keyring.enable = true; + upower.enable = true; + + dbus = { + enable = true; + packages = [ pkgs.dconf ]; + }; + }; + + security.pam.services.sddm.enableGnomeKeyring = true; + + environment.sessionVariables = rec { + XDG_CACHE_HOME = "\${HOME}/.cache"; + XDG_CONFIG_HOME = "\${HOME}/.config"; + XDG_BIN_HOME = "\${HOME}/.local/bin"; + XDG_DATA_HOME = "\${HOME}/.local/share"; + + PATH = [ + "\${XDG_BIN_HOME}" + ]; + }; + + nixpkgs.config.allowUnfreePredicate = pkg: builtins.elem (lib.getName pkg) [ + "ripcord" + "vcv-rack" + ]; + + environment.systemPackages = with pkgs; [ + signal-desktop # bridge to sealight? + scrot + ripcord + feh + sxiv + xkblayout-state + sublime-music + vcv-rack + zathura + calibre + nheko + mpv + newsflash + zeal + xclip + xdotool + rofi + rofimoji + rofi-calc + eww + obs-studio + lightdm + dunst + libnotify + (polybar.override { + pulseSupport = true; + nlSupport = true; + }) + papirus-icon-theme + calendar-cli + wyrd + tootle + ]; + + + location.provider = "geoclue2"; + services = { + redshift = { + enable = true; + temperature = { + day = 5500; + night = 3700; + }; + }; + xserver = { + enable = true; + layout = "us,dvorak"; + desktopManager.wallpaper.mode = "fill"; + displayManager = { + defaultSession = "none+bspwm"; + sessionCommands = '' + ${pkgs.xorg.xrdb}/bin/xrdb -merge <>/dev/null && connect || disconnect + + # keyboard on curve is busted + get_keyboard_id() { + xinput list | grep 'AT Translated Set' | cut -f2 | cut -d'=' -f2 | xinput float + } + + disconnect_keyboard() { + id=$(get_keyboard_id) + xinput float $id + unset id + } + + attach_keyboard() { + id=$(get_keyboard_id) + xinput reattach $id 3 + } + + disconnect_keyboard + ''; + # lightdm.enable = true; + # lightdm.greeters.mini.enable = true; + # lightdm.greeters.mini.user = "anish"; # TODO hardcoded + # lightdm.background = "/etc/nixos/users/profiles/desktop/background.jpg"; + # lightdm.greeters.mini.extraConfig = '' + # text-color = "#ff79c6" + # password-background-color = "#1E2029" + # window-color = "#181a23" + # border-color = "#181a23" + # ''; + }; + windowManager.bspwm.enable = true; + #windowManager.bspwm.configFile = "/home/anish/.bspwm/bspwmrc"; + windowManager.bspwm.sxhkd.configFile = "/home/anish/.config/sxhkdrc"; + }; + }; + + fonts.fonts = with pkgs; [ + fira-code + fira-code-symbols + hermit + #hack + siji + font-awesome + proggyfonts + (nerdfonts.override { fonts = [ "FiraCode" "DroidSansMono" "Iosevka" ]; }) + ]; +} diff --git a/profiles/dhyan/default.nix b/profiles/dhyan/default.nix new file mode 100644 index 00000000..111f9a89 --- /dev/null +++ b/profiles/dhyan/default.nix @@ -0,0 +1,32 @@ +{ pkgs, ... }: + +{ + # TODO + # scrappy script that requires dhyan be cloned to /home/anish/usr/dhyan + # dhyan needs secrets, and internet access to install dependencies, havent figured that out with nix yet + # dhyan also depends on jdk11, but that's only to install dependencies, run `bb -m dhyan.main` once before installing this script + # If you've updated dhyan, you'll want to cd to /home/anish/usr/dhyan and run git pull + systemd.services.dhyan = { + serviceConfig.Type = "oneshot"; + path = [ + pkgs.babashka + pkgs.git + pkgs.jdk11 + pkgs.curl + ]; + startAt = "*08:00:00"; + script = '' + cd /home/anish/usr/dhyan + source .envrc + bb -m dhyan.main + ''; + serviceConfig = { + User = "anish"; + }; + }; + systemd.timers.dhyan = { + wantedBy = [ "timers.target" ]; + partOf = [ "kitaab-sync.service" ]; + timerConfig.OnCalendar = [ "08:00:00" ]; + }; +} diff --git a/profiles/dns/default.nix b/profiles/dns/default.nix new file mode 100644 index 00000000..9935540e --- /dev/null +++ b/profiles/dns/default.nix @@ -0,0 +1,16 @@ +{ config, pkgs, lib, ... }: +{ + services.dnsmasq.enable = true; + services.dnsmasq.extraConfig = '' + domain-needed + no-resolv + local=/lan/ + local=/moss/ + cache-size=5000 + addn-hosts=/etc/adblock.hosts + ''; # find a way to make adblock hosts reproducible and updateable + services.dnsmasq.servers = [ "45.90.30.49" "45.90.28.49" "1.1.1.1" "8.8.8.8" ]; + networking.hosts = { "192.168.1.240" = [ "mossnet.lan" "links.mossnet.lan" "read.mossnet.lan" "stats.mossnet.lan" "music.mossnet.lan" "rss.mossnet.lan" "tasks.mossnet.lan" "file.mossnet.lan" "books.mossnet.lan" ]; }; + networking.firewall.allowedTCPPorts = [ 53 ]; + networking.firewall.allowedUDPPorts = [ 53 ]; +} diff --git a/profiles/ftp/default.nix b/profiles/ftp/default.nix new file mode 100644 index 00000000..f3eb6e2a --- /dev/null +++ b/profiles/ftp/default.nix @@ -0,0 +1,20 @@ +{ pkgs, lib, ... }: + +{ + networking.firewall.allowedTCPPorts = [ 20 21 ]; + networking.firewall.allowedTCPPortRanges = [{ from = 51000; to = 51999; }]; + services.vsftpd = { + enable = true; + writeEnable = true; + anonymousUser = true; + anonymousUserNoPassword = true; + anonymousUploadEnable = true; + anonymousMkdirEnable = true; + anonymousUserHome = "/home/ftp"; + extraConfig = '' + pasv_enable=Yes + pasv_min_port=51000 + pasv_max_port=51999 + ''; + }; +} diff --git a/profiles/gitea/default.nix b/profiles/gitea/default.nix new file mode 100644 index 00000000..2b593ed7 --- /dev/null +++ b/profiles/gitea/default.nix @@ -0,0 +1,59 @@ +{ config, lib, pkgs, ... }: + +{ + services.gitea = { + enable = true; + appName = "Sealight Git Forge"; + domain = "git.sealight.xyz"; + rootUrl = "https://git.sealight.xyz"; + httpPort = 3001; + database = { + type = "postgres"; + # passwordFile = "/run/secrets/gitea-dbpass"; # TODO supplied by agenix + password = "somethingunknowablesorry"; + }; + settings = { + metrics = { + ENABLED = true; + }; + repository = { + DEFAULT_BRANCH = "main"; + }; + }; + }; + + + services.postgresql = { + enable = true; # Ensure postgresql is enabled + authentication = '' + local gitea all ident map=gitea-users + ''; + identMap = # Map the gitea user to postgresql + '' + gitea-users gitea gitea + ''; + # ensureDatabases = [ "gitea" ]; + ensureUsers = [ + { name = "gitea"; ensurePermissions."DATABASE gitea" = "ALL PRIVILEGES"; } + ]; + # TODO + # initialScript # set password for gitea user + }; + + services.nginx = { + enable = true; # Enable Nginx + recommendedGzipSettings = true; + recommendedOptimisation = true; + recommendedProxySettings = true; + recommendedTlsSettings = true; + virtualHosts."git.sealight.xyz" = { + # Gitea hostname + enableACME = true; # Use ACME certs + forceSSL = true; # Force SSL + locations."/".proxyPass = "http://localhost:3001/"; # Proxy Gitea + }; + }; + networking.firewall.allowedTCPPorts = [ 80 443 ]; + security.acme.defaults.email = "anish+acme@lakhwara.com"; + security.acme.acceptTerms = true; +} diff --git a/profiles/gonic/default.nix b/profiles/gonic/default.nix new file mode 100644 index 00000000..9c03639f --- /dev/null +++ b/profiles/gonic/default.nix @@ -0,0 +1,12 @@ +{ config, lib, pkgs, ... }: +{ + services.gonic.enable = true; + services.gonic.settings = '' + music-path /mnt/two/music/ + podcast-path /data/podcasts + cache-path /data/cache + ''; + services.gonic.group = "audio"; + services.gonic.user = "headphones"; + networking.firewall.allowedTCPPorts = [ 4747 ]; +} diff --git a/profiles/gonic/module-gonic.nix b/profiles/gonic/module-gonic.nix new file mode 100644 index 00000000..b48032c7 --- /dev/null +++ b/profiles/gonic/module-gonic.nix @@ -0,0 +1,110 @@ +{ config, lib, pkgs, ... }: + +with lib; + +let + cfg = config.services.gonic; + configFile = "/etc/gonic/config"; + dataFolder = "/var/lib/gonic"; +in +{ + options = { + + services.gonic = { + enable = mkEnableOption "Gonic music server and streamer"; + + settings = lib.mkOption { + type = types.str; + default = { }; + example = literalExample '' + music-path + podcast-path + cache-path + ''; + description = '' + Configuration for Gonic, see for supported values. + ''; + }; + + user = mkOption { + type = types.str; + default = "gonic"; + description = "User account under which gonic runs."; + }; + + group = mkOption { + type = types.str; + default = "gonic"; + description = "Group account under which gonic runs."; + }; + + }; + }; + + config = mkIf cfg.enable { + + environment.etc."gonic/config".text = cfg.settings; + + systemd.services.gonic = { + description = "gonic Music Server and Streamer compatible with Subsonic/Airsonic"; + after = [ "remote-fs.target" "network.target" ]; + wantedBy = [ "multi-user.target" ]; + environment = { + #GONIC_MUSIC_PATH + #GONIC_PODCAST_PATH + #GONIC_CACHE_PATH + #GONIC_DB_PATH + GONIC_SCAN_INTERVAL = "800"; + #... + }; + serviceConfig = { + ExecStart = "${pkgs.gonic}/bin/gonic -config-path /etc/gonic/config"; + WorkingDirectory = dataFolder; + TimeoutStopSec = "20"; + KillMode = "process"; + Restart = "on-failure"; + RestartSec = "10"; + User = cfg.user; + Group = cfg.group; + DevicePolicy = "closed"; + NoNewPrivileges = " yes"; + PrivateTmp = "yes"; + PrivateUsers = "yes"; + ProtectControlGroups = "yes"; + ProtectKernelModules = "yes"; + ProtectKernelTunables = "yes"; + RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6"; + RestrictNamespaces = "yes"; + RestrictRealtime = "yes"; + SystemCallFilter = "~@clock @debug @module @mount @obsolete @privileged @reboot @setuid @swap"; + ReadWritePaths = dataFolder; + StateDirectory = baseNameOf dataFolder; + }; + }; + + users.users = optionalAttrs (cfg.user == "gonic") ({ + gonic = { + description = "gonic service user"; + name = cfg.user; + group = cfg.group; + isSystemUser = true; + }; + }); + + users.groups = optionalAttrs (cfg.group == "gonic") ({ + gonic = { }; + }); + + services.nginx.virtualHosts."music.mossnet.lan" = { + enableACME = false; + forceSSL = false; + + locations."/" = { + extraConfig = '' + proxy_pass http://localhost:4747/; + proxy_set_header X-Forwarded-Host $host; + ''; + }; + }; + }; +} diff --git a/profiles/grasp/default.nix b/profiles/grasp/default.nix new file mode 100644 index 00000000..e01057d3 --- /dev/null +++ b/profiles/grasp/default.nix @@ -0,0 +1,6 @@ +{ ... }: +{ + services."grasp".enable = true; + services."grasp".path = "/home/anish/kitaab/grasp"; + services."grasp".user = "anish"; +} diff --git a/profiles/headphones/default.nix b/profiles/headphones/default.nix new file mode 100644 index 00000000..c2d2830c --- /dev/null +++ b/profiles/headphones/default.nix @@ -0,0 +1,12 @@ +{ config, lib, pkgs, ... }: +{ + services.headphones = { + enable = true; + host = "192.168.1.240"; + port = 8181; + user = "headphones"; + group = "audio"; + dataDir = "/data/music"; + }; + networking.firewall.allowedTCPPorts = [ 8181 ]; +} diff --git a/profiles/helix-zone/dns.nix b/profiles/helix-zone/dns.nix new file mode 100644 index 00000000..a23adc88 --- /dev/null +++ b/profiles/helix-zone/dns.nix @@ -0,0 +1,54 @@ +{ pkgs, ... }: + +let + adblockLocalZones = pkgs.stdenv.mkDerivation { + name = "unbound-zones-adblock"; + + src = (pkgs.fetchFromGitHub { + owner = "StevenBlack"; + repo = "hosts"; + rev = "3.0.0"; + sha256 = "01g6pc9s1ah2w1cbf6bvi424762hkbpbgja9585a0w99cq0n6bxv"; + } + "/hosts"); + + phases = [ "installPhase" ]; + + installPhase = '' + ${pkgs.gawk}/bin/awk '{sub(/\r$/,"")} {sub(/^127\.0\.0\.1/,"0.0.0.0")} BEGIN { OFS = "" } NF == 2 && $1 == "0.0.0.0" { print "local-zone: \"", $2, "\" static"}' $src | tr '[:upper:]' '[:lower:]' | sort -u > $out + ''; + }; + +in { + networking.firewall.allowedTCPPorts = [ 53 853 5353 ]; + networking.firewall.allowedUDPPorts = [ 53 853 5353 ]; + networking.extraHosts = '' 127.0.0.1 helix.domain ''; + # These are causing errors, goes in the server file + # local-data = "mossnet.lan. 10800 IN A 10.0.69.4"; + services.unbound = { + enable = true; + settings = { + server = { + interface = [ "0.0.0.0" ]; + tls-upstream = true; + tls-cert-bundle = "/etc/ssl/certs/ca-certificates.crt"; + include = "${adblockLocalZones}"; + access-control = "0.0.0.0/0 allow"; + verbosity = 2; + do-tcp = true; + do-ip4 = true; + prefetch = true; + prefetch-key = true; + rrset-roundrobin = true; + qname-minimisation-strict = true; + hide-identity = true; + hide-version = true; + local-zone = "mossnet.lan. static"; + }; + forward-zone = [{ + name = "."; + forward-addr = [ "45.90.28.77#c46fd3.dns1.nextdns.io" "2a07:a8c0::#c46fd3.dns1.nextdns.io" "45.90.30.77#c46fd3.dns2.nextdns.io" "2a07:a8c1::#c46fd3.dns2.nextdns.io" ]; + }]; + remote-control.control-enable = true; + }; + }; +} diff --git a/profiles/helix-zone/knot.nix b/profiles/helix-zone/knot.nix new file mode 100644 index 00000000..d6f11947 --- /dev/null +++ b/profiles/helix-zone/knot.nix @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: Apache-2.0 +{ config, pkgs, ... }: +let + # https://github.com/StevenBlack/hosts/issues/451 + # https://github.com/ScriptTiger/Hosts-Conversions + # https://github.com/ScriptTiger/scripttiger.github.io + # https://scripttiger.github.io/alts/ + adblockLocalZones = pkgs.stdenv.mkDerivation { + name = "adblock-rpz"; + src = (pkgs.fetchFromGitHub { + owner = "ScriptTiger"; + repo = "scripttiger.github.io"; + # nix-prefetch-github ScriptTiger scripttiger.github.io + rev = "04402a6726f97c5f0d30436a70ac1344dccb7cf1"; + sha256 = "iSTR7j7QEr5xYtImyntDlVLbnN2ipcLcTRr4sfdx078="; + } + "/alts/rpz/blacklist.txt"); + phases = [ "installPhase" ]; + installPhase = "install -m 444 -D $src $out"; + }; + domain = "sealight.xyz"; + certdir = config.security.acme.certs.${domain}.directory; +in { + networking.firewall.allowedTCPPorts = [ 853 ]; + networking.firewall.allowedUDPPorts = [ 853 ]; + + # for acme certs, TODO: make a proper group + users.users.knot-resolver.extraGroups = [ "nginx" ]; + + # https://github.com/NixOS/nixpkgs/issues/81109 + nixpkgs.config.packageOverrides = pkgs: rec { + knot-resolver = pkgs.knot-resolver.override { extraFeatures = true; }; + }; + services.kresd = { + enable = true; + # Plain DNS only from localhost. + # You might want to add a LAN or VPN subnet, depending on deployment. + #listenPlain = [ "127.0.0.1:53" "[::1]:53" ]; + listenTLS = [ "853" ]; + #listenDoH = [ "" "[::]:443" ]; + instances = 1; + # TODO: chain.pem for stapling: https://gitlab.nic.cz/knot/knot-resolver/-/issues/517 + #policy.add( + # policy.rpz( + # policy.DENY_MSG('domain blocked by your resolver operator'), + # '${adblockLocalZones}', + # false)) + extraConfig = '' + modules.load('predict') + modules = { 'hints > iterate' } + policy.add( + policy.all( + policy.TLS_FORWARD({ + {'45.90.30.0', hostname='87b4e9.dns2.nextdns.io'}, + {'45.90.28.0', hostname='87b4e9.dns1.nextdns.io'} + }))) + policy.add(policy.suffix(policy.FORWARD({'10.0.69.4', '172.16.11.240'}), {todname('mossnet.lan')})) + + net.tls("${certdir}/fullchain.pem", "${certdir}/key.pem") + + -- refresh certs when ACME updates them + -- TODO: could probably do with systemd and a control socket? + -- TODO: may fail on first boot if ACME isn't fast, add a systemd dep + local notify = require('cqueues.notify') + local watcher = notify.opendir('${certdir}') + watcher:add('fullchain.pem') + + worker.coroutine(function () + for flags, name in watcher:changes() do + for flag in notify.flags(flags) do + print('file watcher:', name, notify[flag]) + end + if name == 'fullchain.pem' then + net.tls("${certdir}/fullchain.pem", "${certdir}/key.pem") + end + end + end) + + -- Below we create a tmpfs FS for the cache -- use almost all of it: + cache.size = cache.fssize() - 1*MB + ''; + }; +} diff --git a/profiles/helix-zone/node-composition.nix b/profiles/helix-zone/node-composition.nix new file mode 100644 index 00000000..53bdef1f --- /dev/null +++ b/profiles/helix-zone/node-composition.nix @@ -0,0 +1,17 @@ +# This file has been generated by node2nix 1.9.0. Do not edit! + +{pkgs ? import { + inherit system; + }, system ? builtins.currentSystem, nodejs ? pkgs."nodejs-12_x"}: + +let + nodeEnv = import ./node-env.nix { + inherit (pkgs) stdenv lib python2 runCommand writeTextFile writeShellScript; + inherit pkgs nodejs; + libtool = if pkgs.stdenv.isDarwin then pkgs.darwin.cctools else null; + }; +in +import ./node-packages.nix { + inherit (pkgs) fetchurl nix-gitignore stdenv lib fetchgit; + inherit nodeEnv; +} diff --git a/profiles/helix-zone/node-env.nix b/profiles/helix-zone/node-env.nix new file mode 100644 index 00000000..5f055785 --- /dev/null +++ b/profiles/helix-zone/node-env.nix @@ -0,0 +1,588 @@ +# This file originates from node2nix + +{lib, stdenv, nodejs, python2, pkgs, libtool, runCommand, writeTextFile, writeShellScript}: + +let + # Workaround to cope with utillinux in Nixpkgs 20.09 and util-linux in Nixpkgs master + utillinux = if pkgs ? utillinux then pkgs.utillinux else pkgs.util-linux; + + python = if nodejs ? python then nodejs.python else python2; + + # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise + tarWrapper = runCommand "tarWrapper" {} '' + mkdir -p $out/bin + + cat > $out/bin/tar <> $out/nix-support/hydra-build-products + ''; + }; + + # Common shell logic + installPackage = writeShellScript "install-package" '' + installPackage() { + local packageName=$1 src=$2 + + local strippedName + + local DIR=$PWD + cd $TMPDIR + + unpackFile $src + + # Make the base dir in which the target dependency resides first + mkdir -p "$(dirname "$DIR/$packageName")" + + if [ -f "$src" ] + then + # Figure out what directory has been unpacked + packageDir="$(find . -maxdepth 1 -type d | tail -1)" + + # Restore write permissions to make building work + find "$packageDir" -type d -exec chmod u+x {} \; + chmod -R u+w "$packageDir" + + # Move the extracted tarball into the output folder + mv "$packageDir" "$DIR/$packageName" + elif [ -d "$src" ] + then + # Get a stripped name (without hash) of the source directory. + # On old nixpkgs it's already set internally. + if [ -z "$strippedName" ] + then + strippedName="$(stripHash $src)" + fi + + # Restore write permissions to make building work + chmod -R u+w "$strippedName" + + # Move the extracted directory into the output folder + mv "$strippedName" "$DIR/$packageName" + fi + + # Change to the package directory to install dependencies + cd "$DIR/$packageName" + } + ''; + + # Bundle the dependencies of the package + # + # Only include dependencies if they don't exist. They may also be bundled in the package. + includeDependencies = {dependencies}: + lib.optionalString (dependencies != []) ( + '' + mkdir -p node_modules + cd node_modules + '' + + (lib.concatMapStrings (dependency: + '' + if [ ! -e "${dependency.name}" ]; then + ${composePackage dependency} + fi + '' + ) dependencies) + + '' + cd .. + '' + ); + + # Recursively composes the dependencies of a package + composePackage = { name, packageName, src, dependencies ? [], ... }@args: + builtins.addErrorContext "while evaluating node package '${packageName}'" '' + installPackage "${packageName}" "${src}" + ${includeDependencies { inherit dependencies; }} + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + ''; + + pinpointDependencies = {dependencies, production}: + let + pinpointDependenciesFromPackageJSON = writeTextFile { + name = "pinpointDependencies.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + function resolveDependencyVersion(location, name) { + if(location == process.env['NIX_STORE']) { + return null; + } else { + var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json"); + + if(fs.existsSync(dependencyPackageJSON)) { + var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON)); + + if(dependencyPackageObj.name == name) { + return dependencyPackageObj.version; + } + } else { + return resolveDependencyVersion(path.resolve(location, ".."), name); + } + } + } + + function replaceDependencies(dependencies) { + if(typeof dependencies == "object" && dependencies !== null) { + for(var dependency in dependencies) { + var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency); + + if(resolvedVersion === null) { + process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n"); + } else { + dependencies[dependency] = resolvedVersion; + } + } + } + } + + /* Read the package.json configuration */ + var packageObj = JSON.parse(fs.readFileSync('./package.json')); + + /* Pinpoint all dependencies */ + replaceDependencies(packageObj.dependencies); + if(process.argv[2] == "development") { + replaceDependencies(packageObj.devDependencies); + } + replaceDependencies(packageObj.optionalDependencies); + + /* Write the fixed package.json file */ + fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2)); + ''; + }; + in + '' + node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"} + + ${lib.optionalString (dependencies != []) + '' + if [ -d node_modules ] + then + cd node_modules + ${lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies} + cd .. + fi + ''} + ''; + + # Recursively traverses all dependencies of a package and pinpoints all + # dependencies in the package.json file to the versions that are actually + # being used. + + pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args: + '' + if [ -d "${packageName}" ] + then + cd "${packageName}" + ${pinpointDependencies { inherit dependencies production; }} + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + fi + ''; + + # Extract the Node.js source code which is used to compile packages with + # native bindings + nodeSources = runCommand "node-sources" {} '' + tar --no-same-owner --no-same-permissions -xf ${nodejs.src} + mv node-* $out + ''; + + # Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty) + addIntegrityFieldsScript = writeTextFile { + name = "addintegrityfields.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + function augmentDependencies(baseDir, dependencies) { + for(var dependencyName in dependencies) { + var dependency = dependencies[dependencyName]; + + // Open package.json and augment metadata fields + var packageJSONDir = path.join(baseDir, "node_modules", dependencyName); + var packageJSONPath = path.join(packageJSONDir, "package.json"); + + if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored + console.log("Adding metadata fields to: "+packageJSONPath); + var packageObj = JSON.parse(fs.readFileSync(packageJSONPath)); + + if(dependency.integrity) { + packageObj["_integrity"] = dependency.integrity; + } else { + packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads. + } + + if(dependency.resolved) { + packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided + } else { + packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories. + } + + if(dependency.from !== undefined) { // Adopt from property if one has been provided + packageObj["_from"] = dependency.from; + } + + fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2)); + } + + // Augment transitive dependencies + if(dependency.dependencies !== undefined) { + augmentDependencies(packageJSONDir, dependency.dependencies); + } + } + } + + if(fs.existsSync("./package-lock.json")) { + var packageLock = JSON.parse(fs.readFileSync("./package-lock.json")); + + if(![1, 2].includes(packageLock.lockfileVersion)) { + process.stderr.write("Sorry, I only understand lock file versions 1 and 2!\n"); + process.exit(1); + } + + if(packageLock.dependencies !== undefined) { + augmentDependencies(".", packageLock.dependencies); + } + } + ''; + }; + + # Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes + reconstructPackageLock = writeTextFile { + name = "addintegrityfields.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + var packageObj = JSON.parse(fs.readFileSync("package.json")); + + var lockObj = { + name: packageObj.name, + version: packageObj.version, + lockfileVersion: 1, + requires: true, + dependencies: {} + }; + + function augmentPackageJSON(filePath, dependencies) { + var packageJSON = path.join(filePath, "package.json"); + if(fs.existsSync(packageJSON)) { + var packageObj = JSON.parse(fs.readFileSync(packageJSON)); + dependencies[packageObj.name] = { + version: packageObj.version, + integrity: "sha1-000000000000000000000000000=", + dependencies: {} + }; + processDependencies(path.join(filePath, "node_modules"), dependencies[packageObj.name].dependencies); + } + } + + function processDependencies(dir, dependencies) { + if(fs.existsSync(dir)) { + var files = fs.readdirSync(dir); + + files.forEach(function(entry) { + var filePath = path.join(dir, entry); + var stats = fs.statSync(filePath); + + if(stats.isDirectory()) { + if(entry.substr(0, 1) == "@") { + // When we encounter a namespace folder, augment all packages belonging to the scope + var pkgFiles = fs.readdirSync(filePath); + + pkgFiles.forEach(function(entry) { + if(stats.isDirectory()) { + var pkgFilePath = path.join(filePath, entry); + augmentPackageJSON(pkgFilePath, dependencies); + } + }); + } else { + augmentPackageJSON(filePath, dependencies); + } + } + }); + } + } + + processDependencies("node_modules", lockObj.dependencies); + + fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2)); + ''; + }; + + prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}: + let + forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com"; + in + '' + # Pinpoint the versions of all dependencies to the ones that are actually being used + echo "pinpointing versions of dependencies..." + source $pinpointDependenciesScriptPath + + # Patch the shebangs of the bundled modules to prevent them from + # calling executables outside the Nix store as much as possible + patchShebangs . + + # Deploy the Node.js package by running npm install. Since the + # dependencies have been provided already by ourselves, it should not + # attempt to install them again, which is good, because we want to make + # it Nix's responsibility. If it needs to install any dependencies + # anyway (e.g. because the dependency parameters are + # incomplete/incorrect), it fails. + # + # The other responsibilities of NPM are kept -- version checks, build + # steps, postprocessing etc. + + export HOME=$TMPDIR + cd "${packageName}" + runHook preRebuild + + ${lib.optionalString bypassCache '' + ${lib.optionalString reconstructLock '' + if [ -f package-lock.json ] + then + echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!" + echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!" + rm package-lock.json + else + echo "No package-lock.json file found, reconstructing..." + fi + + node ${reconstructPackageLock} + ''} + + node ${addIntegrityFieldsScript} + ''} + + npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} rebuild + + if [ "''${dontNpmInstall-}" != "1" ] + then + # NPM tries to download packages even when they already exist if npm-shrinkwrap is used. + rm -f npm-shrinkwrap.json + + npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} install + fi + ''; + + # Builds and composes an NPM package including all its dependencies + buildNodePackage = + { name + , packageName + , version + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , preRebuild ? "" + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , meta ? {} + , ... }@args: + + let + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" "meta" ]; + in + stdenv.mkDerivation ({ + name = "${name}-${version}"; + buildInputs = [ tarWrapper python nodejs ] + ++ lib.optional (stdenv.isLinux) utillinux + ++ lib.optional (stdenv.isDarwin) libtool + ++ buildInputs; + + inherit nodejs; + + inherit dontStrip; # Stripping may fail a build for some package deployments + inherit dontNpmInstall preRebuild unpackPhase buildPhase; + + compositionScript = composePackage args; + pinpointDependenciesScript = pinpointDependenciesOfPackage args; + + passAsFile = [ "compositionScript" "pinpointDependenciesScript" ]; + + installPhase = '' + source ${installPackage} + + # Create and enter a root node_modules/ folder + mkdir -p $out/lib/node_modules + cd $out/lib/node_modules + + # Compose the package and all its dependencies + source $compositionScriptPath + + ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} + + # Create symlink to the deployed executable folder, if applicable + if [ -d "$out/lib/node_modules/.bin" ] + then + ln -s $out/lib/node_modules/.bin $out/bin + fi + + # Create symlinks to the deployed manual page folders, if applicable + if [ -d "$out/lib/node_modules/${packageName}/man" ] + then + mkdir -p $out/share + for dir in "$out/lib/node_modules/${packageName}/man/"* + do + mkdir -p $out/share/man/$(basename "$dir") + for page in "$dir"/* + do + ln -s $page $out/share/man/$(basename "$dir") + done + done + fi + + # Run post install hook, if provided + runHook postInstall + ''; + + meta = { + # default to Node.js' platforms + platforms = nodejs.meta.platforms; + } // meta; + } // extraArgs); + + # Builds a node environment (a node_modules folder and a set of binaries) + buildNodeDependencies = + { name + , packageName + , version + , src + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , ... }@args: + + let + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ]; + in + stdenv.mkDerivation ({ + name = "node-dependencies-${name}-${version}"; + + buildInputs = [ tarWrapper python nodejs ] + ++ lib.optional (stdenv.isLinux) utillinux + ++ lib.optional (stdenv.isDarwin) libtool + ++ buildInputs; + + inherit dontStrip; # Stripping may fail a build for some package deployments + inherit dontNpmInstall unpackPhase buildPhase; + + includeScript = includeDependencies { inherit dependencies; }; + pinpointDependenciesScript = pinpointDependenciesOfPackage args; + + passAsFile = [ "includeScript" "pinpointDependenciesScript" ]; + + installPhase = '' + source ${installPackage} + + mkdir -p $out/${packageName} + cd $out/${packageName} + + source $includeScriptPath + + # Create fake package.json to make the npm commands work properly + cp ${src}/package.json . + chmod 644 package.json + ${lib.optionalString bypassCache '' + if [ -f ${src}/package-lock.json ] + then + cp ${src}/package-lock.json . + fi + ''} + + # Go to the parent folder to make sure that all packages are pinpointed + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + + ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} + + # Expose the executables that were installed + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + + mv ${packageName} lib + ln -s $out/lib/node_modules/.bin $out/bin + ''; + } // extraArgs); + + # Builds a development shell + buildNodeShell = + { name + , packageName + , version + , src + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , ... }@args: + + let + nodeDependencies = buildNodeDependencies args; + in + stdenv.mkDerivation { + name = "node-shell-${name}-${version}"; + + buildInputs = [ python nodejs ] ++ lib.optional (stdenv.isLinux) utillinux ++ buildInputs; + buildCommand = '' + mkdir -p $out/bin + cat > $out/bin/shell < $out/bin/mx-puppet-slack + #!/bin/sh + exec ${nodejs}/bin/node $out/lib/node_modules/mx-puppet-slack/build/index.js "\$@" + EOF + chmod +x $out/bin/mx-puppet-slack + ''; + + meta = with lib; { + description = "A slack puppeting bridge for matrix"; + license = licenses.asl20; + homepage = "https://github.com/Sorunome/mx-puppet-slack"; + maintainers = with maintainers; [ chickensoupwithrice ]; + platforms = platforms.unix; + }; +} + diff --git a/profiles/matrix/default.nix b/profiles/matrix/default.nix new file mode 100644 index 00000000..b7ca7b32 --- /dev/null +++ b/profiles/matrix/default.nix @@ -0,0 +1,378 @@ +{ config, lib, pkgs, ... }: + +{ + + services.matrix-synapse = { + enable = true; + settings = { + server_name = "sealight.xyz"; + listeners = [ + { + port = 8448; + tls = false; + resources = [{ + compress = true; + names = [ "client" "federation" ]; + }]; + } + { + port = 9090; + type = "metrics"; + bind_addresses = [ "0.0.0.0" ]; + resources = [{ + compress = false; + names = [ ]; + }]; + tls = false; + } + ]; + app_service_config_files = [ + # The registration file is automatically generated after starting the appservice for the first time. + # cp /var/lib/matrix-appservice-discord/discord-registration.yaml /var/lib/matrix-synapse/ + # chown matrix-synapse:matrix-synapse /var/lib/matrix-synapse/discord-registration.yaml + # "/var/lib/matrix-synapse/telegram-registration.yaml" + # "/var/lib/matrix-synapse/slack-registration.yaml" + # "/var/lib/matrix-synapse/discord-registration.yaml" + # "/var/lib/matrix-synapse/whatsapp-registration.yaml" + ]; + turn_uris = [ + "turn:turn.sealight.xyz:3478?transport=udp" + "turn:turn.sealight.xyz:3478?transport=tcp" + ]; + turn_shared_secret = config.services.coturn.static-auth-secret; + extraConfig = '' + max_upload_size: "50M" + use_presence: false + registration_shared_secret: "hD9HQGTTDxp0mQsQ5JDsfudWMDiubmZENOgPchIvfBvUlPxlvQSvjoO4wn2L1seU"; + ''; + enable_metrics = true; + enable_registration = false; + database = { + name = "psycopg2"; + args.password = "Da0?H*9i{x?,]|kq@iBwlIzu"; # TODO agenix + }; + }; + ## coturn based TURN server integration (TURN server setup mentioned later), + ## shared secret generated while configuring coturn + ## and reused here (power of Nix being a real programming language) + }; + + services.coturn = { + enable = true; + use-auth-secret = true; + static-auth-secret = "jXW1ohIq6wM3NB00xeME3uBihY85xjpkhGoyzBIdwhOpj7gjyxXZu1fwp1lUiYwJ"; + realm = "turn.sealight.xyz"; + min-port = 49111; + max-port = 51111; + no-cli = true; + no-tcp-relay = true; + no-tls = true; + cert = "${config.security.acme.certs."turn.sealight.xyz".directory}/full.pem"; + pkey = "${config.security.acme.certs."turn.sealight.xyz".directory}/key.pem"; + extraConfig = '' + verbose + user-quota=12 + total-quota=1200 + denied-peer-ip=10.0.0.0-10.255.255.255 + denied-peer-ip=192.168.0.0-192.168.255.255 + denied-peer-ip=172.16.0.0-172.31.255.255 + denied-peer-ip=0.0.0.0-0.255.255.255 + denied-peer-ip=100.64.0.0-100.127.255.255 + denied-peer-ip=127.0.0.0-127.255.255.255 + denied-peer-ip=169.254.0.0-169.254.255.255 + denied-peer-ip=192.0.0.0-192.0.0.255 + denied-peer-ip=192.0.2.0-192.0.2.255 + denied-peer-ip=192.88.99.0-192.88.99.255 + denied-peer-ip=198.18.0.0-198.19.255.255 + denied-peer-ip=198.51.100.0-198.51.100.255 + denied-peer-ip=203.0.113.0-203.0.113.255 + denied-peer-ip=240.0.0.0-255.255.255.255 + ''; + }; + + security.acme.certs.${config.services.coturn.realm} = { + /* insert here the right configuration to obtain a certificate */ + webroot = "/var/lib/acme/acme-challenge/"; + email = "anish+acme@lakhwara.com"; + postRun = "systemctl restart coturn.service"; + group = "turnserver"; + }; + + # TODO fix up jitsi bridge stuff + ## services.jitsi-meet = { + ## enable = true; + ## hostName = "jitsi.sealight.xyz"; + ## }; + ## services.jitsi-videobridge.enable = true; + + services.postgresql = { + enable = true; + ## postgresql user and db name remains in the + ## service.matrix-synapse.database_args setting which + ## by default is matrix-synapse + # TODO agenix + initialScript = pkgs.writeText "synapse-init.sql" '' + CREATE ROLE "matrix-synapse" WITH LOGIN PASSWORD "Da0?H*9i{x?,]|kq@iBwlIzu"; + CREATE DATABASE "matrix-synapse" WITH OWNER "matrix-synapse" + TEMPLATE template0 + LC_COLLATE = "C" + LC_CTYPE = "C"; + ''; + authentication = '' + local matrix-synapse all ident map=matrix-synapse-users + ''; + identMap = # Map the matrix-synapse user to postgresql + '' + matrix-synapse-users matrix-synapse matrix-synapse + ''; + }; + + networking.firewall = + let + range = with config.services.coturn; [{ + from = min-port; + to = max-port; + }]; + in + { + enable = true; + allowedUDPPortRanges = range; # coturn + allowedTCPPortRanges = range; + allowedTCPPorts = [ + 22 # SSH + 8448 # Matrix federation + 8008 + 80 + 443 + 3478 # Coturn service + 5349 # Coturn service + 9090 # Synapse Metrics + ]; + allowedUDPPorts = [ + 3478 + 5349 # Coturn service + ]; + }; + + nixpkgs.overlays = [ + (self: super: { + element-web = super.element-web.override { + conf = { + default_server_config = { + "m.homeserver" = { + "base_url" = "https://chat.sealight.xyz"; + "server_name" = "sealight.xyz"; + }; + "m.identity_server" = { + "base_url" = "https://vector.im"; + }; + }; + + ## jitsi will be setup later, + ## but we need to add to Riot configuration + jitsi.preferredDomain = "jitsi.sealight.xyz"; + }; + }; + }) + ]; + + services.nginx = { + enable = true; + virtualHosts = { + "sealight.xyz" = { + forceSSL = true; + enableACME = true; + locations."/" = { + root = "/var/www/sealight.xyz"; + }; + locations."/_matrix" = { + proxyPass = "http://localhost:8448"; + }; + # locations."/slackbridge" = { + # proxyPass = "http://localhost:9899"; + # }; + }; + ## virtual host for Synapse + "chat.sealight.xyz" = { + forceSSL = true; + enableACME = true; # TODO + #useACMEHost = "sealight.xyz"; + locations."/" = { + proxyPass = "http://localhost:8448"; + }; + }; + ## virtual host for Riot/Web + "element.sealight.xyz" = { + forceSSL = true; + enableACME = true; # TODO + #useACMEHost = "sealight.xyz"; + ## root points to the riot-web package content, also configured via Nix + locations."/" = { + root = pkgs.element-web; + }; + }; + # ${config.services.jitsi-meet.hostName} = { + # enableACME = true; # TODO + # forceSSL = true; # TODO + # }; + }; + ## other nginx specific best practices + recommendedGzipSettings = true; + recommendedOptimisation = true; + recommendedTlsSettings = true; + }; + + services.mautrix-telegram = { + enable = false; + environmentFile = /etc/secrets/telegram.env; # file containing the appservice and telegram tokens + # The appservice is pre-configured to use SQLite by default. It's also possible to use PostgreSQL. + settings = { + homeserver = { + address = "https://sealight.xyz"; + domain = "sealight.xyz"; + }; + appservice = { + provisioning.enabled = false; + id = "telegram"; + bot_username = "telegrambridge"; + public = { + enabled = false; + prefix = "/public"; + external = "https://chat.sealight.xyz/public"; + }; + address = "http://localhost:18787"; + port = 18787; + # The service uses SQLite by default, but it's also possible to use PostgreSQL instead: + #database = "postgresql:///mautrix-telegram?host=/run/postgresql"; + }; + bridge = { + relaybot.authless_portals = false; + permissions = { + "@aynish:sealight.xyz" = "admin"; + }; + }; + }; + }; + + # services.heisenbridge = { + # enable = true; + # homeserver = "https://sealight.xyz"; + # listenPort = 14456; + # appServiceToken = "wyujLh8kjpmk2bfKeEE3sZ2gWOEUBKK5"; + # homeserverToken = "yEHs7lthD2ZHUibJOAv1APaFhEjxN5PT"; + # }; + + + # environment.systemPackages = with pkgs; [ matrix-appservice-slack ]; + #services.mx-puppet-slack= { + #enable = false; + #settings = { + # bridge = { + # bindAddress = "localhost"; + # port = 16786; + # domain = "sealight.xyz"; + # homeserverUrl = "https://sealight.xyz"; + # }; + # provisioning = { + # whitelist = [ "@aynish:sealight.xyz" ]; + # }; + # relay = { + # whitelist = [ "@aynish:sealight.xyz" ]; + # }; + # namePatterns = { + # group = ":name"; + # room = ":name[:team? - :team,]"; + # user = ":name (Slack)"; + # userOverride = ":displayname"; + # }; + # presence = { + # enabled = false; + # }; + # oauth = { + # enabled = false; + # }; + #}; + #serviceDependencies = ["matrix-synapse.service"]; + #}; + + # services.mautrix-whatsapp = { + # enable = false; + # The appservice is pre-configured to use SQLite by default. It's also possible to use PostgreSQL. + #configOptions = { + # homeserver = { + # address = "https://chat.sealight.xyz"; + # domain = "sealight.xyz"; + # }; + # appservice = { + # id = "whatsapp"; + # address = http://localhost:9897; + # hostname = "0.0.0.0"; + # port = 9897; + # database = { + # type = "sqlite3"; + # uri = "/var/lib/mautrix-whatsapp/mautrix-whatsapp.db"; + # }; + # state_store_path = "/var/lib/mautrix-whatsapp/mx-state.json"; + # bot = { + # username = "whatsappbot"; + # displayname = "WhatsApp bridge bot"; + # avatar = "mxc://maunium.net/NeXNQarUbrlYBiPCpprYsRqr"; + # }; + # as_token = ""; + # hs_token = ""; + # }; + # bridge = { + # username_template = "whatsapp_{{.}}"; + # displayname_template = "{{if .Notify}}{{.Notify}}{{else}}{{.Jid}}{{end}} (WA)"; + # command_prefix = "!wa"; + # permissions = { + # "@aynish:sealight.xyz" = 100; + # }; + # }; + # logging = { + # directory = "/var/lib/mautrix-whatsapp/logs"; + # file_name_format = "{{.Date}}-{{.Index}}.log"; + # file_date_format = "\"2006-01-02\""; + # file_mode = 384; + # timestamp_format = "Jan _2, 2006 15:04:05"; + # print_level = "debug"; + # }; + # metrics = { + # enabled = true; + # listen = "http://localhost:5070"; + # }; + #}; + # }; + + #services.mx-puppet-discord = { + # enable = true; + # settings = { + # bridge = { + # bindAddress = "localhost"; + # port = 16785; + # domain = "sealight.xyz"; + # homeserverUrl = "https://sealight.xyz"; + # avatarUrl = "https://discord.com/assets/2d20a45d79110dc5bf947137e9d99b66.svg"; + # }; + # provisioning = { + # whitelist = [ "@aynish:sealight.xyz" ]; + # }; + # relay = { + # whitelist = [ "@aynish:sealight.xyz" ]; + # }; + # namePatterns = { + # group = ":name"; + # room = ":name"; + # user = ":name (Discord)"; + # userOverride = ":displayname"; + # }; + # presence = { + # enabled = false; + # }; + # }; + # serviceDependencies = [ "matrix-synapse.service" ]; + #}; + + + +} diff --git a/profiles/matrix/matrix-slack.nix b/profiles/matrix/matrix-slack.nix new file mode 100644 index 00000000..8c4a9e77 --- /dev/null +++ b/profiles/matrix/matrix-slack.nix @@ -0,0 +1,154 @@ +{ config, pkgs, lib, ... }: + +with lib; + +let + dataDir = "/var/lib/matrix-appservice-slack"; + registrationFile = "${dataDir}/slack-registration.yaml"; + #appDir = "${pkgs.matrix-appservice-slack}/${pkgs.matrix-appservice-slack.passthru.nodeAppDir}"; + cfg = config.services.matrix-appservice-slack; + # TODO: switch to configGen.json once RFC42 is implemented + settingsFile = pkgs.writeText "matrix-appservice-slack-settings.json" (builtins.toJSON cfg.settings); + +in +{ + options = { + services.matrix-appservice-slack = { + enable = mkEnableOption "a bridge between Matrix and Slack"; + + settings = mkOption rec { + # TODO: switch to types.config.json as prescribed by RFC42 once it's implemented + type = types.attrs; + apply = recursiveUpdate default; + default = { + # empty values necessary for registration file generation + # actual values defined in environmentFile + auth = { + clientID = ""; + botToken = ""; + }; + }; + example = literalExample '' + { + bridge = { + domain = "public-domain.tld"; + homeserverUrl = "http://public-domain.tld:8008"; + }; + } + ''; + description = '' + config.yaml configuration as a Nix attribute set. + + + + Configuration options should match those described in + + config.sample.yaml. + + + + and + should be set to match the public host name of the Matrix homeserver for webhooks and avatars to work. + + + + Secret tokens should be specified using + instead of this world-readable attribute set. + ''; + }; + + environmentFile = mkOption { + type = types.nullOr types.path; + default = null; + description = '' + File containing environment variables to be passed to the matrix-appservice-discord service, + in which secret tokens can be specified securely by defining values for + APPSERVICE_SLACK_AUTH_CLIENT_I_D and + APPSERVICE_SLACK_AUTH_BOT_TOKEN. + ''; + }; + + url = mkOption { + type = types.str; + default = "http://localhost:${toString cfg.port}"; + description = '' + The URL where the application service is listening for HS requests. + ''; + }; + + port = mkOption { + type = types.port; + default = 9898; # from https://github.com/matrix-org/matrix-appservice-slack/blob/develop/config/config.sample.yaml#L70 + description = '' + Port number on which the bridge should listen for internal communication with the Matrix homeserver. + ''; + }; + + localpart = mkOption { + type = with types; nullOr str; + default = null; + description = '' + The user_id localpart to assign to the AS. + ''; + }; + + serviceDependencies = mkOption { + type = with types; listOf str; + default = optional config.services.matrix-synapse.enable "matrix-synapse.service"; + description = '' + List of Systemd services to require and wait for when starting the application service, + such as the Matrix homeserver if it's running on the same host. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + systemd.services.matrix-appservice-slack = { + description = "A bridge between Matrix and Slack."; + + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ] ++ cfg.serviceDependencies; + after = [ "network-online.target" ] ++ cfg.serviceDependencies; + + preStart = '' + if [ ! -f '${registrationFile}' ]; then + ${pkgs.matrix-appservice-slack}/bin/matrix-appservice-slack \ + --generate-registration \ + --url=${escapeShellArg cfg.url} \ + ${optionalString (cfg.localpart != null) "--localpart=${escapeShellArg cfg.localpart}"} \ + --config='${settingsFile}' \ + --file='${registrationFile}' + fi + ''; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + + ProtectSystem = "strict"; + ProtectHome = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + + DynamicUser = true; + PrivateTmp = true; + #WorkingDirectory = appDir; + StateDirectory = baseNameOf dataDir; + UMask = 0027; + EnvironmentFile = cfg.environmentFile; + + ExecStart = '' + ${pkgs.matrix-appservice-slack}/bin/matrix-appservice-slack \ + --file='${registrationFile}' \ + --config='${settingsFile}' \ + --port='${toString cfg.port}' + ''; + }; + }; + }; + + meta.maintainers = with maintainers; [ chickensoupandrice ]; +} + diff --git a/profiles/matrix/mautrix-whatsapp.nix b/profiles/matrix/mautrix-whatsapp.nix new file mode 100644 index 00000000..91431e9e --- /dev/null +++ b/profiles/matrix/mautrix-whatsapp.nix @@ -0,0 +1,97 @@ +{ lib, config, pkgs, ... }: + +with lib; + +let + cfg = config.services.mautrix-whatsapp; + + configFile = pkgs.runCommand "mautrix-whatsapp" + { + buildInputs = [ pkgs.mautrix-whatsapp pkgs.remarshal ]; + preferLocalBuild = true; + } '' + mkdir -p $out + ${pkgs.remarshal}/bin/json2yaml -i ${pkgs.writeText "config.json" (builtins.toJSON cfg.configOptions)} \ + -o $out/config.yaml + + ${pkgs.mautrix-whatsapp}/bin/mautrix-whatsapp -c $out/config.yaml -g -r $out/registration.yaml + ''; + +in +{ + options.services.mautrix-whatsapp = { + enable = mkEnableOption "Mautrix-whatsapp, a puppeting bridge between Matrix and WhatsApp."; + + configOptions = mkOption { + type = types.attrs; + description = '' + This options will be transform in YAML configuration file for the bridge + + Look here for documentation. + ''; + example = { + configOptions = { + homeserver = { + address = https://matrix.org; + domain = "matrix.org"; + }; + appservice = { + address = http://localhost:8080; + hostname = "0.0.0.0"; + port = 8080; + database = { + type = "sqlite3"; + uri = "/var/lib/mautrix-whatsapp/mautrix-whatsapp.db"; + }; + state_store_path = "/var/lib/mautrix-whatsapp/mx-state.json"; + id = "whatsapp"; + bot = { + username = "whatsappbot"; + displayname = "WhatsApp bridge bot"; + avatar = "mxc://maunium.net/NeXNQarUbrlYBiPCpprYsRqr"; + }; + as_token = ""; + hs_token = ""; + }; + bridge = { + username_template = "whatsapp_{{.}}"; + displayname_template = "{{if .Notify}}{{.Notify}}{{else}}{{.Jid}}{{end}} (WA)"; + command_prefix = "!wa"; + permissions = { + "@example:matrix.org" = 100; + }; + }; + logging = { + directory = "/var/lib/mautrix-whatsapp/logs"; + file_name_format = "{{.Date}}-{{.Index}}.log"; + file_date_format = "\"2006-01-02\""; + file_mode = 384; + timestamp_format = "Jan _2, 2006 15:04:05"; + print_level = "debug"; + }; + }; + }; + }; + }; + + config = mkIf cfg.enable { + systemd.services.mautrix-whatsapp = { + description = "Mautrix-WhatsApp Service - A WhatsApp bridge for Matrix"; + after = [ "network.target" "matrix-synapse.service" ]; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + DynamicUser = true; + StateDirectory = "mautrix-whatsapp"; + LoggingDir = "mautrix-whatsapp"; + ExecStart = '' + ${pkgs.mautrix-whatsapp}/bin/mautrix-whatsapp -c "${configFile}/config.yaml" + ''; + Restart = "on-failure"; + }; + }; + + #services.matrix-synapse.app_service_config_files = [ "${configFile}/registration.yaml" ]; + + }; +} diff --git a/profiles/matrix/mod-mx-puppet-slack.nix b/profiles/matrix/mod-mx-puppet-slack.nix new file mode 100644 index 00000000..602cd615 --- /dev/null +++ b/profiles/matrix/mod-mx-puppet-slack.nix @@ -0,0 +1,125 @@ +{ config, pkgs, lib, ... }: + +with lib; + +let + dataDir = "/var/lib/mx-puppet-slack"; + registrationFile = "${dataDir}/slack-registration.yaml"; + cfg = config.services.mx-puppet-slack; + settingsFormat = pkgs.formats.json { }; + settingsFile = settingsFormat.generate "mx-puppet-slack-config.json" cfg.settings; + mx-puppet-slack = pkgs.callPackage ./pkg-mx-puppet-slack.nix { }; + +in +{ + options = { + services.mx-puppet-slack = { + enable = mkEnableOption '' + mx-puppet-slack is a slack puppeting bridge for matrix. + It handles bridging private and group DMs, as well as Guilds (servers) + ''; + + settings = mkOption rec { + apply = recursiveUpdate default; + inherit (settingsFormat) type; + default = { + bridge.port = 8434; + presence = { + enabled = true; + interval = 500; + }; + provisioning.whitelist = [ ]; + relay.whitelist = [ ]; + + # variables are preceded by a colon. + namePatterns = { + user = ":name"; + userOverride = ":displayname"; + room = ":name"; + group = ":name"; + }; + + #defaults to sqlite but can be configured to use postgresql with + #connstring + database.filename = "${dataDir}/database.db"; + logging = { + console = "info"; + lineDateFormat = "MMM-D HH:mm:ss.SSS"; + }; + }; + example = literalExpression '' + { + bridge = { + bindAddress = "localhost"; + domain = "example.com"; + homeserverUrl = "https://example.com"; + }; + + provisioning.whitelist = [ "@admin:example.com" ]; + relay.whitelist = [ "@.*:example.com" ]; + } + ''; + description = '' + config.yaml configuration as a Nix attribute set. + Configuration options should match those described in + + sample.config.yaml. + ''; + }; + serviceDependencies = mkOption { + type = with types; listOf str; + default = optional config.services.matrix-synapse.enable "matrix-synapse.service"; + description = '' + List of Systemd services to require and wait for when starting the application service. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + systemd.services.mx-puppet-slack = { + description = '' + mx-puppet-slack is a slack puppeting bridge for matrix. + It handles bridging private and group DMs, as well as Guilds (servers). + ''; + + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ] ++ cfg.serviceDependencies; + after = [ "network-online.target" ] ++ cfg.serviceDependencies; + + preStart = '' + # generate the appservice's registration file if absent + if [ ! -f '${registrationFile}' ]; then + ${mx-puppet-slack}/bin/mx-puppet-slack -r -c ${settingsFile} \ + -f ${registrationFile} + fi + ''; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + + ProtectSystem = "strict"; + ProtectHome = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + + DynamicUser = true; + PrivateTmp = true; + WorkingDirectory = mx-puppet-slack; + StateDirectory = baseNameOf dataDir; + UMask = 0027; + + ExecStart = '' + ${mx-puppet-slack}/bin/mx-puppet-slack \ + -c ${settingsFile} \ + -f ${registrationFile} + ''; + }; + }; + }; + + meta.maintainers = with maintainers; [ chickensoupwithrice ]; +} + diff --git a/profiles/metrics/default.nix b/profiles/metrics/default.nix new file mode 100644 index 00000000..d94655b9 --- /dev/null +++ b/profiles/metrics/default.nix @@ -0,0 +1,159 @@ +{ config, pkgs, ... }: { + # grafana configuration + #services.grafana = { + # enable = true; + # domain = "grafana.mossnet.lan"; + # port = 2342; + # addr = "127.0.0.1"; + #}; + # + ## nginx reverse proxy + #services.nginx.virtualHosts.${config.services.grafana.domain} = { + # locations."/" = { + # proxyPass = "http://127.0.0.1:${toString config.services.grafana.port}"; + # proxyWebsockets = true; + # }; + #}; + + services.prometheus = { + enable = true; + port = 9001; + exporters = { + node = { + enable = true; + enabledCollectors = [ "systemd" ]; + port = 9002; + }; + }; + rules = [ + '' + groups: + - name: synapse + rules: + - record: "synapse_federation_transaction_queue_pendingEdus:total" + expr: "sum(synapse_federation_transaction_queue_pendingEdus or absent(synapse_federation_transaction_queue_pendingEdus)*0)" + - record: "synapse_federation_transaction_queue_pendingPdus:total" + expr: "sum(synapse_federation_transaction_queue_pendingPdus or absent(synapse_federation_transaction_queue_pendingPdus)*0)" + - record: 'synapse_http_server_request_count:method' + labels: + servlet: "" + expr: "sum(synapse_http_server_request_count) by (method)" + - record: 'synapse_http_server_request_count:servlet' + labels: + method: "" + expr: 'sum(synapse_http_server_request_count) by (servlet)' + + - record: 'synapse_http_server_request_count:total' + labels: + servlet: "" + expr: 'sum(synapse_http_server_request_count:by_method) by (servlet)' + + - record: 'synapse_cache:hit_ratio_5m' + expr: 'rate(synapse_util_caches_cache:hits[5m]) / rate(synapse_util_caches_cache:total[5m])' + - record: 'synapse_cache:hit_ratio_30s' + expr: 'rate(synapse_util_caches_cache:hits[30s]) / rate(synapse_util_caches_cache:total[30s])' + + - record: 'synapse_federation_client_sent' + labels: + type: "EDU" + expr: 'synapse_federation_client_sent_edus + 0' + - record: 'synapse_federation_client_sent' + labels: + type: "PDU" + expr: 'synapse_federation_client_sent_pdu_destinations:count + 0' + - record: 'synapse_federation_client_sent' + labels: + type: "Query" + expr: 'sum(synapse_federation_client_sent_queries) by (job)' + + - record: 'synapse_federation_server_received' + labels: + type: "EDU" + expr: 'synapse_federation_server_received_edus + 0' + - record: 'synapse_federation_server_received' + labels: + type: "PDU" + expr: 'synapse_federation_server_received_pdus + 0' + - record: 'synapse_federation_server_received' + labels: + type: "Query" + expr: 'sum(synapse_federation_server_received_queries) by (job)' + + - record: 'synapse_federation_transaction_queue_pending' + labels: + type: "EDU" + expr: 'synapse_federation_transaction_queue_pending_edus + 0' + - record: 'synapse_federation_transaction_queue_pending' + labels: + type: "PDU" + expr: 'synapse_federation_transaction_queue_pending_pdus + 0' + + - record: synapse_storage_events_persisted_by_source_type + expr: sum without(type, origin_type, origin_entity) (synapse_storage_events_persisted_events_sep{origin_type="remote"}) + labels: + type: remote + - record: synapse_storage_events_persisted_by_source_type + expr: sum without(type, origin_type, origin_entity) (synapse_storage_events_persisted_events_sep{origin_entity="*client*",origin_type="local"}) + labels: + type: local + - record: synapse_storage_events_persisted_by_source_type + expr: sum without(type, origin_type, origin_entity) (synapse_storage_events_persisted_events_sep{origin_entity!="*client*",origin_type="local"}) + labels: + type: bridges + - record: synapse_storage_events_persisted_by_event_type + expr: sum without(origin_entity, origin_type) (synapse_storage_events_persisted_events_sep) + - record: synapse_storage_events_persisted_by_origin + expr: sum without(type) (synapse_storage_events_persisted_events_sep) + '' + ]; + scrapeConfigs = [ + { + job_name = "helix"; + static_configs = [{ + targets = [ "127.0.0.1:${toString config.services.prometheus.exporters.node.port}" ]; + }]; + } + { + job_name = "synapse"; + metrics_path = "/_synapse/metrics"; + static_configs = [{ + targets = [ "localhost:9090" ]; + }]; + } + { + job_name = "gitea"; + static_configs = [{ + targets = [ "localhost:3001" ]; + }]; + } + ]; + }; + + networking.firewall = { + enable = true; + allowedTCPPorts = [ 9001 ]; + }; + + services.nginx.virtualHosts."sealight.xyz" = { + locations."/metrics" = { + #basicAuth = { anish = "password"; }; + proxyPass = "http://localhost:9001"; + }; + }; + + services.loki = { + enable = false; # TODO + #configFile = /var/loki-config.yaml; + }; + + # systemd.services.promtail = { + # description = "Promtail service for Loki"; + # wantedBy = [ "multi-user.target" ]; + + # serviceConfig = { + # ExecStart = '' + # ${pkgs.grafana-loki}/bin/promtail --config.file ${/var/promtail.yaml} + # ''; + # }; + # }; +} diff --git a/profiles/mimetypes/default.nix b/profiles/mimetypes/default.nix new file mode 100644 index 00000000..6e6e61ee --- /dev/null +++ b/profiles/mimetypes/default.nix @@ -0,0 +1,19 @@ +{ pkgs, lib, ... }: + +{ + xdg.mime.defaultApplications = { + "application/pdf" = "firefox.desktop"; + "image/png" = [ + "sxiv.desktop" + "feh.desktop" + ]; + "image/jpg" = [ + "sxiv.desktop" + "feh.desktop" + ]; + "image/jpeg" = [ + "sxiv.desktop" + "feh.desktop" + ]; + }; +} diff --git a/profiles/monitoring/default.nix b/profiles/monitoring/default.nix new file mode 100644 index 00000000..c652a5ab --- /dev/null +++ b/profiles/monitoring/default.nix @@ -0,0 +1,60 @@ +{ config, pkgs, ... }: { + # grafana configuration + services.grafana = { + enable = true; + domain = "stats.mossnet.lan"; + port = 2342; + addr = "127.0.0.1"; + }; + + # nginx reverse proxy + services.nginx.recommendedProxySettings = true; # Needed for new grafana versions + services.nginx.virtualHosts.${config.services.grafana.domain} = { + locations."/" = { + proxyPass = "http://127.0.0.1:${toString config.services.grafana.port}"; + proxyWebsockets = true; + }; + }; + + services.prometheus = { + enable = true; + port = 9001; + exporters = { + node = { + enable = true; + enabledCollectors = [ "systemd" ]; + port = 9002; + }; + dnsmasq = { + enable = true; + port = 9153; + }; + }; + scrapeConfigs = [ + { + job_name = "box"; + static_configs = [{ targets = [ "127.0.0.1:${toString config.services.prometheus.exporters.node.port}" ]; }]; + } + { + job_name = "dns"; + static_configs = [{ targets = [ "127.0.0.1:${toString config.services.prometheus.exporters.dnsmasq.port}" ]; }]; + } + ]; + }; + + services.loki = { + #enable = true; + #configFile = /var/loki-config.yaml; + }; + + #systemd.services.promtail = { + # description = "Promtail service for Loki"; + # wantedBy = [ "multi-user.target" ]; + + # serviceConfig = { + # ExecStart = '' + # ${pkgs.grafana-loki}/bin/promtail --config.file ${/var/promtail.yaml} + # ''; + # }; + #}; +} diff --git a/profiles/mossnet-hosts/default.nix b/profiles/mossnet-hosts/default.nix new file mode 100644 index 00000000..763fa9d6 --- /dev/null +++ b/profiles/mossnet-hosts/default.nix @@ -0,0 +1,14 @@ +{ + networking.extraHosts = '' + 192.168.1.240 mossnet.lan + 192.168.1.240 links.mossnet.lan + 192.168.1.240 read.mossnet.lan + 192.168.1.240 music.mossnet.lan + 192.168.1.240 stats.mossnet.lan + 192.168.1.240 file.mossnet.lan + ''; + # 10.0.69.4 mossnet.lan + # 10.0.69.4 links.mossnet.lan + # 10.0.69.4 read.mossnet.lan + # 10.0.69.4 stats.mossnet.lan +} diff --git a/profiles/mount-mossnet/default.nix b/profiles/mount-mossnet/default.nix new file mode 100644 index 00000000..ded0cc48 --- /dev/null +++ b/profiles/mount-mossnet/default.nix @@ -0,0 +1,9 @@ +{ pkgs, lib, ... }: + +{ + fileSystems."/mnt/mossnet" = { + device = "10.0.69.4:/mnt/two"; + fsType = "nfs"; + options = [ "noatime" ]; + }; +} diff --git a/profiles/music/default.nix b/profiles/music/default.nix new file mode 100644 index 00000000..350df3ae --- /dev/null +++ b/profiles/music/default.nix @@ -0,0 +1,62 @@ +{ pkgs, lib, ... }: + +{ + environment.systemPackages = with pkgs; [ + qjackctl + libjack2 # needed for overtone with pipewire + jack2 # needed for overtone with pipewire + + # GUI + carla + + # Plugins + helm + # surge + distrho + orca-c + supercollider + dirt + sunvox + vcv-rack + lmms + bespokesynth + lsp-plugins + helio-workstation + projectm # milkdrop visualizer + + # DAWs + # ardour + # reaper + renoise + ]; + + hardware.pulseaudio.enable = lib.mkForce false; + security.rtkit.enable = true; + + services.pipewire = { + enable = true; + alsa.enable = true; + alsa.support32Bit = true; + pulse.enable = true; + jack.enable = true; + config = { + pipewire."context.properties"."default.clock.rate" = "48000"; + pipewire-pulse."stream.properties"."resample.quality" = 15; + client."stream.properties"."resample.quality" = 15; + client-rt."stream.properties"."resample.quality" = 15; + #jack."context.modules" = []; + }; + #media-session.config.bluez-monitor.properties = { + # "bluez5.headset-roles" = [ "hsp_hs" "hsp_ag" ]; + # "bluez5.codecs" = [ "aac" "ldac" "aptx_hd" ]; + #}; + }; + + #systemd.services.bluethoot.serviceConfig.ExecStart = [ + # "" + # "${config.hardware.bluetooth.package}/libexec/bluetooth/bluetoothd --noplugin=sap" + #]; + boot.kernelModules = [ "snd-seq" "snd-rawmidi" ]; # midi sequence kernel mods + hardware.pulseaudio.package = pkgs.pulseaudio.override { jackaudioSupport = true; }; + +} diff --git a/profiles/nextcloud/default.nix b/profiles/nextcloud/default.nix new file mode 100644 index 00000000..76105c34 --- /dev/null +++ b/profiles/nextcloud/default.nix @@ -0,0 +1,60 @@ +{ pkgs, config, ... }: +{ + #age.secrets.nextcloud-db.file = "/etc/nixos/secrets/nextcloud-db.age"; + #age.secrets.nextcloud-db.owner = "nextcloud"; + #age.secrets.nextcloud-admin.file = "/etc/nixos/secrets/nextcloud-admin.age"; + #age.secrets.nextcloud-admin.owner = "nextcloud"; + services.nextcloud = { + enable = true; + hostName = "mossnet.lan"; + home = "/data/nextcloud2"; + package = pkgs.nextcloud22; + + # Use HTTPS for links + https = false; + + # Auto-update Nextcloud Apps + autoUpdateApps.enable = true; + # Set what time makes sense for you + autoUpdateApps.startAt = "05:00:00"; + + config = { + # Further forces Nextcloud to use HTTPS + # overwriteProtocol = "https"; + + # Nextcloud PostegreSQL database configuration, recommended over using SQLite + dbtype = "pgsql"; + dbuser = "nextcloud2"; + dbhost = "/run/postgresql"; # nextcloud will add /.s.PGSQL.5432 by itself + dbname = "nextcloud2"; + dbpassFile = "/var/nextcloud-db-pass"; + + adminpassFile = "/var/nextcloud-admin-pass"; + adminuser = "admin"; + }; + }; + + # Enable PostgreSQL + services.postgresql = { + enable = true; + + # Ensure the database, user, and permissions always exist + ensureDatabases = [ "nextcloud" ]; + ensureUsers = [ + { + name = "nextcloud"; + ensurePermissions."DATABASE nextcloud" = "ALL PRIVILEGES"; + } + ]; + }; + + # Ensure that postgres is running before running the setup + systemd.services."nextcloud-setup" = { + requires = [ "postgresql.service" ]; + after = [ "postgresql.service" ]; + }; + + networking.firewall.allowedTCPPorts = [ 80 443 ]; + + #nixpkgs.config.permittedInsecurePackages = [ "nextcloud-19.0.6"]; +} diff --git a/profiles/nfs/default.nix b/profiles/nfs/default.nix new file mode 100644 index 00000000..bf09097a --- /dev/null +++ b/profiles/nfs/default.nix @@ -0,0 +1,35 @@ +{ + #fileSystems."/export/" = { + # device = "/mnt/mafuyu"; + # options = [ "bind" ]; + #}; + + services.nfs.server = { + enable = true; + # fixed rpc.statd port; for firewall + lockdPort = 4001; + mountdPort = 4002; + statdPort = 4000; + extraNfsdConfig = ''''; + exports = '' + /home/ftp 192.168.1.0/24(rw) + /mnt/one 192.168.1.0/24(rw) + /mnt/two 192.168.1.0/24(rw,no_subtree_check) 10.0.69.0/24(rw,no_subtree_check) + /mnt/three 192.168.1.0/24(rw) + ''; + }; + + networking.firewall = { + allowedTCPPorts = [ 111 2049 4000 4001 4002 20048 ]; + allowedUDPPorts = [ 111 2049 4000 4001 4002 20048 ]; + }; + + #systemd.services.create-mount-dir = { + # serviceConfig = { + # ExecStart = "mkdir /export"; + # }; + # wantedBy = [ "multi-user.target" ]; + # after = [ "remote-fs.target" ]; + # description = "Create a directory we can mount on fs"; + #}; +} diff --git a/profiles/radicale/default.nix b/profiles/radicale/default.nix new file mode 100644 index 00000000..e08af459 --- /dev/null +++ b/profiles/radicale/default.nix @@ -0,0 +1,24 @@ +{ config, lib, pkgs, ... }: +{ + services.radicale = { + enable = true; + package = pkgs.radicale; + settings = { + server.hosts = [ "0.0.0.0:5252" ]; + }; + }; + + networking.firewall.allowedTCPPorts = [ 5252 ]; + + services.nginx.virtualHosts."cal.mossnet.lan" = { + enableACME = false; + forceSSL = false; + + locations."/" = { + extraConfig = '' + proxy_pass http://localhost:5252/; + proxy_set_header X-Forwarded-Host $host; + ''; + }; + }; +} diff --git a/profiles/rss-bridge/default.nix b/profiles/rss-bridge/default.nix new file mode 100644 index 00000000..94e7f7ef --- /dev/null +++ b/profiles/rss-bridge/default.nix @@ -0,0 +1,11 @@ +{ pkgs, lib, config, ... }: +{ + services.rss-bridge = { + enable = true; + virtualHost = "bridge.sealight.xyz"; + whitelist = [ "Facebook" "Bandcamp" "Twitter" "Telegram" "Instagram" "Reddit" ]; + }; + + #services.nginx.virtualHosts."bridge.sealight.xyz".forceSSL = true; + #services.nginx.virtualHosts."bridge.sealight.xyz".enableACME = true; +} diff --git a/profiles/seafile/default.nix b/profiles/seafile/default.nix new file mode 100644 index 00000000..13d7e2ae --- /dev/null +++ b/profiles/seafile/default.nix @@ -0,0 +1,54 @@ +{ pkgs, ... }: + +{ + services.seafile = { + enable = true; + seafileSettings = { + fileserver.host = "0.0.0.0"; + fileserver.port = 8082; + }; + ccnetSettings.General.SERVICE_URL = "http://file.mossnet.lan"; + adminEmail = "anish@lakhwara.com"; + initialAdminPassword = "arandompasswordsecure!"; + }; + + services.nginx = { + enable = true; + }; + services.nginx.upstreams."gunicorn_seafile" = { + servers."unix:/run/seahub/gunicorn.sock" = { }; + }; + services.nginx.upstreams."seafhttp" = { + servers."127.0.0.1:8082" = { }; + }; + services.nginx.virtualHosts."file.mossnet.lan" = { + serverName = "file.mossnet.lan"; + locations."/" = { + proxyPass = "http://gunicorn_seafile"; # without a trailing / + extraConfig = '' + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Host $server_name; + #proxy_set_header Host $host; + proxy_read_timeout 1200s; + + client_max_body_size 0; # disable max upload size + ''; + }; + locations."/seafhttp" = { + proxyPass = "http://seafhttp"; # without a trailing / + extraConfig = '' + rewrite ^/seafhttp(.*)$ $1 break; + client_max_body_size 0; + + proxy_connect_timeout 36000s; + proxy_read_timeout 36000s; + proxy_send_timeout 36000s; + + proxy_request_buffering off; + send_timeout 36000s; + ''; + }; + }; +} diff --git a/profiles/sealight-website/default.nix b/profiles/sealight-website/default.nix new file mode 100644 index 00000000..e81bbf2b --- /dev/null +++ b/profiles/sealight-website/default.nix @@ -0,0 +1,14 @@ +{ + # services.nginx = { + # enable = true; + # virtualHosts = { + # "sealight.xyz" = { + # forceSSL = true; + # enableACME = true; + # locations."/" = { + # root = "/var/www/sealight.xyz"; + # }; + # }; + # }; + # }; +} diff --git a/profiles/secrets/default.nix b/profiles/secrets/default.nix new file mode 100644 index 00000000..3fc78875 --- /dev/null +++ b/profiles/secrets/default.nix @@ -0,0 +1,9 @@ +{ self, pkgs, config, lib, ... }: +{ + # Secrets used by home-manager modules + age.secrets.fastmail.file = "${self}/secrets/fastmail.age"; + age.secrets.fastmail.owner = "anish"; + + age.secrets.mossnet.file = "${self}/secrets/mossnet.age"; + age.secrets.mossnet.owner = "anish"; +} diff --git a/profiles/server/default.nix b/profiles/server/default.nix new file mode 100644 index 00000000..34ea2db8 --- /dev/null +++ b/profiles/server/default.nix @@ -0,0 +1,10 @@ +{ config, ... }: +{ + services.openssh = { + enable = true; + passwordAuthentication = false; + permitRootLogin = "no"; + }; + networking.firewall.allowedTCPPorts = [ 80 433 22 ]; # ssh and website + security.sudo.wheelNeedsPassword = false; # needed for deploy-rs +} diff --git a/profiles/shaarli/default.nix b/profiles/shaarli/default.nix new file mode 100644 index 00000000..517314de --- /dev/null +++ b/profiles/shaarli/default.nix @@ -0,0 +1,114 @@ +{ pkgs, config, ... }: +let + dataDir = "/var/www/shaarli-config"; + name = "shaarli"; +in +{ + services.nginx = { + enable = true; + virtualHosts = { + "links.mossnet.lan" = { + forceSSL = false; + enableACME = false; + root = "${dataDir}"; + extraConfig = '' + index index.php; + ''; + locations = { + "/".extraConfig = '' + index index.php; + try_files _ /index.php$is_args$args; + ''; + + "~ (index)\\.php$".extraConfig = '' + try_files $uri =404; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + + fastcgi_pass unix:${config.services.phpfpm.pools."${name}".socket}; + fastcgi_index index.php; + + fastcgi_param QUERY_STRING $query_string; + fastcgi_param REQUEST_METHOD $request_method; + fastcgi_param CONTENT_TYPE $content_type; + fastcgi_param CONTENT_LENGTH $content_length; + + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_param SCRIPT_NAME $fastcgi_script_name; + fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; + fastcgi_param REQUEST_URI $request_uri; + fastcgi_param DOCUMENT_URI $document_uri; + fastcgi_param DOCUMENT_ROOT $document_root; + fastcgi_param SERVER_PROTOCOL $server_protocol; + + fastcgi_param GATEWAY_INTERFACE CGI/1.1; + fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; + + fastcgi_param REMOTE_ADDR $remote_addr; + fastcgi_param REMOTE_PORT $remote_port; + fastcgi_param SERVER_ADDR $server_addr; + fastcgi_param SERVER_PORT $server_port; + fastcgi_param SERVER_NAME $server_name; + ''; + + "~ \\.php$".extraConfig = '' + deny all; + ''; + + "^~ /tpl/".extraConfig = "alias ${pkgs.shaarli}/tpl/;"; + + "^~ /plugins/".extraConfig = "alias ${pkgs.shaarli}/plugins/;"; + + "~* \\.(?:ico|css|js|gif|jpe?g|png)$".extraConfig = '' + expires max; + add_header Pragma public; + add_header Cache-Control "public, must-revalidate, proxy-revalidate"; + ''; + }; + }; + }; + }; + + services.phpfpm = { + pools = { + "${name}" = { + user = "nginx"; + group = "nginx"; + #listen = "/run/phpfpm/php.sock"; + settings = { + "listen.owner" = "nginx"; + "listen.group" = "nginx"; + "user" = "nginx"; + "pm" = "dynamic"; + "pm.max_children" = "4"; + "pm.min_spare_servers" = "1"; + "pm.max_spare_servers" = "4"; + "pm.max_requests" = "32"; + "catch_workers_output" = "1"; + "php_admin_value[error_log]" = "/var/log/nginx/${name}-phpfpm-error.log"; + }; + }; + }; + }; + users.extraUsers."${name}" = { group = "${name}"; }; + users.extraGroups."${name}" = { }; + users.users.shaarli.isSystemUser = true; + systemd.services.shaarli-install = { + serviceConfig.Type = "oneshot"; + wantedBy = [ "multi-user.target" ]; + script = '' + if [ ! -d "${dataDir}" ]; then + #cp -R ${pkgs.shaarli}/data.orig/.htaccess ${dataDir}/cache/ + #cp -R ${pkgs.shaarli}/data.orig/.htaccess ${dataDir}/data/ + #cp -R ${pkgs.shaarli}/data.orig/.htaccess ${dataDir}/pagecache/ + #cp -R ${pkgs.shaarli}/data.orig/.htaccess ${dataDir}/tmp/ + mkdir -p ${dataDir}/{cache,data,pagecache,tmp} + ln -s ${pkgs.shaarli}/* ${dataDir} + fi + chown -Rc nginx:nginx ${dataDir} + find ${dataDir} -type d ! -perm 0700 -exec chmod 0700 {} \; -exec chmod g-s {} \; + find ${dataDir} -type f ! -perm 0600 -exec chmod 0600 {} \; + ''; + }; + #networking.firewall.allowedTCPPorts = [ 80 ]; +} diff --git a/profiles/site/default.nix b/profiles/site/default.nix new file mode 100644 index 00000000..18a074ed --- /dev/null +++ b/profiles/site/default.nix @@ -0,0 +1,6 @@ +{ self, pkgs, ... }: +{ + services."anish.lakhwara.com".enable = true; + security.acme.email = "anish+acme@lakhwara.com"; + security.acme.acceptTerms = true; +} diff --git a/profiles/sync/cal/default.nix b/profiles/sync/cal/default.nix new file mode 100644 index 00000000..e89e300f --- /dev/null +++ b/profiles/sync/cal/default.nix @@ -0,0 +1,21 @@ +{ pkgs, ... }: + +{ + systemd.services.vdir-sync = { + serviceConfig.Type = "oneshot"; + path = [ + pkgs.vdirsyncer + ]; + script = '' + vdirsyncer sync + ''; + serviceConfig = { + User = "anish"; + }; + }; + systemd.timers.vdir-sync = { + wantedBy = [ "timers.target" ]; + partOf = [ "vdir-sync.service" ]; + timerConfig.OnCalendar = [ "hourly" ]; + }; +} diff --git a/profiles/sync/kitaab/default.nix b/profiles/sync/kitaab/default.nix new file mode 100644 index 00000000..b3e626b7 --- /dev/null +++ b/profiles/sync/kitaab/default.nix @@ -0,0 +1,26 @@ +{ pkgs, ... }: + +{ + systemd.services.kitaab-sync = { + serviceConfig.Type = "oneshot"; + path = [ + pkgs.git + pkgs.coreutils + ]; + script = '' + cd /home/anish/kitaab + git add -A + git diff-index --quiet HEAD || git commit -m 'syncing kitaab' # if nothing, don't exit 1 + git push + exit 0 + ''; + serviceConfig = { + User = "anish"; + }; + }; + systemd.timers.kitaab-sync = { + wantedBy = [ "timers.target" ]; + partOf = [ "kitaab-sync.service" ]; + timerConfig.OnCalendar = [ "hourly" ]; + }; +} diff --git a/profiles/sync/music/default.nix b/profiles/sync/music/default.nix new file mode 100644 index 00000000..4c070e43 --- /dev/null +++ b/profiles/sync/music/default.nix @@ -0,0 +1,20 @@ +{ pkgs, lib, ... }: + +{ + systemd.services.get-music-sync = { + serviceConfig.Type = "oneshot"; + path = [ + pkgs.coreutils + pkgs.rsync + ]; + script = builtins.readFile ./get-music.sh; + serviceConfig = { + User = "anish"; + }; + }; + systemd.timers.get-music-timer = { + wantedBy = [ "timers.target" ]; + partOf = [ "get-music-sync.service" ]; + timerConfig.OnCalendar = [ "daily" ]; + }; +} diff --git a/profiles/sync/music/get-music.sh b/profiles/sync/music/get-music.sh new file mode 100755 index 00000000..2269bb89 --- /dev/null +++ b/profiles/sync/music/get-music.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +rsync -r --ignore-existing --log-file=/data/incoming/download-log hypercube@talos.feralhosting.com:private/transmission/data/* /data/incoming + +# you need to set defaults for beets +# if already imported -> Skip +# Auto accept changes +# also install it lmao +#beet import /data/incoming + diff --git a/profiles/sync/website/default.nix b/profiles/sync/website/default.nix new file mode 100644 index 00000000..af7b00c1 --- /dev/null +++ b/profiles/sync/website/default.nix @@ -0,0 +1,35 @@ +{ pkgs, inputs, ... }: + +{ + systemd.services.website-deploy = { + serviceConfig.Type = "oneshot"; + path = [ + pkgs.git + pkgs.coreutils + pkgs.nixUnstable + pkgs.openssh + inputs.deploy.packages.${pkgs.system}.deploy-rs + ]; + script = '' + cd /etc/nixos/ # TODO make variable + nix flake lock --update-input poonam + nix flake lock --update-input basant + # TODO + # git add flake.lock + # git commit -m "update website" + # git push + deploy .#cube --hostname lakhwara.com + exit 0 + ''; + serviceConfig = { + User = "anish"; + }; + }; + systemd.timers.website-deploy = { + after = [ "kitaab-sync.timer" ]; + wantedBy = [ "timers.target" ]; + partOf = [ "website-deploy.service" ]; + timerConfig.OnCalendar = [ "daily" ]; + timerConfig.persistent = "true"; + }; +} diff --git a/profiles/syncthing/default.nix b/profiles/syncthing/default.nix new file mode 100644 index 00000000..142bfdd5 --- /dev/null +++ b/profiles/syncthing/default.nix @@ -0,0 +1,14 @@ +{ pkgs, ... }: + +{ + services.syncthing = { + enable = true; + user = "anish"; + group = "users"; + dataDir = "/home/anish/"; + configDir = "/home/anish/.config/syncthing"; + }; + + networking.firewall.allowedTCPPorts = [ 8384 22000 ]; + networking.firewall.allowedUDPPorts = [ 22000 21027 ]; +} diff --git a/profiles/taskd/default.nix b/profiles/taskd/default.nix new file mode 100644 index 00000000..64a914f6 --- /dev/null +++ b/profiles/taskd/default.nix @@ -0,0 +1,9 @@ +{ config, pkgs, ... }: + +{ + services.taskserver.enable = true; + services.taskserver.fqdn = "task.moss"; + services.taskserver.listenHost = "0.0.0.0"; + services.taskserver.listenPort = 53589; + services.taskserver.organisations.mossnet.users = [ "anish" ]; +} diff --git a/profiles/wallabag/default.nix b/profiles/wallabag/default.nix new file mode 100644 index 00000000..be36de0c --- /dev/null +++ b/profiles/wallabag/default.nix @@ -0,0 +1,100 @@ +{ pkgs, config, lib, ... }: + +{ + services.postgresql = { + enable = true; + package = pkgs.postgresql_11; + + # Ensure the database, user, and permissions always exist + ensureDatabases = [ "wallabag" ]; + ensureUsers = [ + { + name = "wallabag"; + ensurePermissions."DATABASE wallabag" = "ALL PRIVILEGES"; + } + ]; + }; + + services.wallabag = { + enable = true; + hostName = "read.mossnet.lan"; + package = pkgs.wallabag; + conf = '' + # This file is a "template" of what your parameters.yml file should look like + parameters: + # Uncomment these settings or manually update your parameters.yml + # to use docker-compose + # + # database_driver: %env.database_driver% + # database_host: %env.database_host% + # database_port: %env.database_port% + # database_name: %env.database_name% + # database_user: %env.database_user% + # database_password: %env.database_password% + + database_driver: pdo_pgsql + database_host: localhost + database_port: ~ + database_name: wallabag + database_user: wallabag + database_password: wallabag + # For SQLite, database_path should be "%kernel.project_dir%/data/db/wallabag.sqlite" + database_path: ~ + database_table_prefix: wallabag_ + database_socket: null + # with PostgreSQL and SQLite, you must set "utf8" + database_charset: utf8 + + domain_name: http://read.mossnet.lan + server_name: "mossnet wallabag instance" + + mailer_transport: smtp + mailer_user: ~ + mailer_password: ~ + mailer_host: 127.0.0.1 + mailer_port: false + mailer_encryption: ~ + mailer_auth_mode: ~ + + locale: en + + # A secret key that's used to generate certain security-related tokens + secret: SAFGOECRIlfal89oe6u0(*^dsaaih961 + + # two factor stuff + twofactor_auth: true + twofactor_sender: no-reply@wallabag.org + + # fosuser stuff + fosuser_registration: true + fosuser_confirmation: true + + # how long the access token should live in seconds for the API + fos_oauth_server_access_token_lifetime: 3600 + # how long the refresh token should life in seconds for the API + fos_oauth_server_refresh_token_lifetime: 1209600 + + from_email: no-reply@wallabag.org + + rss_limit: 50 + + # RabbitMQ processing + rabbitmq_host: localhost + rabbitmq_port: 5672 + rabbitmq_user: guest + rabbitmq_password: guest + rabbitmq_prefetch_count: 10 + + # Redis processing + redis_scheme: tcp + redis_host: localhost + redis_port: 6379 + redis_path: null + redis_password: null + + # sentry logging + sentry_dsn: ~ + ''; + }; + # networking.firewall.allowedTCPPorts = [ 8080 ]; +} diff --git a/profiles/wifi/default.nix b/profiles/wifi/default.nix new file mode 100644 index 00000000..74528ac8 --- /dev/null +++ b/profiles/wifi/default.nix @@ -0,0 +1,42 @@ +{ config, pkgs, ... }: + +{ + networking.dhcpcd.wait = "background"; + networking.dhcpcd.extraConfig = "noarp"; + networking.wireless.userControlled.enable = true; + networking.wireless.networks = { + "Chester 11403" = { + pskRaw = "43fcb0bea43633899a9885865c53ea79d268b9bdfb8c3f4013718e43e6672e5e"; + }; + "HSBNEWiFi" = { + pskRaw = "0820d84980eeb47630f13f04804fc9add684a8feebb64ba914cafc48f569d801"; + }; + "TP-LINK_1D79" = { + pskRaw = "6d960910c33a59e94b151281cc3982863b4b112d8a4efd1b165e4f8e52e7dae8"; + }; + "nadir" = { + pskRaw = "92e0c1f0b3a1bada333964f0ee4ac04e0d9ba941aa3f29216cc3782595a41e5f"; + }; + "WiFi-399631" = { + pskRaw = "2e312c9721e470847f751d8b844d264dc5e2612361a579fc0bdebd2135b5a8ea"; + }; + "line" = { + pskRaw = "ec36a5a116224c12e305c90b7f3c5a0b7417abfaacf15828748f6a1e1e316c03"; + }; + "MEHRA" = { + pskRaw = "e1573bc9e30fd68ac8a805b7c5f9871322ffcdac909746831555905c2e156abb"; + }; + "Sandeep1" = { + pskRaw = "035972401640bf4dc2d8651c0b9df515a69f6bc2bffa07cc936183128a6ccf0a"; + }; + "chadpad" = { + pskRaw = "2594b3880a60817950bd60b2770c9793fd4cb784ed183f685a52502a9df2c7b1"; + }; + # "updog" = { + # pskRaw = "be28d9e50e4d9a065f1afccad52675d0d4fabe85526c0245648671721db606b1"; + # }; + "Vodafone-07F38" = { + pskRaw = "4ffd87de73ed31ef1aee1d0d178857490afbda3f0bb8453a0baaee7b2576f302"; + }; + }; +} diff --git a/profiles/wireguard-box/default.nix b/profiles/wireguard-box/default.nix new file mode 100644 index 00000000..bc025571 --- /dev/null +++ b/profiles/wireguard-box/default.nix @@ -0,0 +1,61 @@ +{ config, pkgs, lib, ... }: + +{ + services.tailscale.enable = true; + networking.firewall.allowedUDPPorts = [ 60990 ]; + + # Enable WireGuard + networking.wireguard.interfaces = { + # "wg0" is the network interface name. You can name the interface arbitrarily. + wg0 = { + # Determines the IP address and subnet of the client's end of the tunnel interface. + ips = [ "10.0.69.4/24" ]; + listenPort = 60990; # to match firewall allowedUDPPorts (without this wg uses random port numbers) + + # Path to the private key file. + # + # Note: The private key can also be included inline via the privateKey option, + # but this makes the private key world-readable; thus, using privateKeyFile is + # recommended. + privateKeyFile = "/home/anish/wg/privkey"; + + peers = [ + # For a client configuration, one peer entry for the server will suffice. + { + # Public key of the server (not a file path). + publicKey = "c1J4p63rD3IlszugMZiki7UBV3YmDdqa3DU4UejXzAI="; + + # Forward all the traffic via VPN. + allowedIPs = [ "10.0.69.0/24" ]; + # Or forward only particular subnets + #allowedIPs = [ "10.100.0.1" "91.108.12.0/22" ]; + + # Set this to the server IP and port. + endpoint = "69.61.38.225:60990"; # ToDo: route to endpoint not automatically configured https://wiki.archlinux.org/index.php/WireGuard#Loop_routing https://discourse.nixos.org/t/solved-minimal-firewall-setup-for-wireguard-client/7577 + + # Send keepalives every 25 seconds. Important to keep NAT tables alive. + persistentKeepalive = 25; + } + ]; + }; + }; + + # boot.extraModulePackages = with config.boot.kernelPackages; [ wireguard ]; + # environment.systemPackages = [ pkgs.wireguard ]; + # networking.wireguard.enable = true; + # networking.wireguard.interfaces = { + # wg0 = { + # ips = [ "10.0.69.4/32" ]; + # privateKeyFile = "/home/anish/wg/privkey"; + # listenPort = 60990; + # + # peers = [ + # { # helix - server + # publicKey = "{c1J4p63rD3IlszugMZiki7UBV3YmDdqa3DU4UejXzAI=}"; + # allowedIPs = [ "10.0.69.1/24" ]; + # endpoint = "sealight.xyz:60990"; + # persistentKeepalive = 25; + # } ]; + # }; + # }; +} diff --git a/profiles/wireguard-server/default.nix b/profiles/wireguard-server/default.nix new file mode 100644 index 00000000..838c485a --- /dev/null +++ b/profiles/wireguard-server/default.nix @@ -0,0 +1,41 @@ +{ config, pkgs, lib, ... }: +{ + environment.systemPackages = [ pkgs.wireguard-tools pkgs.mosh ]; + networking.nat = { + enable = true; + externalInterface = "ens3"; + internalInterfaces = [ "wg0" ]; + }; + networking.firewall = { + allowedUDPPorts = [ 60990 ]; + }; + + networking.wireguard.interfaces.wg0 = { + ips = [ "10.0.69.1/24" ]; + listenPort = 60990; + privateKeyFile = "/var/lib/wireguard/private"; + generatePrivateKeyFile = true; # TODO agenix secret + peers = [ + { + # box + publicKey = "Ra78mOc110K7URN5uB3m9d78iBKgeRHzT+3HkiFp9BU="; + allowedIPs = [ "10.0.69.4/32" ]; + } + { + # line + publicKey = "fsb1FuGmYi89p4CVXytKw2FYamONKtoanxrgs/dJjC8="; + allowedIPs = [ "10.0.69.3/32" ]; + } + { + # curve + publicKey = "XmV4AcPPND/eeSI6d9M1iahCjtymqY6DdUDEFNP/x3g="; + allowedIPs = [ "10.0.69.2/32" ]; + } + { + # helix + publicKey = "gcdq86hhEUlqF2chqYB/F8pALyAMNFvwLycxBoHuoDs="; + allowedIPs = [ "10.0.69.5/32" ]; + } + ]; + }; +} diff --git a/profiles/wireguard/default.nix b/profiles/wireguard/default.nix new file mode 100644 index 00000000..ff2fbabb --- /dev/null +++ b/profiles/wireguard/default.nix @@ -0,0 +1,30 @@ +{ config, pkgs, lib, ... }: + +{ + # services.tailscale.enable = true; + networking.firewall.allowedUDPPorts = [ 60990 ]; + age.secrets.curve-wg.file = "/etc/nixos/secrets/curve-wg.age"; + age.secrets.curve-wg.owner = "anish"; + + networking.wireguard.interfaces = { + # TODO need some kind of module here to configure curve & box from hosts or something + wg0 = { + ips = [ "10.0.69.2/24" ]; + listenPort = 60990; # to match firewall allowedUDPPorts (without this wg uses random port numbers) + + privateKeyFile = "/run/agenix/curve-wg"; + peers = [ + # For a client configuration, one peer entry for the server will suffice. + { + publicKey = "c1J4p63rD3IlszugMZiki7UBV3YmDdqa3DU4UejXzAI="; + allowedIPs = [ "10.0.69.0/24" ]; + # Set this to the server IP and port. + endpoint = "69.61.38.225:60990"; # ToDo: route to endpoint not automatically configured https://wiki.archlinux.org/index.php/WireGuard#Loop_routing https://discourse.nixos.org/t/solved-minimal-firewall-setup-for-wireguard-client/7577 + + # Send keepalives every 25 seconds. Important to keep NAT tables alive. + persistentKeepalive = 25; + } + ]; + }; + }; +} diff --git a/screenshots/desktop.png b/screenshots/desktop.png new file mode 100644 index 00000000..9463f3cd Binary files /dev/null and b/screenshots/desktop.png differ diff --git a/screenshots/fakebusy.png b/screenshots/fakebusy.png new file mode 100644 index 00000000..9996b8c0 Binary files /dev/null and b/screenshots/fakebusy.png differ diff --git a/screenshots/firefox.png b/screenshots/firefox.png new file mode 100644 index 00000000..282baff9 Binary files /dev/null and b/screenshots/firefox.png differ diff --git a/screenshots/rofi.png b/screenshots/rofi.png new file mode 100644 index 00000000..fa455482 Binary files /dev/null and b/screenshots/rofi.png differ diff --git a/secrets/.gitattributes b/secrets/.gitattributes new file mode 100644 index 00000000..901863e3 --- /dev/null +++ b/secrets/.gitattributes @@ -0,0 +1,4 @@ +* filter=git-crypt diff=git-crypt +.gitattributes !filter !diff +secrets.nix !filter !diff +README.md !filter !diff diff --git a/secrets/borg-password.age b/secrets/borg-password.age new file mode 100644 index 00000000..ae9b8787 Binary files /dev/null and b/secrets/borg-password.age differ diff --git a/secrets/box-wg.age b/secrets/box-wg.age new file mode 100644 index 00000000..51508c37 --- /dev/null +++ b/secrets/box-wg.age @@ -0,0 +1,8 @@ +age-encryption.org/v1 +-> ssh-ed25519 K2vF/Q Vbe7tvR9OtiY6YCfCAwkV9L/wlKd4h+stYnZu3aCSC4 +U5V2qDLFNrY4SQn9aZZyNtsfXpae8eqo6JH66gbKwdg +-> %!/-grease ErIq e d{ZU +vKMMQJKGGb1YCU3Jn6xq5JTLoGYgC+X58WVxjpHYF126aDBN0NOYxYqDJFRQGe5S +7wuRgDPn +--- QE25f0fQlnz4v6ei4OczAW9BpqOvnkwdc7re508d4A4 +z@fE/_`)YVhc~w'F1iEޖU(3xtPZ; 3g[a6a0aU0 \ No newline at end of file diff --git a/secrets/curve-wg.age b/secrets/curve-wg.age new file mode 100644 index 00000000..a1cdf212 --- /dev/null +++ b/secrets/curve-wg.age @@ -0,0 +1,13 @@ +age-encryption.org/v1 +-> ssh-ed25519 E8y8hg hedyIPcLQGc3KmKFzhVWU/zHcattXe4oRGo8wY/TV3s +wXjPQaUnxci/pQKoNXMm7/yhXZ8Ec69w/3bJOxkiXws +-> ssh-ed25519 AiezdQ lb8Hwsl8FDk/CExAVqMS0w20MJq5GKUm0NkE5O7k/is +aspWW5q6YpXKIvkIzFIPdPFp7/oRgrE/cpqtis5BASY +-> ssh-ed25519 K2vF/Q qw5EytbSJskHAcuKFbqZyvut5iJomIRMwgxFohvJBQo +GkHaGU3BnBX2BCZ2eF8X1whFmQTKueXvOqC08UggQWU +-> z-grease +h8wf5RrYDiHoC5CuvGmL6xeol9K2o24A7WAky8qrmKWgjzlhR7IcitQ4AX9teOec +9wsfVkTBgbc +--- +l7lATgPTYXuOOCaTYEOVMGxW0Ryaj5RAYaAVT/zIQE +fؑExP?sdPBg* |dnb9P + HŚ}-)$5W \ No newline at end of file diff --git a/secrets/fastmail.age b/secrets/fastmail.age new file mode 100644 index 00000000..3a3aeb4a Binary files /dev/null and b/secrets/fastmail.age differ diff --git a/secrets/mossnet.age b/secrets/mossnet.age new file mode 100644 index 00000000..2a75cae7 --- /dev/null +++ b/secrets/mossnet.age @@ -0,0 +1,12 @@ +age-encryption.org/v1 +-> ssh-ed25519 E8y8hg g7zZHmh04X43ZguiRhdjeZ2BtBsT3o8qhSntPxDzd0k +6Cwi06GFH36g44rbkIK1rLxkXFJ5yWLpMsvl3xzFSY8 +-> ssh-ed25519 AiezdQ tpn28KlGD2vaeS+3tsaxjhXfcMMNMgsZbQE9YySup3w +TbfWuW62lYWkp0xnrrzbdMzNJ+jNn+5tMCZEz4GdTVs +-> ssh-ed25519 K2vF/Q 7SQse/JhNP09k7xtyjw1Y2mnhFH5bmaXjqWrpxO5Bxg +aKV2EN0a8t6NS+88eAG9+bu6+sFd9/Rc4nNoR0os9X0 +-> xjS>-grease *{_ +fOiZzBai7fC+jxV7RH8bKLx05h+UVmCR51CGMaAAsIyHivI+hb2M3lDfWdn0shZQ +byznwCva3kNQwG3m4MYgk6J4/QiasZGF0O+QoA +--- gEmFFhuHpKOP74G/65xuCK0EA3ERvF78q8eVTMlmkOY +ʝdD3-\XBS||9TSz@/ZUdR" \ No newline at end of file diff --git a/secrets/secrets.nix b/secrets/secrets.nix new file mode 100644 index 00000000..1685d2d0 --- /dev/null +++ b/secrets/secrets.nix @@ -0,0 +1,17 @@ +let + # set ssh public keys here for your system and user + user = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIItTdCyYVur6LzRQf08JZUcEAr23H7fTRRmDJOzoOc6A anish@curve"; + system = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIMPcqWQ/L5nLTsBFHArl3AJb9xynhfsKenb5h0NNuMV root@curve"; + mossnet = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAA0bsVbdQR6iWNLKIiID57A1+dVXC58Dtf5cSXg6/JF root@box"; + curve = [ system user ]; + allKeys = [ system user mossnet ]; + systemOnly = [ system mossnet ]; +in +{ + "fastmail.age".publicKeys = allKeys; + "mossnet.age".publicKeys = allKeys; + "curve-wg.age".publicKeys = curve; + "box-wg.age".publicKeys = [ mossnet ]; + # "wallabag.age".publicKeys = [ mossnet ]; + "borg-password.age".publicKeys = systemOnly; +} diff --git a/shell.nix b/shell.nix new file mode 100644 index 00000000..575a5d82 --- /dev/null +++ b/shell.nix @@ -0,0 +1 @@ +(import ./lib/compat).shellNix diff --git a/shell/default.nix b/shell/default.nix new file mode 100644 index 00000000..24f1a332 --- /dev/null +++ b/shell/default.nix @@ -0,0 +1,7 @@ +{ self, inputs, ... }: +{ + modules = [ + ./devos.nix + ]; +} + diff --git a/shell/devos.nix b/shell/devos.nix new file mode 100644 index 00000000..0b52f88b --- /dev/null +++ b/shell/devos.nix @@ -0,0 +1,58 @@ +{ pkgs, extraModulesPath, inputs, ... }: +let + + hooks = import ./hooks; + + pkgWithCategory = category: package: { inherit package category; }; + linter = pkgWithCategory "linter"; + docs = pkgWithCategory "docs"; + devos = pkgWithCategory "devos"; + +in +{ + _file = toString ./.; + + imports = [ "${extraModulesPath}/git/hooks.nix" ]; + git = { inherit hooks; }; + + # tempfix: remove when merged https://github.com/numtide/devshell/pull/123 + devshell.startup.load_profiles = pkgs.lib.mkForce (pkgs.lib.noDepEntry '' + # PATH is devshell's exorbitant privilige: + # fence against its pollution + _PATH=''${PATH} + # Load installed profiles + for file in "$DEVSHELL_DIR/etc/profile.d/"*.sh; do + # If that folder doesn't exist, bash loves to return the whole glob + [[ -f "$file" ]] && source "$file" + done + # Exert exorbitant privilige and leave no trace + export PATH=''${_PATH} + unset _PATH + ''); + + packages = with pkgs; [ + git-crypt + ]; + + commands = with pkgs; [ + (devos nixUnstable) + (devos agenix) + { + category = "devos"; + name = pkgs.nvfetcher-bin.pname; + help = pkgs.nvfetcher-bin.meta.description; + command = "cd $DEVSHELL_ROOT/pkgs; ${pkgs.nvfetcher-bin}/bin/nvfetcher -c ./sources.toml --no-output $@"; + } + (linter nixpkgs-fmt) + (linter editorconfig-checker) + # (docs python3Packages.grip) too many deps + (docs mdbook) + (devos inputs.deploy.packages.${pkgs.system}.deploy-rs) + ] + + ++ lib.optional + (system != "i686-linux") + (devos cachix) + + ; +} diff --git a/shell/hooks/default.nix b/shell/hooks/default.nix new file mode 100644 index 00000000..10f2c9d2 --- /dev/null +++ b/shell/hooks/default.nix @@ -0,0 +1,4 @@ +{ + enable = true; + pre-commit.text = builtins.readFile ./pre-commit.sh; +} diff --git a/shell/hooks/pre-commit.sh b/shell/hooks/pre-commit.sh new file mode 100755 index 00000000..985d3b40 --- /dev/null +++ b/shell/hooks/pre-commit.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=$(${git}/bin/git hash-object -t tree /dev/null) +fi + +diff="git diff-index --name-only --cached $against --diff-filter d" + +nix_files=($($diff -- '*.nix')) +all_files=($($diff)) + +# Format staged nix files. +if [[ -n "${nix_files[@]}" ]]; then + nixpkgs-fmt "${nix_files[@]}" \ + && git add "${nix_files[@]}" +fi + +# check editorconfig +editorconfig-checker -- "${all_files[@]}" +if [[ $? != '0' ]]; then + printf "%b\n" \ + "\nCode is not aligned with .editorconfig" \ + "Review the output and commit your fixes" >&2 + exit 1 +fi diff --git a/users/anish/default.nix b/users/anish/default.nix new file mode 100644 index 00000000..234df394 --- /dev/null +++ b/users/anish/default.nix @@ -0,0 +1,29 @@ +{ hmUsers, pkgs, ... }: + +{ + #home-manager.users = { inherit (hmUsers) anish; }; + + users.users.anish = { + description = "Personal user for Anish"; + hashedPassword = "MVHHpy9gbe3ow"; + shell = pkgs.zsh; + isNormalUser = true; + extraGroups = [ "wheel" "audio" ]; + openssh.authorizedKeys.keys = [ + # Curve + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDM0Zvei46x/yZl/IeBCq6+IYQQ0avulzVyBysF9cPigZMCybWRV7IEU+E3k9t6JrbdbdGfJkcZIWmsWDdKS8W8mBnZpVoT0ffLynu8JQ/TKdGm4Qv6bgUeKNrGsNv0ZPs2CDaGSLj0oJfRF7Ko10tcLP0vW+yujrh+y6TH/vVzJioaV4TGvtCUpn+wEQah9ROwPQLUUofsSWdnRsDJ/gp37zXWs4l5wyjSKtP3O9RZUP7kBekbSqEgSXiTk0oUQSVqIWl9NDiP6onk/gSOjXsR/JPqsSN/XI/c/yj6gyY0f51Ru2D7iBxuMJIJcWV+rU6coIj+ULcQWLzt/7TI8jq5AOOzI/ll4zbL24Eo84Rz+TP9tvMMhDZ0VaMN22AJ8qQEjc5P09tWKsX7Jg39XelyV1jHXncE4yvIE9F4RSCHzWCeKeXakizQNuzSaxTxIExRFYHjNW5bR6+3MTGwVrEIXU+qML+0yFTR86MT+tdY5AreAJQLwbog79O1NupeXJE= anish@curve" + # Line + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDtU2GMYjXj6RGO1+mwM4TDGOo0qrKLTL4Di8+QgDX0p5vUEsnE1PS9wnuqCmSu75U8g0XIAMtvtdYyGk1N+Bx01erAZpT8DLYtIXFCyaiN28PVu5T1D0T+TQ7xgIH1qenXZR2DOQdf6kpvKEfm7+7bWhCo0N/KFMpmReubyzHDQcq/1qQasxTL+YALQFOjwKqsOTBXbHwZ103AEAcQX4ftBFEOfVli4/1aKIK4dNSZYB7J9Htq707YnsEqo9RLAMh0aOTTYgTx9AoSUDeqGuh/AGkcB7NcS7EEtI6d5YUGylwZh/gF6hqE0jl8kn2m5jMKXL3CRohZvjifue8x/GIjpu5WRabUuhBEbrfTQQaC7taHnt5rvYCGzKZx09TexUzhuz2CL480DRoxSG+P+lCNm1dIg/EZrnGEzXCSr36PlOqS5t5gm8tPkzCmZf2wU15A3ZIYUPmnYLqsn4WmIV7rKmdqt2ctWELUXow3PPiZXBucP9P3xpsYEfF1SB2SGNc= u0_a139@localhost" + ]; + }; + + # home-manager.users.anish.programs.git = { + # userName = "Anish Lakhwara"; + # userEmail = "anish+git@lakhwara.com"; + # delta.enable = true; + # }; + + #home-manager.users.anish = { suites, ... }: { + # imports = suites.gui; + #}; +} diff --git a/users/modules/.flake-keep b/users/modules/.flake-keep new file mode 100644 index 00000000..e69de29b diff --git a/users/nixos/default.nix b/users/nixos/default.nix new file mode 100644 index 00000000..5c037fe8 --- /dev/null +++ b/users/nixos/default.nix @@ -0,0 +1,12 @@ +{ hmUsers, ... }: +{ + home-manager.users = { inherit (hmUsers) nixos; }; + + users.users.nixos = { + uid = 1000; + password = "nixos"; + description = "default"; + isNormalUser = true; + extraGroups = [ "wheel" ]; + }; +} diff --git a/users/profiles/ayu/kitty.conf b/users/profiles/ayu/kitty.conf new file mode 100644 index 00000000..e38f2172 --- /dev/null +++ b/users/profiles/ayu/kitty.conf @@ -0,0 +1,24 @@ +#: Ayu theme for kitty +#: Stolen from https://codeberg.org/Raimu/kitty-ayu-color-scheme/src/branch/main/ayu-Mirage.conf + +background #1F2430 +foreground #CBCCC6 +cursor #FFCC66 +selection_background #33415E +color0 #000000 +color8 #4D5566 +color1 #FF3333 +color9 #F27983 +color2 #BAE67E +color10 #A6CC70 +color3 #FFA759 +color11 #F29E74 +color4 #73D0FF +color12 #77A8D9 +color5 #D4BFFF +color13 #A37ACC +color6 #95E6CB +color14 #4CBF99 +color7 #ffffff +color15 #F0F0F0 +selection_foreground #CBCCC6 diff --git a/users/profiles/cal/default.nix b/users/profiles/cal/default.nix new file mode 100644 index 00000000..27811d2a --- /dev/null +++ b/users/profiles/cal/default.nix @@ -0,0 +1,98 @@ +{ pkgs, config, age, ... }: + +{ + home.packages = with pkgs; [ + khal + khard + vdirsyncer + ]; + + xdg.configFile = { + "vdirsyncer/config".text = '' + [general] + status_path = "/home/anish/.config/vdirsyncer/status/" + + [pair contacts] + a = "contacts_local" + b = "contacts_remote" + collections = ["from b"] + metadata = ["displayname"] + + [storage contacts_local] + type = "filesystem" + path = "~/.contacts/" + fileext = ".vcf" + + [storage contacts_remote] + type = "carddav" + url = "http://mossnet.lan:5252/anish" + username = "anish" + password.fetch = ["command", "echo", "acceptsanypassword"] + + [pair calendar] + a = "calendar_local" + b = "calendar_remote" + collections = ["from b"] + metadata = ["displayname"] + + [storage calendar_local] + type = "filesystem" + path = "~/.calendar/" + fileext = ".ics" + + [storage calendar_remote] + type = "caldav" + url = "http://mossnet.lan:5252/anish" + username = "anish" + password.fetch = ["command", "echo", "allpasswordsaccepted"] + ''; + + "khal/config".text = '' + [calendars] + + [[calendar_local]] + path = ~/.calendar/* + type = discover + + [[contacts_local]] + path = ~/.contacts/* + type = birthdays + + [locale] + timeformat = %H:%M + dateformat = %Y-%m-%d + longdateformat = %Y-%m-%d + datetimeformat = %Y-%m-%d %H:%M + longdatetimeformat = %Y-%m-%d %H:%M + ''; + + "khard/khard.conf".text = '' + [addressbooks] + [[personal]] + path = ~/.contacts/* + + [general] + debug = no + default_action = list + editor = nvim, -i, NONE + merge_editor = nvim, -d + + [contact table] + display = first_name + group_by_addressbook = no + reverse = no + show_nicknames = yes + show_uids = no + sort = last_name + localize_dates = yes + preferred_phone_number_type = pref, cell, home + preferred_email_address_type = pref, home, work + + [vcard] + private_objects = Jabber, + preferred_version = 3.0 + search_in_source_files = no + skip_unparsable = no + ''; + }; +} diff --git a/users/profiles/cli/default.nix b/users/profiles/cli/default.nix new file mode 100644 index 00000000..9ff92a16 --- /dev/null +++ b/users/profiles/cli/default.nix @@ -0,0 +1,256 @@ +{ self, lib, pkgs, config, ... }: +{ + home.packages = with pkgs; [ + binutils + coreutils + dnsutils + dosfstools + #git + bottom + gptfdisk + starship + iputils + jq + manix + moreutils + nix-index + cached-nix-shell + nmap + ripgrep + skim + tealdeer + usbutils + utillinux + whois + iftop + wget + curl + exa + bat + fd + ncdu + duf + trash-cli + nix-index + silver-searcher + tcpdump + mtr + file + lsof + atool + strace + zip + unzip + rsync + tmux + pwgen + glow + pass + less + gdb + xxd + taskwarrior + yt-dlp + gnupg + syncthing + dijo + #ssb-patchwork + fontconfig + pandoc + ]; + + programs.zsh = { + enable = true; + enableCompletion = true; + enableAutosuggestions = true; + + initExtra = '' + bindkey -v + flakify() { + if [ ! -e flake.nix ]; then + nix flake new -t github:nix-community/nix-direnv . + elif [ ! -e .envrc ]; then + echo "use flake" > .envrc + direnv allow + fi + vim flake.nix + } + autopair-init + ''; + sessionVariables = { + EDITOR = "nvim"; + TERMINFO_DIRS = "${pkgs.kitty.terminfo.outPath}/share/terminfo"; # Needed to run home-manager switch on non-nixOS + }; + plugins = [ + # { + # name = "zsh-autocomplete"; + # src = pkgs.fetchFromGitHub { + # owner = "marlonrichert"; + # repo = "zsh-autocomplete"; + # rev = "22.01.21"; + # sha256 = "+UziTYsjgpiumSulrLojuqHtDrgvuG91+XNiaMD7wIs="; + # }; + # } + { + name = "zsh-autopair"; + src = pkgs.fetchFromGitHub { + owner = "hlissner"; + repo = "zsh-autopair"; + rev = "34a8bca0c18fcf3ab1561caef9790abffc1d3d49"; + sha256 = "1h0vm2dgrmb8i2pvsgis3lshc5b0ad846836m62y8h3rdb3zmpy1"; + }; + file = "autopair.zsh"; + } + { + name = "zsh-syntax-highlighting"; + src = pkgs.fetchFromGitHub { + owner = "zsh-users"; + repo = "zsh-syntax-highlighting"; + rev = "0.6.0"; + sha256 = "0zmq66dzasmr5pwribyh4kbkk23jxbpdw4rjxx0i7dx8jjp2lzl4"; + }; + file = "zsh-syntax-highlighting.zsh"; + } + { + name = "zsh-autoquoter"; + src = pkgs.fetchFromGitHub { + owner = "ianthehenry"; + repo = "zsh-autoquoter"; + rev = "819a615fbfd2ad25c5d311080e3a325696b45de7"; + sha256 = "r0jdo+YFTOejvNMTqzXi5ftcLzDpuKejX0wMFwqKdJY="; + }; + file = "zsh-autoquoter.zsh"; + } + { + name = "zsh-nix-shell"; + file = "nix-shell.plugin.zsh"; + src = pkgs.fetchFromGitHub { + owner = "chisui"; + repo = "zsh-nix-shell"; + rev = "v0.5.0"; + sha256 = "0za4aiwwrlawnia4f29msk822rj9bgcygw6a8a6iikiwzjjz0g91"; + }; + } + ]; + }; + + programs.starship = { + enable = true; + enableZshIntegration = true; + }; + + programs.fzf = { + enable = true; + enableZshIntegration = true; + }; + + programs.direnv = { + enable = true; + enableZshIntegration = true; + nix-direnv.enable = true; + # nix-direnv.enableFlakes = true; always enabled + }; + + programs.zoxide = { + enable = true; + enableZshIntegration = true; + }; + + services.kdeconnect.enable = true; + + home.shellAliases = { + # quick cd + ".." = "cd .."; + "..." = "cd ../.."; + "...." = "cd ../../.."; + "....." = "cd ../../../.."; + + # kitaab recents + kr = "cd /home/anish/kitaab/vimwiki; ls --sort=modified --reverse | fzf --preview 'bat --style=numbers --color=always --terminal-width -1 {}'"; + + # modern cli tools + ls = "exa --icons"; + l = "exa -l --icons"; + la = "exa -la --icons"; + tree = "ls --tree --icons"; + cat = "bat"; + unzip = "aunpack"; + copy = "xclip -selection clipboard"; + paste = "xclip -selection clipboard -o"; + rm = "echo USE TRASH, FOOL: trash "; + trash = "trash-put"; + + # task warrior + # TODO: make blocked a context? + t = "task -BLOCKED"; + tun = "task -BLOCKED -wait"; + tr = "task newest limit:page"; + tu = "task unblocked -wait"; + tl = "task list"; + ta = "task add"; + tn = "task-note"; + tm = "task limit:page"; + te = "task edit"; + ts = "task sync"; + + scrot = "flameshot screen -c -p ~/screenshots/"; + scrotgui = "flameshot gui -p ~/screenshots/"; + + # git + g = "git"; + + # grep + grep = "rg"; + gi = "grep -i"; + + # internet ip + myip = "dig +short myip.opendns.com @208.67.222.222 2>&1"; + + # nix + n = "nix"; + np = "n profile"; + ni = "np install"; + nr = "np remove"; + ns = "n search --no-update-lock-file"; + nf = "n flake"; + nfl = "nf lock"; + nepl = "n repl ''"; + srch = "ns nixos"; + orch = "ns override"; + nrb = "cd /tmp; sudo nixos-rebuild switch --flake '/etc/nixos/#curve'; cd $OLDPWD"; + nrt = "cd /tmp; sudo nixos-rebuild test --flake '/etc/nixos/#curve'; cd $OLDPWD"; + ned = "cd /etc/nixos; vim; cd $OLDPWD"; + ncd = "cd /etc/nixos"; + mn = '' + manix "" | grep '^# ' | sed 's/^# \(.*\) (.*/\1/;s/ (.*//;s/^# //' | sk --preview="manix '{}'" | xargs manix + ''; + # fix nixos-option + nixos-option = "nixos-option -I nixpkgs=${self}/lib/compat"; + + # sudo + s = "sudo -E "; + pls = "s"; + si = "sudo -i"; + se = "sudoedit"; + + # top + top = "btm"; + + # systemd + ctl = "systemctl"; + stl = "s systemctl"; + utl = "systemctl --user"; + ut = "systemctl --user start"; + un = "systemctl --user stop"; + up = "s systemctl start"; + dn = "s systemctl stop"; + jtl = "journalctl"; + + # quick ssh + kssh = "kitten +kitty ssh"; + smm = "ssh 10.0.69.4"; # box over wireguard + sm = "ssh mossnet.lan"; # box regular + ss = "ssh sealight.xyz"; # helix + # sl = "ssh 69.61.38.225"; # lituus has become helix + }; +} diff --git a/users/profiles/cli/starship.toml b/users/profiles/cli/starship.toml new file mode 100644 index 00000000..f08a026f --- /dev/null +++ b/users/profiles/cli/starship.toml @@ -0,0 +1,92 @@ +[aws] +symbol = " " + +[character] +success_symbol = "[❯](bold purple)" +vicmd_symbol = "[❮](bold purple)" + +[battery] +full_symbol = " " +charging_symbol = " " +discharging_symbol = " " + +[conda] +symbol = " " + +[directory] +style = "cyan" +read_only = " 🔒" + +[docker_context] +symbol = " " + +[elixir] +symbol = " " + +[elm] +symbol = " " + +[git_branch] +format = "[$symbol$branch]($style) " +symbol = " " +style = "bold dimmed white" + +[git_status] +format = '([「$all_status$ahead_behind」]($style) )' +conflicted = "⚠️" +ahead = "⟫${count} " +behind = "⟪${count}" +diverged = "🔀 " +untracked = "📁 " +stashed = "↪ " +modified = "𝚫 " +staged = "✔ " +renamed = "⇆ " +deleted = "✘ " +style = "bold bright-white" + +[golang] +symbol = " " + +[hg_branch] +symbol = " " + +[java] +symbol = " " + +[julia] +symbol = " " + +[memory_usage] +symbol = " " +disabled = false + +[nim] +symbol = " " + +[nix_shell] +format = '[$symbol$state]($style) ' +symbol = " " +pure_msg = "λ" +impure_msg = "⎔" + +[nodejs] +symbol = " " + +[package] +symbol = " " + +[php] +symbol = " " + +[python] +symbol = " " + +[ruby] +symbol = " " + +[rust] +symbol = " " + +[status] +disabled = false diff --git a/users/profiles/desktop/Xresources b/users/profiles/desktop/Xresources new file mode 100644 index 00000000..ed68792a --- /dev/null +++ b/users/profiles/desktop/Xresources @@ -0,0 +1,80 @@ +!! Colors +#define blk #1F2430 +#define bblk #F28779 +#define red #A6CC70 +#define bred #FFCC66 +#define grn #5CCFE6 +#define bgrn #F29E74 +#define ylw #77A8D9 +#define bylw #5C6773 +#define blu #707A8C +#define bblu #F27983 +#define mag #BAE67E +#define bmag #FFD580 +#define cyn #73D0FF +#define bcyn #FFA759 +#define wht #95E6CB +#define bwht #CBCCC6 +#define bg blk +#define fg wht + +*.foreground: fg +*.background: bg +*.cursorColor: mag + +*.color0: blk +*.color8: bblk +*.color1: red +*.color9: bred +*.color2: grn +*.color10: bgrn +*.color3: ylw +*.color11: bylw +*.color4: blu +*.color12: bblu +*.color5: mag +*.color13: bmag +*.color6: cyn +*.color14: bcyn +*.color7: wht +*.color15: bwht + +! greys +*.color234: #1E2029 +*.color235: #282a36 +*.color236: #373844 +*.color237: #44475a +*.color239: #565761 +*.color240: #6272a4 +*.color241: #b6b6b2 + + +!! general +st.scratch.font: JetBrainsMono:pixelsize=16 + + +!! xst +st.font: JetBrainsMono:pixelsize=12 +st.borderpx: 10 + + +!! urxvt +URxvt*depth: 32 +URxvt*.background: blk +URxvt*.borderless: 1 +URxvt*.buffered: true +URxvt*.cursorBlink: true +URxvt*.font: xft:Fira Code:pixelsize=12 +URxvt*.internalBorder: 10 +URxvt*.letterSpace: 0 +URxvt*.lineSpace: 0 +URxvt*.loginShell: false +URxvt*.matcher.button: 1 +URxvt*.matcher.rend.0: Uline Bold fg5 +URxvt*.saveLines: 5000 +URxvt*.scrollBar: false +URxvt*.underlineColor: grey +URxvt.clipboard.autocopy: true +URxvt.iso14755: false +URxvt.iso14755_52: false +URxvt.perl-ext-common: default,matcher diff --git a/users/profiles/desktop/ayu-Xresources b/users/profiles/desktop/ayu-Xresources new file mode 100644 index 00000000..34e38a60 --- /dev/null +++ b/users/profiles/desktop/ayu-Xresources @@ -0,0 +1,44 @@ +! +! Generated with : +! XRDB2Xreources.py +! +*.foreground: #1F2430 +*.background: #0f1419 +*.cursorColor: #f29718 +! +! Black +*.color0: #000000 +*.color8: #323232 +! +! Red +*.color1: #ff3333 +*.color9: #ff6565 +! +! Green +*.color2: #b8cc52 +*.color10: #eafe84 +! +! Yellow +*.color3: #e7c547 +*.color11: #fff779 +! +! Blue +*.color4: #36a3d9 +*.color12: #68d5ff +! +! Magenta +*.color5: #f07178 +*.color13: #ffa3aa +! +! Cyan +*.color6: #95e6cb +*.color14: #c7fffd +! +! White +*.color7: #ffffff +*.color15: #ffffff +! +! Bold, Italic, Underline +*.colorBD: #e6e1cf +!*.colorIT: +!*.colorUL: diff --git a/users/profiles/desktop/ayu-dark-kitty.conf b/users/profiles/desktop/ayu-dark-kitty.conf new file mode 100644 index 00000000..451d8b8b --- /dev/null +++ b/users/profiles/desktop/ayu-dark-kitty.conf @@ -0,0 +1,23 @@ + +background #0A0E14 +foreground #B3B1AD +cursor #E6B450 +selection_background #273747 +color0 #000000 +color8 #4D5566 +color1 #FF3333 +color9 #D96C75 +color2 #C2D94C +color10 #91B362 +color3 #FF8F40 +color11 #F29668 +color4 #59C2FF +color12 #6994BF +color5 #D4BFFF +color13 #A37ACC +color6 #95E6CB +color14 #4CBF99 +color7 #ffffff +color15 #F0F0F0 +selection_foreground #B3B1AD + diff --git a/users/profiles/desktop/ayu-kitty.conf b/users/profiles/desktop/ayu-kitty.conf new file mode 100644 index 00000000..3ad94cdc --- /dev/null +++ b/users/profiles/desktop/ayu-kitty.conf @@ -0,0 +1,25 @@ +#: This is a port of ayu Mirage color scheme +#: based on : +#: https://github.com/ayu-theme/ayu-colors + +background #1F2430 +foreground #CBCCC6 +cursor #FFCC66 +selection_background #33415E +color0 #000000 +color8 #4D5566 +color1 #FF3333 +color9 #F27983 +color2 #BAE67E +color10 #A6CC70 +color3 #FFA759 +color11 #F29E74 +color4 #73D0FF +color12 #77A8D9 +color5 #D4BFFF +color13 #A37ACC +color6 #95E6CB +color14 #4CBF99 +color7 #ffffff +color15 #F0F0F0 +selection_foreground #CBCCC6 diff --git a/users/profiles/desktop/background.jpg b/users/profiles/desktop/background.jpg new file mode 100644 index 00000000..c0338112 Binary files /dev/null and b/users/profiles/desktop/background.jpg differ diff --git a/users/profiles/desktop/bin/hotplug-monitor.sh b/users/profiles/desktop/bin/hotplug-monitor.sh new file mode 100755 index 00000000..0fc021a3 --- /dev/null +++ b/users/profiles/desktop/bin/hotplug-monitor.sh @@ -0,0 +1,11 @@ +#! /usr/bin/env bash + +connect() { + xrandr --output HDMI-2 --same-as eDP-1 +} + +disconnect() { + xrandr --output HDMI-2 --off +} + +xrandr | grep "HDMI-2 connected" &>>/dev/null && connect || disconnect diff --git a/users/profiles/desktop/bin/mpv-ify b/users/profiles/desktop/bin/mpv-ify new file mode 100755 index 00000000..d3f343b2 --- /dev/null +++ b/users/profiles/desktop/bin/mpv-ify @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +URL="$(xclip -selection clipboard -o)" +mpv $URL diff --git a/users/profiles/desktop/bin/passmenu b/users/profiles/desktop/bin/passmenu new file mode 100755 index 00000000..bdca124e --- /dev/null +++ b/users/profiles/desktop/bin/passmenu @@ -0,0 +1,68 @@ +#!/usr/bin/env bash + +# Prompts for a pass entry, then for a specific field. Similar to passmenu, but +# uses rofi, and can resume from a previous session. +# +# Example: passmenu [RESUME] + +ROFI_CMD='rofi -dmenu -theme theme/passmenu.rasi' +MSG_CMD='notify-send' +set -e +shopt -s nullglob globstar + +for prog in xclip pass; do + if ! command -v "$prog" >/dev/null; then + >&2 echo "$prog not installed, aborting" + exit 1 + fi +done + +if [[ $1 == -r ]]; then + resume=1; shift +fi + +url= +# Get qutebrowser's current url +win=$(xdotool getactivewindow) +if [[ -n $win ]]; then + winname=$(xdotool getwindowname $win) + if [[ $winname =~ " - Mozilla Firefox$" ]]; then + url=${winname% - Mozilla*} + url=${url##* - } + while (( ${#url//[^.]/} > 1 )); do + url=${url#*.} + done + fi +fi + +LAST_ENTRY_FILE=/tmp/_upm +if [[ -n $resume && -f $LAST_ENTRY_FILE ]]; then + entry="$(<$LAST_ENTRY_FILE)" +else + prefix=${PASSWORD_STORE_DIR-~/.password-store} + password_files=( "$prefix"/**/*.gpg ) + password_files=( "${password_files[@]#"$prefix"/}" ) + password_files=( "${password_files[@]%.gpg}" ) + entry=$(printf "%s\n" "${password_files[@]}" | $ROFI_CMD -p "..." -filter "$url") +fi + +if [[ -z $entry ]]; then + $MSG_CMD "Error!" "Failed to select $entry" + exit 1 +fi + +echo "$entry" >/tmp/_upm +secrets="$(pass show "$entry")" +if [[ -n $secrets ]]; then + fields=$(awk -F': ' 'NR>1 && !/^otpauth:/ {print $1}' <<<"$secrets") + field=$(printf "password\n%s\notp\n" "${fields[@]}" | $ROFI_CMD -p "$entry") + case $field in + password) pass -c "$entry" ;; + otp) printf "%s" "$(pass otp -c "$entry")" ;; + *) printf "%s" "$(awk -v "key=$field:" '$1 == key {print $2}' <<<"$secrets")" | xclip -selection clipboard -in ;; + esac + $MSG_CMD "Success!" "Copied $entry/$field to clipboard for 45s" +else + $MSG_CMD "Error!" "Failed to retrieve $entry" + exit 2 +fi diff --git a/users/profiles/desktop/bin/powermenu b/users/profiles/desktop/bin/powermenu new file mode 100755 index 00000000..5846b2a2 --- /dev/null +++ b/users/profiles/desktop/bin/powermenu @@ -0,0 +1,31 @@ +#!/usr/bin/env sh + +rofi_command="rofi -theme theme/powermenu.rasi" + +### Options ### +power_off="\tShutdown" +reboot="\tReboot" +lock="\tLock" +suspend="鈴\tSleep" +log_out="\tLogout" +# Variable passed to rofi +options="$power_off\n$reboot\n$lock\n$suspend\n$log_out" + +case "$(echo -e "$options" | $rofi_command -dmenu)" in + " Shutdown") + systemctl poweroff + ;; + " Reboot") + systemctl reboot + ;; + " Lock") + dm-tool lock + ;; + "鈴 Sleep") + dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Pause + systemctl suspend + ;; + " Logout") + bspc quit + ;; +esac diff --git a/users/profiles/desktop/bin/screenshot b/users/profiles/desktop/bin/screenshot new file mode 100755 index 00000000..157d8e8d --- /dev/null +++ b/users/profiles/desktop/bin/screenshot @@ -0,0 +1,53 @@ +#!/usr/bin/env bash + +timer=5 + +# Options +select="麗" +window="类" +screen="" +delay="" +cancel="" + +# Variable passed to rofi +options="$select\n$window\n$screen\n$delay\n$cancel" + +rofi_command="rofi -theme theme/screenshotmenu.rasi" + +setFilename() { + directory="/tmp/" + filename="IMG_$(date +%Y%m%d_%H%M%S).jpg" + filepath=$directory$filename +} + +notify() { + dunstify "Screenshot saved and copied to clipboard" -i accessories-screenshot +} + +chosen="$(echo -e "$options" | $rofi_command -dmenu)" +case $chosen in + $select) + setFilename + maim -Buosd 0.25 \ + | tee $filepath | xclip -selection c -t image/png + notify + ;; + $window) + setFilename + maim -Buod 0.25 -i $(xdotool getactivewindow) \ + | tee $filepath | xclip -selection c -t image/png + notify + ;; + $screen) + setFilename + maim -Buod 0.25 \ + | tee $filepath | xclip -selection c -t image/png + notify + ;; + $delay) + setFilename + maim -Buod $timer \ + | tee $filepath | xclip -selection c -t image/png + notify + ;; +esac diff --git a/users/profiles/desktop/bspwmrc b/users/profiles/desktop/bspwmrc new file mode 100755 index 00000000..a68f97c6 --- /dev/null +++ b/users/profiles/desktop/bspwmrc @@ -0,0 +1,48 @@ +#!/usr/bin/env bash + +# case $HOSTNAME in +# kuro) export LAN=eno1 ;; +# shiro) export LAN=wlp3s0 ;; +# esac + +export MONITOR=$(xrandr -q | grep primary | cut -d' ' -f1) +export MONITORS=( $(xrandr -q | grep ' connected' | cut -d' ' -f1) ) +MONITOR=${MONITOR:-${MONITORS[0]}} + +# Only have workspaces for primary monitor +bspc monitor $MONITOR -d {1,2,3,4,5} + +bspc config remove_disabled_monitors true +bspc config remove_unplugged_monitors true + +bspc config borderless_monocle true +bspc config gapless_monocle true + +bspc config border_width 1 +bspc config window_gap 4 + +bspc config normal_border_color "#181a23" +bspc config active_border_color "#181a23" +bspc config focused_border_color "#bd93f9" +bspc config presel_feedback_color "#bd93f9" + +# Extra padding for polybar +bspc config -m primary top_padding 34 +bspc config -m primary bottom_padding 0 + +# Rules +bspc rule -r '*' + +bspc rule -a Pinentry state=floating center=on +bspc rule -a Emacs split_ratio=0.28 state=tiled +bspc rule -a Firefox split_ratio=0.32 +bspc rule -a feh state=fullscreen +bspc rule -a 'Emacs:org*' state=floating +bspc rule -a 'Emacs:scratch' state=floating +bspc rule -a 'Emacs:emacs-everywhere' state=floating sticky=on +bspc rule -a '*:scratch' state=floating sticky=on center=on border=off rectangle=1000x800+0+0 + +# polybar +for file in $XDG_CONFIG_HOME/bspwm/rc.d/*; do + source "$file" +done diff --git a/users/profiles/desktop/default.nix b/users/profiles/desktop/default.nix new file mode 100644 index 00000000..80d90f7c --- /dev/null +++ b/users/profiles/desktop/default.nix @@ -0,0 +1,151 @@ +{ pkgs, config, lib, ... }: +let + dracula-gtk = pkgs.fetchFromGitHub { + owner = "dracula"; + repo = "gtk"; + rev = "502f212d83bc67e8f0499574546b99ec6c8e16f9"; + sha256 = "1wx9nzq7cqyvpaq4j60bs8g7gh4jk8qg4016yi4c331l4iw1ymsa"; + }; +in +{ + home.pointerCursor = { + x11.enable = true; + package = pkgs.capitaine-cursors; + name = "capitaine-cursors"; + }; + # Install themes + home.packages = with pkgs; [ + ayu-theme-gtk + dracula-theme + capitaine-cursors + paper-icon-theme + papirus-icon-theme + libsForQt5.qtstyleplugin-kvantum + qt5ct + gtk-engine-murrine + gtk_engines + maim + kitty + libreoffice + inotify-tools + ]; + + xresources.properties = { + "*.foreground" = "#95E6CB"; + "*.background" = "#1F2430"; + "*.cursorColor" = "#BAE67E"; + # Black + "*.color0" = "#1F2430"; + "*.color8" = "#F28779"; + # Red + "*.color1" = "#A6CC70"; + "*.color9" = "#FFCC66"; + # Green + "*.color2" = "#5CCFE6"; + "*.color10" = "#F29E74"; + # Yellow + "*.color3" = "#77A8D9"; + "*.color11" = "#5C6773"; + # Blue + "*.color4" = "#707A8C"; + "*.color12" = "#F27983"; + # Magenta + "*.color5" = "#BAE67E"; + "*.color13" = "#FFD580"; + # Cyan + "*.color6" = "#73D0FF"; + "*.color14" = "#FFA759"; + # White + "*.color7" = "#95E6CB"; + "*.color15" = "#CBCCC6"; + # Bold, Italic, Underline + "*.colorBD" = "#e6e1cf"; + }; + + # Move required config files around + xdg.enable = true; # This doesn't seem to do anything so we have below + xdg.configHome = "/home/anish/.config"; # TODO bad hardcode + xdg.configFile = { + "Kvantum/Dracula/Dracula.kvconfig".source = "${dracula-gtk}/kde/kvantum/Dracula-purple-solid/Dracula-purple-solid.kvconfig"; + "Kvantum/Dracula/Dracula.svg".source = "${dracula-gtk}/kde/kvantum/Dracula-purple-solid/Dracula-purple-solid.svg"; + "Kvantum/kvantum.kvconfig".text = "[General]\ntheme=Dracula"; + }; + home.file = { + ".config/bspwm/rc.d/polybar".source = ./run.sh; + ".config/bspwm/bspwmrc".source = ./bspwmrc; + ".config/sxhkdrc".source = ./sxhkdrc; + ".config/rofi/theme" = { + source = ./rofi; + recursive = true; + }; + ".config/polybar" = { + source = ./polybar; + recursive = true; + }; + ".config/dunst/dunstrc".source = ./dunstrc; + ".config/kitty/kitty.conf".source = ./kitty.conf; + ".config/kitty/ayu.conf".source = ./ayu-kitty.conf; + ".config/zathura/zathurarc".source = ./zathurarc; + ".background-image".source = ./background.jpg; + # gtk3 theme + ".config/gtk-3.0/settings.ini".text = '' + [Settings] + gtk-theme-name=Dracula + gtk-icon-theme-name=Paper + gtk-cursor-theme-name=Capitaine Cursors - White + gtk-fallback-icon-theme=gnome + gtk-application-prefer-dark-theme=true + gtk-xft-hinting=1 + gtk-xft-hintstyle=hintfull + gtk-xft-rgba=none + ''; + # GTK2 global theme (widget and icon theme) + ".config/gtk-2.0/gtkrc".text = '' + gtk-theme-name=Ayu-Mirage + gtk-icon-theme-name=Capitaine Cursors - White + gtk-font-name="Sans 10" + ''; + # TODO hardcoded + ".local/bin/passmenu".source = ./bin/passmenu; + ".local/bin/powermenu".source = ./bin/powermenu; + ".local/bin/screenshot".source = ./bin/screenshot; + ".local/bin/mpv-ify".source = ./bin/mpv-ify; + ".config/eww/eww.yuck".source = ./eww/eww.yuck; + ".config/eww/eww.scss".source = ./eww/eww.scss; + ".config/eww/widgets.yuck".source = ./eww/widgets.yuck; + # ".local/bin/hotplug-monitor.sh".source = ./bin/hotplug-monitor.sh; + }; + + qt = { + enable = true; + platformTheme = "gtk"; + style = { name = "qt5ct-style"; }; + }; + + # Compositor + services.picom = { + enable = true; + fade = true; + fadeDelta = 1; + fadeSteps = [ "0.01" "0.022" ]; + shadow = true; + shadowOffsets = [ (-10) (-10) ]; + shadowOpacity = "0.22"; + # activeOpacity = "1.00"; + # inactiveOpacity = "0.92"; + extraOptions = '' + shadow-radius = 12; + # blur-background = true; + # blur-background-frame = true; + # blur-background-fixed = true; + blur-kern = "7x7box"; + blur-strength = 320; + corner-radius = 3 + ''; + }; + + programs.autorandr.enable = true; + services.udiskie.automount = true; + + services.mpris-proxy.enable = true; # bluetooth media control +} diff --git a/users/profiles/desktop/dunstrc b/users/profiles/desktop/dunstrc new file mode 100644 index 00000000..8fcfe622 --- /dev/null +++ b/users/profiles/desktop/dunstrc @@ -0,0 +1,49 @@ +[global] +alignment = left +bounce_freq = 0 +browser = firefox -new-tab +corner_radius = 2 +dmenu = rofi -dmenu -p dunst: +follow = none +font = Fira Sans 11 +format = "%s\n%b" +frame_color = "#1a1c25" +frame_width = 1 +# geometry [{width}]x{height}][+/-{x}+/-{y}] +geometry = "440x15-26+26" +history_length = 20 +horizontal_padding = 16 +icon_position = right +idle_threshold = 120 +ignore_newline = no +indicate_hidden = yes +line_height = 0 +markup = full +max_icon_size = 64 +monitor = 0 +padding = 20 +separator_color = auto +separator_height = 4 +show_age_threshold = 60 +show_indicators = yes +shrink = no +sort = yes +startup_notification = false +sticky_history = yes +transparency = 5 +word_wrap = yes + +[urgency_low] +background = "#1E2029" +foreground = "#bbc2cf" +timeout = 8 + +[urgency_normal] +background = "#2a2d39" +foreground = "#bbc2cf" +timeout = 14 + +[urgency_critical] +background = "#cc6666" +foreground = "#1E2029" +timeout = 0 diff --git a/users/profiles/desktop/eww/eww.scss b/users/profiles/desktop/eww/eww.scss new file mode 100644 index 00000000..6e328f06 --- /dev/null +++ b/users/profiles/desktop/eww/eww.scss @@ -0,0 +1,50 @@ +* { + all: unset; + color: #cdd6f4; +} + +/* Calendar */ + +.cal-box { + background-color: #181825; + border-radius: 8px; + font-family: JetBrainsMono Nerd Font; + font-size: 1.2em; + + .cal-inner-box { + padding: 1rem 1rem .3rem 1rem; + + .cal { + &.highlight { + padding: 10rem; + } + + padding: .8rem .25rem 0rem; + margin-left: 10px; + } + } +} + +calendar:selected { + color: #9ece6a; +} + +calendar.header { + color: #ad8ee6; + font-weight: bold; +} + +calendar.button { + color: #449dab; +} + +calendar.highlight { + color: #7aa2f7; + font-weight: bold; +} + +calendar:indeterminate { + color: #8C8C8C; +} + + diff --git a/users/profiles/desktop/eww/eww.yuck b/users/profiles/desktop/eww/eww.yuck new file mode 100644 index 00000000..047a6f50 --- /dev/null +++ b/users/profiles/desktop/eww/eww.yuck @@ -0,0 +1,13 @@ +; includes: +;widgets +(include "widgets.yuck") + +;; Calendar Windows ;; + +(defwindow calendar + :geometry (geometry :x "-19px" + :y "50px" + :width "270px" + :height "60px" + :anchor "top right") +(cal)) diff --git a/users/profiles/desktop/eww/widgets.yuck b/users/profiles/desktop/eww/widgets.yuck new file mode 100644 index 00000000..0912a03b --- /dev/null +++ b/users/profiles/desktop/eww/widgets.yuck @@ -0,0 +1,20 @@ +; widgets + +(defpoll time0 :interval "10s" "date '+%H':%M") +(defpoll date :interval "10s" "date '+%b %d'") + +;; Calendar Widgets ;; +(defwidget cal [] + (box :class "cal-box" + :orientation "v" + (box :class "cal-inner-box" + (calendar :class "cal" + :day calendar_day + :month calendar_month + :year calendar_year)))) +(defpoll calendar_day :interval "10h" + "date '+%d'") +(defpoll calendar_month :interval "10h" + "calendar") +(defpoll calendar_year :interval "10h" + "date '+%Y'") diff --git a/users/profiles/desktop/kitty.conf b/users/profiles/desktop/kitty.conf new file mode 100644 index 00000000..643afbcf --- /dev/null +++ b/users/profiles/desktop/kitty.conf @@ -0,0 +1,7 @@ +include ayu.conf +font_family Hermit +bold_font auto +italic_font auto +bold_italic_font auto +open_url_with default +mouse_map left click ungrabbed mouse_click_url_or_select diff --git a/users/profiles/desktop/polybar.conf b/users/profiles/desktop/polybar.conf new file mode 100644 index 00000000..aa45980e --- /dev/null +++ b/users/profiles/desktop/polybar.conf @@ -0,0 +1,385 @@ +[colors] +black = ${xrdb:color0} +bblack = ${xrdb:color8} +red = ${xrdb:color1} +bred = ${xrdb:color9} +green = ${xrdb:color2} +bgreen = ${xrdb:color10} +yellow = ${xrdb:color3} +byellow = ${xrdb:color11} +blue = ${xrdb:color4} +bblue = ${xrdb:color12} +magenta = ${xrdb:color5} +bmagenta = ${xrdb:color13} +cyan = ${xrdb:color6} +bcyan = ${xrdb:color14} +white = ${xrdb:color7} +bwhite = ${xrdb:color15} + +bg = ${xrdb:background} +fg = ${colors.magenta} +bg-alt = #1E2029 +fg-alt = #373844 +bg-dark = #181a23 + +alert = ${colors.yellow} +accent = #604c7e + + +[global/wm] +margin-top = 0 +margin-bottom = 34 + +[bar/main] +monitor = ${env:MONITOR} +monitor-strict = true +enable-ipc = true +wm-restack = bspwm +# REQUIRED to move the window with hideit.sh +override-redirect = true +fixed-center = true + +background = ${colors.bg} +foreground = ${colors.fg} + +width = 100% +height = 34 +offset-x = 0 +offset-y = 0 +# bottom = true + +overline-size = 0 +overline-color = #f00 +underline-size = 0 +underline-color = #00f + +border-bottom-size = 0 +border-top-size = 1 +border-color = ${colors.bg-dark} + +padding-left = 2 +padding-right = 2 +module-margin-left = 0 +module-margin-right = 0 + +font-0 = "Fira Code:pixelsize=9;2" +font-1 = "Wuncon Siji:pixelsize=12;2" +font-2 = "Siji:pixelsize=10;2" + +; modules-left = volume pad cpu memory pad pkg mail +modules-left = pulseaudio pad cpu memory pad fs +modules-center = bspwm +modules-right = syncthing redshift wlan pad network-up pad network-down pad battery pad date + +;tray-position = center +;tray-padding = 2 +;tray-transparent = true +;tray-background = #0063ff + +[module/bspwm] +type = internal/bspwm +pin-workspaces = true +enable-click = true + +# ws-icon-0 = 1; +# ws-icon-1 = 2; +# ws-icon-2 = 3; +# ws-icon-3 = 4; +# ws-icon-4 = 5; +# ws-icon-5 = 6; +ws-icon-default =  + +format = +label-padding = 1 + +label-focused = %icon% +label-focused-background = ${colors.bg-dark} +label-focused-foreground = ${colors.fg} +# label-focused-underline = ${colors.magenta} +; label-focused-foreground = ${xrdb:color2} +label-focused-padding = 1 + +label-occupied = %icon% +label-occupied-foreground = ${colors.accent} +label-occupied-padding = 1 + +; label-urgent = %icon% +label-urgent-foreground = ${colors.alert} +; label-urgent-background = ${colors.alert} +label-urgent-padding = 1 + +label-empty = %icon% +label-empty-foreground = ${colors.fg-alt} +label-empty-padding = 1 + +[module/date] +type = internal/date +interval = 5 + +label = %date% %time% +date = %A, %h %d +date-alt = %Y-%m-%d +time = %I:%M %p +time-alt = %H:%M:%S +format-prefix = "" +format-prefix-padding = 1 +; format-prefix-background = ${colors.bg-alt} +format-prefix-foreground = ${colors.accent} +; format-underline = ${xrdb:color4} + +[module/fs] +type = internal/fs +mount-0 = / +mount-1 = /mnt/projects ; for desktops +mount-2 = /home ; for laptop +interval = 30 + +; Available tags: +; (default) +; +; +; +format-mounted = "" +format-mounted-foreground = ${colors.accent} +; Available tokens: +; %mountpoint% +; %type% +; %fsname% +; %percentage_free% +; %percentage_used% +; %total% +; %free% +; %used% +; Default: %mountpoint% %percentage_free%% + +; Available tags: +; (default) +format-unmounted = +label-unmounted = +label-unmounted-foreground = ${colors.fg-alt} + +bar-used-indicator = +bar-used-width = 8 +bar-used-foreground-0 = ${colors.fg} +bar-used-foreground-1 = ${colors.fg} +bar-used-foreground-2 = ${colors.yellow} +bar-used-foreground-3 = ${colors.alert} +bar-used-foreground-4 = ${colors.alert} +bar-used-fill = | +bar-used-empty = ¦ +bar-used-empty-foreground = ${colors.fg-alt} + +[module/xwindow] +type = internal/xwindow +label = %title:0:80:...% +label-padding-left = 2 + +; [module/mpd] +; type = internal/mpd +; host = /home/hlissner/.config/mpd/mpd.sock +; +; format-online = +; format-padding = 5 +; +; label-song-maxlen = 45 +; label-song-ellipsis = true +; +; icon-prev =  +; icon-seekb =  +; icon-stop =  +; icon-play =  +; icon-pause =  +; icon-next =  +; icon-seekf =  +; +; icon-random =  +; icon-repeat =  +; +; toggle-on-foreground = ${colors.fg} +; toggle-off-foreground = #66 + +[module/cpu] +type = internal/cpu +interval = 2 +format = +format-prefix = "" +format-foreground = ${colors.accent} +; format-underline = #f90000 +; label = %percentage%% +format-padding = 1 + +bar-load-indicator = +bar-load-width = 8 +bar-load-foreground-0 = ${colors.fg} +bar-load-foreground-1 = ${colors.fg} +bar-load-foreground-2 = ${colors.yellow} +bar-load-foreground-3 = ${colors.alert} +bar-load-foreground-4 = ${colors.alert} +bar-load-fill = | +bar-load-empty = ¦ +bar-load-empty-foreground = ${colors.fg-alt} + +[module/memory] +type = internal/memory +interval = 3 +format = +format-prefix = "" +format-prefix-foreground = ${colors.accent} +; format-underline = #4bffdc +; label = %percentage_used%% +format-padding-left = 1 + +; Only applies if is used +bar-used-indicator = +bar-used-width = 8 +bar-used-foreground-0 = ${colors.fg} +bar-used-foreground-1 = ${colors.fg} +bar-used-foreground-2 = ${colors.yellow} +bar-used-foreground-3 = ${colors.alert} +bar-used-foreground-4 = ${colors.alert} +bar-used-fill = | +bar-used-empty = ¦ +bar-used-empty-foreground = ${colors.fg-alt} + +[module/wlan] +type = internal/network +interface = ${env:WLP:wlp3s0} +interval = 3.0 + +format-connected = +format-disconnected = +format-disconnected-foreground = + +; label-connected = +; label-disconnected = ! +; label-disconnected-foreground = ${colors.red} + +ramp-signal-0 =  +ramp-signal-0-foreground = ${colors.yellow} +ramp-signal-1 =  +ramp-signal-1-foreground = ${colors.yellow} +ramp-signal-2 =  +ramp-signal-2-foreground = ${colors.yellow} +ramp-signal-3 =  +ramp-signal-3-foreground = ${colors.accent} +ramp-signal-4 =  +ramp-signal-4-foreground = ${colors.fg} + +[module/network-up] +type = internal/network +interface = ${env:LAN:eno1} +interval = 4.0 +label-connected = "%upspeed%" +format-connected-prefix = " " +format-connected-prefix-foreground = ${colors.accent} +format-connected-foreground = ${colors.fg} +format-connected-background = +format-connected-underline = +format-disconnected-prefix = " " +format-disconnected-prefix-foreground = ${colors.alert} +format-disconnected-foreground = ${colors.alert} + +[module/network-down] +type = internal/network +interface = ${env:LAN:eno1} +interval = 4.0 +label-connected = "%downspeed%" +format-connected-prefix = " " +format-connected-prefix-foreground = ${colors.accent} +format-connected-foreground = ${colors.fg} +format-connected-background = +format-connected-underline = +format-disconnected-prefix = " " +format-disconnected-prefix-foreground = ${colors.alert} +format-disconnected-foreground = ${colors.alert} + +[module/pulseaudio] +type = internal/pulseaudio + +; format-volume = +format-volume = +; label-volume = " " +label-volume-foreground = ${colors.accent} + +; format-muted-prefix = " " +format-muted-foreground = ${colors.alert} +label-muted =  + +bar-volume-width = 8 +# bar-volume-foreground-0 = ${colors.magenta} +# bar-volume-foreground-1 = ${colors.magenta} +# bar-volume-foreground-2 = ${colors.magenta} +# bar-volume-foreground-3 = ${colors.magenta} +# bar-volume-foreground-4 = ${colors.magenta} +# bar-volume-foreground-5 = ${colors.magenta} +# bar-volume-foreground-6 = ${colors.magenta} +bar-volume-gradient = false +bar-volume-indicator = | +bar-volume-indicator-font = 1 +bar-volume-indicator-foreground = #ff +bar-volume-fill = ─ +bar-volume-fill-font = 1 +bar-volume-empty = ─ +bar-volume-empty-font = 1 +bar-volume-empty-foreground = ${colors.fg-alt} + +; Only applies if is used +ramp-volume-0 =  +ramp-volume-1 =  +ramp-volume-2 =  + +[module/battery] +type = internal/battery +battery = BAT2 +adapter = ADP1 +full-at = 98 + +format-charging = +format-charging-underline = #ffb52a + +format-discharging = +format-discharging-underline = ${self.format-charging-underline} + +format-full-prefix = " " +format-full-prefix-foreground = ${colors.fg-alt} +format-full-underline = ${self.format-charging-underline} + +ramp-capacity-0 =  +ramp-capacity-1 =  +ramp-capacity-2 =  +ramp-capacity-0-foreground = ${colors.red} +ramp-capacity-1-foreground = #575864 +ramp-capacity-2-foreground = ${colors.fg-alt} + +animation-charging-0 =  +animation-charging-1 =  +animation-charging-2 =  +animation-charging-framerate = 1000 +animation-charging-foreground = ${colors.fg} + + +;===================================================== +; Custom scripts +;===================================================== + +[module/pad] +type = custom/text +content = " " +content-foreground = ${colors.fg-alt} + +[module/redshift] +type = custom/script +exec = ~/.config/polybar/modules/redshift +exec-if = pgrep -x redshift +interval = 60 +format-padding = 1 + +[module/syncthing] +type = custom/script +exec = echo 1 +exec-if = systemctl is-active syncthing +format = "" +format-foreground = ${colors.fg} +interval = 30 + +; vim:ft=dosini diff --git a/users/profiles/desktop/polybar/config b/users/profiles/desktop/polybar/config new file mode 100644 index 00000000..4532935a --- /dev/null +++ b/users/profiles/desktop/polybar/config @@ -0,0 +1,411 @@ +[colors] + +yellow = #ffd580 +orange = #fe8019 +blue = #73d0ff +green = #bae67e +red = #ff3333 +bg = #1f2430 +fg = #bfbab0 +icons = #bae67e +cyan = #95e6cb +text = ${xrdb:color2} +unfocus = ${xrdb:color1} +accent = #604c7e +sky = #73d0ff +mauve = #bae67e +alert = ${colors.yellow} + +bg-alt = #1E2029 +fg-alt = #373844 +bg-dark = #181a23 + +[bar/mybar] +; monitor = VGA-1 + +override-redirect = false + +; Put the bar at the bottom of the screen +bottom = false + +; Prefer fixed center position for the `modules-center` block +fixed-center = true + +width = 100% +height = 34 + +offset-x = +offset-y = + +; Background ARGB color (e.g. #f00, #ff992a, #ddff1023) +background = ${colors.bg} + +; Foreground ARGB color (e.g. #f00, #ff992a, #ddff1023) +foreground = ${colors.fg} + +line-size = 0 +line-color = #fff + +; Number of spaces to add at the beginning/end of the bar +; Individual side values can be defined using: +; padding-{left,right} +padding-right = 1 +padding-left = 0 + +; Number of spaces to add before/after each module +; Individual side values can be defined using: +; module-margin-{left,right} +module-margin = 0 +margin-bottom = 34 + +font-0 = "Iosevka Term:pixelsize=13;4" +font-1 = "Iosevka Term:pixelsize=6;1" +font-2 = "Fira Code:pixelsize=13;2" +font-3 = "Siji:pixelsize=8;2" + +; Add module mpd for artist - title info +modules-left = bspwm sps volume +modules-center = title +modules-right = wireless-network sps battery sps memory sps cpu sps date + +; The separator will be inserted between the output of each module +separator = + +; This value is used to add extra spacing between elements +; @deprecated: This parameter will be removed in an upcoming version +spacing = 0 + +; Opacity value between 0.0 and 1.0 used on fade in/out +dim-value = 1.0 + +wm-name = bspwm + +tray-position = right + +; If true, the bar will not shift its +; contents when the tray changes +tray-detached = false + +; Tray icon max size +tray-maxsize = 16 + +tray-background = ${colors.bg} +;offset defined as pixel value (e.g. 35) or percentage (e.g. 50%) + +tray-offset-x = 0 +tray-offset-y = 0 + +; Pad the sides of each tray icon +tray-padding = 0 + +; Scale factor for tray clients +tray-scale = 1.0 + +wm-restack = bspwm + +dpi-x = 133 +dpi-y = 133 + +enable-ipc = false + +; Fallback click handlers that will be called if +; there's no matching module handler found. + +[module/bspwm] +type = internal/bspwm +pin-workspaces = true +enable-click = true + +ws-icon-0 = 1;%{T1}%{T-} +ws-icon-1 = 2;%{T1}%{T-} +ws-icon-2 = 3;%{T1}%{T-} +ws-icon-3 = 4;%{T1}%{T-} +ws-icon-4 = 5;%{T1}%{T-} +ws-icon-default =  +; fuzzy-match = true + +format = +label-padding = 1 +label-foreground = ${colors.green} + +label-focused = %icon% +label-focused-background = ${colors.yellow} +label-focused-foreground = ${colors.bg} +# label-focused-underline = ${colors.magenta} +; label-focused-foreground = ${xrdb:color2} +label-focused-padding = 1 + +label-occupied = %icon% +label-occupied-foreground = ${colors.accent} +label-occupied-padding = 1 + +label-urgent = %icon% +label-urgent-foreground = ${colors.alert} +; label-urgent-background = ${colors.alert} +label-urgent-padding = 1 +; label-urgent-font = 3 + +label-empty = %icon% +label-empty-foreground = ${colors.fg-alt} +label-empty-padding = 1 + +[module/date] +type = internal/date + +; Seconds to sleep between updates +interval = 1.0 + +; See "http://en.cppreference.com/w/cpp/io/manip/put_time" for details on how to format the date string +; NOTE: if you want to use syntax tags here you need to use %%{...} +date = %{T1}%{T-}%{T2} %d/%a%{T-} + +; Optional time format +time = %{T2} %H:%M%{T-} + +; if `date-alt` or `time-alt` is defined, clicking +; the module will toggle between formats +date-alt = %{T1}%{T-}%{T2} %a, %d %b %y%{T-} +time-alt = %{T2} %H:%M:%S%{T-} + +label = %date%%time% +label-font = 0 +label-foreground = ${colors.green} + +[module/wireless-network] +type = internal/network +interface = wlp3s0 + +label-connected = %essid% +label-connected-font = 2 +format-connected = +label-connected-foreground = #82b414 + +format-disconnected = +label-disconnected = "睊" +label-disconnected-foreground = #f92672 + +ramp-signal-foreground = #82b414 +ramp-signal-0 = " " +ramp-signal-1 = " " +ramp-signal-2 = " " +ramp-signal-3 = " " +ramp-signal-4 = " " +ramp-signal-5 = " " + +[module/cpu] +type = internal/cpu + +; Seconds to sleep between updates +; Default: 1 +interval = 0.5 + +label = %{T1}%{T-}%{T2} %percentage:2%%%{T-} + +label-foreground = ${colors.cyan} + +[module/memory] +type = internal/memory + +; Seconds to sleep between updates +; Default: 1 +interval = 0.5 +format =