" >> $(APPNAME)_$(VERSION)-1_$(1)/DEBIAN/control @echo "Architecture: $(1)" >> $(APPNAME)_$(VERSION)-1_$(1)/DEBIAN/control @echo "Description: My CLI tool" >> $(APPNAME)_$(VERSION)-1_$(1)/DEBIAN/control @dpkg-deb --build -Zgzip $(APPNAME)_$(VERSION)-1_$(1) @rm -rf $(APPNAME)_$(VERSION)-1_$(1) endef ``` The `-Zgzip` flag tells `dpkg-deb` to use gzip compression, which produces slightly larger packages than xz but is more universally compatible. The version is injected automatically from the latest git tag: ```makefile VERSION := $(shell git describe --tags --abbrev=0) ``` So tagging a release in git is all it takes to produce the correct package version. # Step 2: the `aptblob` tool The real hero of this setup is [`zombiezen.com/go/aptblob`](https://pkg.go.dev/zombiezen.com/go/aptblob). It is a small Go utility that creates and maintains APT repositories without requiring you to install `reprepro`, `aptly`, or any other heavyweight tooling. Because it is fetched and run via `go run`, there is no separate installation step — Go's module system handles it. `aptblob` supports multiple storage backends via URL: `file://` for local disk, and cloud storage providers for production hosting. # Step 3: initialising the repository Before uploading any packages, the repository needs to be bootstrapped with an `InRelease` file that describes the repository metadata. This is handled by `init-repo.sh`: ```bash #!/usr/bin/env bash go run zombiezen.com/go/aptblob@latest init -k $KEY_ID "file://`pwd`/apt-repo" stable <`. Once a user runs `brew tap org/something`, Homebrew knows to look for formulas in that repo. From that point on, `brew install org/something/mycli` works exactly like installing any official Homebrew package.
The naming convention is the only magic: no registration, no approval process. Anyone can host a tap.
# The formula
Formulas live in a `Formula/` directory and are written in Ruby using Homebrew's DSL. For a pre-built Go binary, the formula is remarkably simple:
```ruby
class MyCli < Formula
desc "CLI interface for My App"
homepage "https://example.com"
url "https://cdn.example.com/mycli/5c7b6ef47a682ffe.../mycli-macos.tar.gz"
version "1.47.0"
sha256 "48e146382b0f527549328da4bed9d90f2d584e1b05a8f94846cf47c3c66a9343"
license "MIT"
def install
bin.install "mycli"
end
test do
system "#{bin}/mycli", "--version"
end
end
```
There are only four things that change on each release:
- `url` — points to the new tarball on the CDN
- `version` — the semver string shown by `brew info`
- `sha256` — the checksum Homebrew verifies before unpacking
The `install` block copies the binary into the Homebrew prefix (`/opt/homebrew/bin/` on Apple Silicon, `/usr/local/bin/` on Intel). The `test` block is a smoke test Homebrew runs after install — here, just confirming the binary exits cleanly when asked for its version.
# Building a universal macOS binary
The URL points to a `.tar.gz` containing a single binary. Rather than shipping separate arm64 and x86_64 tarballs and maintaining two formula entries, we use `lipo` to merge them into one universal binary:
```makefile
define build-binary-mac
@echo "Building for macos"
GOOS=darwin GOARCH=arm64 go build -o mycli-arm .
GOOS=darwin GOARCH=amd64 go build -o mycli-x86 .
lipo -create -output mycli mycli-x86 mycli-arm
tar czf ./mycli-macos.tar.gz mycli
rm -f mycli-x86 mycli-arm mycli
endef
```
`GOOS=darwin GOARCH=arm64 go build` and `GOOS=darwin GOARCH=amd64 go build` produce two binaries. `lipo -create` stitches them into a Fat Binary that macOS automatically runs under the native architecture. The result: one tarball, one formula URL, works on both Apple Silicon and Intel Macs without any user-facing complexity.
# The CDN URL strategy
The binary is uploaded to object storage (DigitalOcean Spaces in our case, but S3 or any public CDN works equally well). The URL path includes the git commit SHA:
```
https://cdn.example.com/mycli/{git-sha}/mycli-macos.tar.gz
```
Embedding the commit SHA rather than the version tag means:
- Uploads are naturally immutable — the same SHA always points to the same build
- Multiple release candidates for the same version cannot collide
- The `create-index.py` script (which generates a `index.json` listing all build artifacts) uses the same SHA, keeping the release artefacts coherent
# Updating the formula
When a new version ships:
1. Build and upload the tarball: `make build-all` produces `mycli-macos.tar.gz`; CI uploads it to the CDN under the new commit SHA.
2. Compute the SHA256 of the tarball: `sha256sum mycli-macos.tar.gz`
3. Update three lines in the formula: `url`, `version`, `sha256`
4. Open a PR against the tap repository
The tap CI then validates the change before it merges (more on that below).
# CI: validating formulas with `brew test-bot`
The tap repo includes a GitHub Actions workflow that runs on every push and pull request:
```yaml
name: brew test-bot
on:
push:
branches: [main]
pull_request:
jobs:
test-bot:
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: Homebrew/actions/setup-homebrew@main
- run: brew test-bot --only-cleanup-before
- run: brew test-bot --only-setup
- run: brew test-bot --only-tap-syntax
- run: brew test-bot --only-formulae
if: github.event_name == 'pull_request'
- name: Upload bottles as artifact
if: always() && github.event_name == 'pull_request'
uses: actions/upload-artifact@main
with:
name: bottles
path: '*.bottle.*'
```
`brew test-bot` is Homebrew's own CI harness. The steps do progressively more:
| Step | What it checks |
|------|---------------|
| `--only-tap-syntax` | Ruby syntax, formula naming conventions, `brew audit` rules |
| `--only-formulae` | Actually installs the formula and runs the `test do` block |
Running on both `ubuntu-latest` and `macos-latest` catches issues specific to either platform — important because Homebrew has first-class Linux support (`Linuxbrew`) and many teams use it in Docker-based CI.
# CI: Merging PRs with `brew pr-pull`
The second workflow handles the merge step:
```yaml
name: brew pr-pull
on:
pull_request_target:
types: [labeled]
jobs:
pr-pull:
if: contains(github.event.pull_request.labels.*.name, 'pr-pull')
runs-on: ubuntu-22.04
steps:
- uses: Homebrew/actions/setup-homebrew@main
- uses: Homebrew/actions/git-user-config@main
- name: Pull bottles
env:
HOMEBREW_GITHUB_API_TOKEN: ${{ github.token }}
PULL_REQUEST: ${{ github.event.pull_request.number }}
run: |
brew pr-pull --debug --tap="$GITHUB_REPOSITORY" "$PULL_REQUEST"
- uses: Homebrew/actions/git-try-push@main
with:
token: ${{ github.token }}
branch: main
- name: Delete branch
if: github.event.pull_request.head.repo.fork == false
run: git push --delete origin "$BRANCH"
```
Instead of merging PRs normally, a maintainer applies the `pr-pull` label. `brew pr-pull` then:
1. Downloads any pre-built bottles attached to the PR as GitHub Actions artifacts
2. Commits the bottle checksums into the formula
3. Pushes directly to `main` and deletes the PR branch
This mirrors the workflow used by the official Homebrew/homebrew-core tap and means the merge is always handled by Homebrew's own tooling rather than GitHub's merge button.
For a simple pre-built binary formula (no compilation step, no bottle needed), this is mostly ceremony — but it is good practice because it keeps the tap workflow consistent with the broader Homebrew ecosystem and makes it easy to add bottles later if the build-from-source path is ever needed.
# The user experience
After all of this, the user-facing story is clean:
```bash
# One-time setup
brew tap myorg/mycli
# Install
brew install mycli
# Upgrade when a new version ships
brew upgrade mycli
```
And because Homebrew auto-discovers shell completions in `share/zsh/site-functions/`, `share/bash-completion/`, and similar paths, completions are picked up automatically if the binary generates them into those locations at install time.
# Summary
| Component | What it does |
|-----------|-------------|
| `homebrew-mycli` repo | The tap — a public GitHub repo Homebrew reads formulas from |
| `Formula/mycli.rb` | Declares the URL, version, checksum, install path, and smoke test |
| Universal binary (`lipo`) | One tarball covers both Apple Silicon and Intel in a single formula entry |
| CDN + commit SHA URL | Immutable, content-addressed artifact storage |
| `brew test-bot` CI | Validates formula syntax and install on every PR |
| `brew pr-pull` CI | Homebrew-native merge flow that handles bottle attachment |
The tap repository itself is under 20 lines of real content. Most of the work is a one-time setup; after that, each release is a three-line diff to the formula and a label click to merge.
---
--- title: Adding 2FA to Phoenix LiveView with phx.gen.auth. tags: ["auth", "phoenix", "elixir"] ---
Two-factor authentication (2FA) is a great way to improve account security. This post walks through how to add TOTP-based 2FA to a Phoenix LiveView app using the built-in `phx.gen.auth` authentication system.
We’ll cover:
* Adding required fields and dependencies
* 2FA setup flow using LiveView
* TOTP challenge during login
* LiveView-specific login handling
---
## Add dependencies
Add the following libraries to `mix.exs`:
```elixir
defp deps do
[
{:nimble_totp, "~> 1.0"},
{:qr_code, "~> 2.2"}
]
end
```
Then run:
```bash
mix deps.get
```
---
## Extend the user schema
Add two fields to your `users` table:
```elixir
# priv/repo/migrations/*_add_totp_to_users.exs
alter table(:users) do
add :totp_secret, :string
add :totp_confirmed_at, :utc_datetime
end
```
Migrate:
```bash
mix ecto.migrate
```
In your user schema:
```elixir
schema "users" do
field :totp_secret, :string
field :totp_confirmed_at, :utc_datetime
# ...
end
```
Ensure your `changeset/2` casts these fields:
```elixir
def changeset(user, attrs) do
user
|> cast(attrs, [:email, :totp_secret, :totp_confirmed_at])
|> validate_required([:email])
end
```
---
## Add 2FA setup LiveView
Create a new LiveView at `/settings/two_factor` that generates a secret, renders a QR code, and lets the user enter their TOTP code.
```elixir
defmodule MyAppWeb.TwoFactorSetupLive do
use MyAppWeb, :live_view
alias NimbleTOTP
alias QRCode
alias MyApp.Accounts
def mount(_params, _session, socket) do
user = socket.assigns.current_user
if user.totp_secret do
{:ok, assign(socket, setup?: false)}
else
secret = Base.encode32(NimbleTOTP.secret())
uri = NimbleTOTP.otpauth_uri("MyApp:#{user.email}", Base.decode32!(secret), issuer: "MyApp")
{:ok, png} = QRCode.create(uri, :png)
b64 = Base.encode64(png)
{:ok,
assign(socket,
setup?: true,
secret: secret,
qr_code: "data:image/png;base64,#{b64}",
code: "",
error: nil
)}
end
end
def handle_event("verify", %{"code" => code}, socket) do
secret = Base.decode32!(socket.assigns.secret)
if NimbleTOTP.valid?(secret, code) do
{:ok, _} =
Accounts.update_user(socket.assigns.current_user, %{
totp_secret: socket.assigns.secret,
totp_confirmed_at: DateTime.utc_now()
})
{:noreply,
socket
|> put_flash(:info, "2FA enabled.")
|> push_redirect(to: "/settings")}
else
{:noreply, assign(socket, error: "Invalid code")}
end
end
end
```
```heex
<%= if @error, do: content_tag(:p, @error, class: "text-red-500") %>
<% else %>
```
Keep in mind that summing RSS values from multiple processes can overestimate actual memory usage because shared memory pages may be counted multiple times.
# Monitoring memory usage over time
For live monitoring:
```bash
watch -n 1 \
'systemctl show my-service.service --property=MemoryCurrent --value'
```
Or use:
```bash
systemd-cgtop
```
This tool displays CPU, memory, and I/O usage per cgroup and is often the most convenient way to identify memory-hungry services on a system.
# Configuring memory limits
Systemd can also enforce memory limits.
Example:
```ini
[Service]
MemoryMax=1G
```
After updating the unit file:
```bash
sudo systemctl daemon-reload
sudo systemctl restart my-service.service
```
To verify the configured limit:
```bash
systemctl show my-service.service --property=MemoryMax
```
# Conclusion
For services managed by systemd, `MemoryCurrent` is usually the most accurate representation of how much memory the service is actually consuming. Unlike process-level tools, it accounts for the entire cgroup, making it ideal for monitoring applications that use worker pools, background jobs, or multiple child processes.
Useful commands to remember:
```bash
systemctl status my-service.service
systemctl show my-service.service --property=MemoryCurrent
systemd-cgtop
```
These provide a much clearer picture of service-level memory usage than inspecting individual processes alone.
---
--- title: Fixing PHPUnit 13 with*() without expects() deprecations in Laravel tests. tags: ["php", "laravel", "testing", "best-practice"] ---
After upgrading to PHPUnit 13, you may run into this deprecation warning in Laravel test suites:
```text
Using with*() without expects() is deprecated and will no longer be possible in PHPUnit 14.
```
At first sight, the code often already looks correct:
```php
$mock->expects($this->once())
->method('runSequenceOfCommands')
->with([...]);
```
So what is actually causing the warning?
# The real issue
In many Laravel applications, the problem comes from using Laravel’s `createPartialMock()` helper together with newer PHPUnit versions.
Example:
```php
$class = $this->createPartialMock(
NightlyCommand::class,
['runSequenceOfCommands']
);
```
While this worked fine in older PHPUnit versions, PHPUnit 13 tightened internal mock expectation handling and now emits deprecation warnings in some cases when using Laravel’s wrapper helpers.
# The fix
Instead of `createPartialMock()`, use PHPUnit’s native mock builder API.
Replace this:
```php
$class = $this->createPartialMock(
NightlyCommand::class,
['runSequenceOfCommands']
);
```
With this:
```php
$class = $this->getMockBuilder(NightlyCommand::class)
->onlyMethods(['runSequenceOfCommands'])
->getMock();
```
And for multiple mocked methods:
```php
$class = $this->getMockBuilder(NightlyCommand::class)
->onlyMethods([
'runSequenceOfCommands',
'confirm',
])
->getMock();
```
# Why this works
`getMockBuilder()` uses PHPUnit’s modern native mock API directly, avoiding the legacy compatibility layer behind Laravel’s partial mock helpers.
This makes your tests:
* compatible with PHPUnit 13
* future-proof for PHPUnit 14
* less dependent on framework-specific mock wrappers
# Final result
Your expectations can stay exactly the same:
```php
$class->expects($this->once())
->method('runSequenceOfCommands')
->with(
$this->isInstanceOf(NightlyCommand::class),
[
// expected commands
]
);
```
But by switching to `getMockBuilder()`, the deprecation warning disappears cleanly.
---
--- title: Why crypto.getRandomValues() matters in JavaScript. tags: ["auth", "javascript", "best-practice"] ---
Generating random values sounds simple, until you need randomness that is actually secure.
A lot of JavaScript developers reach for `Math.random()` out of habit. While that works fine for visual effects, games, or non-critical IDs, it should never be used for anything security-sensitive.
That’s where the Web Crypto API comes in.
# The problem with `Math.random()`
`Math.random()` is not cryptographically secure.
Its output is deterministic and predictable enough that an attacker may be able to reproduce or guess generated values under certain conditions.
That makes it unsuitable for:
* Session tokens
* Password reset links
* API keys
* CSRF tokens
* Encryption keys
* Secure identifiers
Example:
```javascript
const id = Math.random().toString(36).slice(2)
```
This may look random, but it is not secure.
# Using `crypto.getRandomValues()`
Modern browsers provide a secure random number generator through the Web Crypto API.
Example:
```javascript
const bytes = new Uint8Array(16)
crypto.getRandomValues(bytes)
console.log(bytes)
```
This fills the typed array with cryptographically secure random bytes provided by the operating system.
# Generating a secure random token
A common use case is generating secure tokens or identifiers.
```javascript
function generateToken(length = 32) {
const bytes = new Uint8Array(length)
crypto.getRandomValues(bytes)
return Array.from(bytes)
.map(byte => byte.toString(16).padStart(2, "0"))
.join("")
}
console.log(generateToken())
```
Example output:
```text
4f8b7d3a1f9e0c8d7a2b6c5d4e3f1a9c
```
This is significantly safer than using `Math.random()`.
# Typed arrays are required
`crypto.getRandomValues()` only works with integer-based typed arrays.
Supported examples include:
```javascript
new Uint8Array(32)
new Uint16Array(16)
new Int32Array(8)
```
This will fail:
```javascript
crypto.getRandomValues([])
```
Because regular JavaScript arrays are not supported.
# Browser and runtime support
`crypto.getRandomValues()` is widely supported in modern browsers.
It is also available in runtimes like:
* Node.js
* Deno
* Bun
Example in Node.js:
```javascript
const bytes = new Uint8Array(16)
crypto.getRandomValues(bytes)
console.log(bytes)
```
In older Node.js versions, developers typically used:
```javascript
require("crypto").randomBytes(16)
```
# UUID generation
If your goal is generating UUIDs, modern runtimes also support:
```javascript
crypto.randomUUID()
```
Example:
```text
550e8400-e29b-41d4-a716-446655440000
```
Internally, this also uses cryptographically secure randomness.
# Things to remember
* Use `Math.random()` for non-security-related randomness only
* Use `crypto.getRandomValues()` for anything security-sensitive
* Prefer `crypto.randomUUID()` when generating UUIDs
* Always generate randomness using the operating system’s secure RNG
For modern JavaScript applications, `crypto.getRandomValues()` should be the default choice whenever security matters.
---
--- title: How to find all Jira issues ever assigned to someone (even historical ones). tags: ["tools", "best-practice"] ---
If you've ever tried to pull up all the tickets that **Sarah Mitchell** worked on last year, you've probably started with the obvious query:
```jql
assignee = "sarah.mitchell@example.com"
```
And then realised it only shows her *current* tickets — not the ones she handed off to **Tom Bergkamp** or closed six months ago.
Here's the fix.
# The `was` operator
Jira's JQL has a `was` operator that checks the **change history** of a field, not just its current value. So to find every issue Sarah was ever assigned to:
```jql
assignee was "sarah.mitchell@example.com"
```
Simple, but powerful.
# Checking multiple people at once
Need to audit the work of an entire sub-team? Use `was in` with a list:
```jql
assignee was in ("sarah.mitchell@example.com", "tom.bergkamp@example.com", "priya.nair@example.com")
```
This returns any issue that was assigned to *any* of those three people at any point in time.
# Scoping to a specific year
Combine it with the `during` clause to limit results to a time window — useful for annual reviews, retrospectives, or handover audits:
```jql
assignee was in ("sarah.mitchell@example.com", "tom.bergkamp@example.com") during ("2025-01-01", "2025-12-31")
```
This only matches issues where one of them was the assignee *at some point during 2025* — even if the ticket has since been reassigned or closed.
# Putting it all together
A full, practical query might look like this:
```jql
project = "PLATFORM"
AND assignee was in ("sarah.mitchell@example.com", "tom.bergkamp@example.com")
AND during ("2025-01-01", "2025-12-31")
ORDER BY updated DESC
```
The `was` operator works on other fields too — `status was "In Progress"`, `priority was "High"`, etc. — so it's worth keeping in your JQL toolkit whenever you need to query history rather than current state.
---
--- title: Downloading external images as squares from a Phoenix app. tags: ["frontend", "elixir", "phoenix", "javascript"] ---
A common need in admin tools: click a button, download a remote image as a square JPEG. Simple enough — until CORS gets in the way.
# The CORS problem
When fetching a cross-origin image and drawing it onto a `
Two-Factor Authentication
<%= if @setup? do %>Scan this QR code in your authenticator app:
2FA is already enabled.
<% end %> ``` --- ## Add a TOTP challenge LiveView When a user logs in with 2FA enabled, redirect them to a LiveView at `/two_factor` to enter their code. ```elixir defmodule MyAppWeb.TwoFactorChallengeLive do use MyAppWeb, :live_view alias MyApp.Accounts alias NimbleTOTP alias MyAppWeb.UserAuth def mount(_params, %{"pending_user_id" => id}, socket) do {:ok, assign(socket, user: Accounts.get_user!(id), code: "", error: nil)} end def handle_event("verify", %{"code" => code}, socket) do user = socket.assigns.user if NimbleTOTP.valid?(Base.decode32!(user.totp_secret), code) do {:noreply, socket |> put_flash(:info, "Logged in with 2FA.") |> UserAuth.log_in_user(user, %{})} else {:noreply, assign(socket, error: "Invalid code")} end end end ``` ```heex