# Secure a new project

A new integration or card, from the first commit to the first release. A new repository is the easiest place to start, because nothing in it depends on the old way yet.

Source: https://ha-barkley.github.io/security/walk-throughs/new-project/

From HASC, the Home Assistant Security Controls for integrations, cards and apps. A community catalog, not an official Home Assistant or Open Home Foundation project.

Each control has an ID, cited as HASC-CI-4, and a level from 1 to 3. "Level marker" means anyone can check the control from outside the project, and levels are graded on those controls only.

## Your answers

Some steps depend on these answers. Those steps say which answer they're for.

- What are you building? "An integration", "A dashboard card" or "An app (add-on)"
- Where will the repository live? "My own account" or "An organization with a security configuration"

## Before you create the repository

Lock down your account first. If you sign commits (level 2), set it up now, so every commit in the project is signed. [Your GitHub account](https://ha-barkley.github.io/security/controls/account/) has every account control.

### ACC-1: Turn on two-factor login with a passkey or a security key

*Level 1*

**Why:** A common way to take over an account is a page that looks like a real login. A password and an authenticator code work on any site you type them into, and a lookalike can pass them straight on to the real one. A passkey or security key only works on the site it was made for. In 2025, phishing like this was used to publish malware from maintainers' accounts on both PyPI and npm ([how it happened](https://ha-barkley.github.io/security/attacks/#phishing)).

Settings → Password and authentication. An authenticator app is fine as a second method. Avoid SMS. Store the recovery codes somewhere offline.

### ACC-4: Sign your commits

*Level 2 · Level marker*

**Why:** Git lets anyone put any name and email on a commit. A signature can't be made without your key, so signed commits let people tell your work from a commit pushed with a stolen token or written to look like yours. In 2021, two malicious commits were pushed to PHP's source code in the names of two of its core developers ([PHP's announcement](https://news-web.php.net/php.internals/113838)).

An SSH key is the simplest way. You can use the one you already push with.

1. If you don't have an SSH key, run `ssh-keygen -t ed25519`. It saves the public half as `~/.ssh/id_ed25519.pub`.
2. Tell Git to sign every commit and tag with it.
   
   `Terminal`
   
   ```
   git config --global gpg.format ssh
   git config --global user.signingkey ~/.ssh/id_ed25519.pub
   git config --global commit.gpgsign true
   git config --global tag.gpgsign true
   ```
   
   Change the path if your key has a different name.
3. Give GitHub the public key, so it can check your signatures. Until you do, your signed commits show "Unverified". In Settings → SSH and GPG keys, choose New SSH key, set Key type to *Signing Key*, and paste the line that `cat ~/.ssh/id_ed25519.pub` prints. Only share the file ending in `.pub`. The one without `.pub` is your private key. From a terminal, the GitHub CLI can do it instead:
   
   `Terminal`
   
   ```
   gh auth refresh -h github.com -s admin:ssh_signing_key
   gh ssh-key add ~/.ssh/id_ed25519.pub --type signing --title "My laptop"
   ```
   
   A key you already added for pushing has to be added again as a signing key.

Where the private key is kept decides what someone gets if they copy your files or run code on your machine:

| Where the key is                                    | Someone copies your files         | Malware runs as you               | Day to day                                                        |
|-----------------------------------------------------|-----------------------------------|-----------------------------------|-------------------------------------------------------------------|
| A file with no passphrase                           | They have your key                | Can sign                          | Nothing to type                                                   |
| A file with a passphrase, loaded into the SSH agent | Useless without the passphrase    | Can sign while the key is loaded  | Unlock once per login. macOS can keep the passphrase in Keychain. |
| A password manager's SSH agent                      | There's no key file               | Asks before each app uses the key | Approve each app                                                  |
| A security key (`ssh-keygen -t ed25519-sk`)         | The key never leaves the hardware | Needs a touch for every signature | A touch for every commit, so a rebase of 20 commits is 20 touches |

With a password manager, its own instructions give the value for `user.signingkey`. GPG keys work too, with GitHub's GPG instructions.

In a codespace you don't need a key of your own. Turn on Settings → Codespaces → GPG verification for the repositories you trust, and GitHub signs the commits you make there. Commits you make on GitHub's website are signed by GitHub already.

### ACC-5: Then turn on vigilant mode

*Level 2*

**Why:** Signing only helps if an unsigned commit in your name stands out. Without vigilant mode, GitHub shows an unsigned commit with no label, like most commits. With it on, an unsigned commit in your name shows "Unverified".

On the same page, tick "Flag unsigned commits as unverified". Any commit with your name that you didn't sign then shows "Unverified", including one pushed with a stolen token. Wait until a commit you push shows "Verified", or your own commits show "Unverified" too.

## Start with these files

Put them in the first commit, so the repository never holds a secret and people can report a problem from day one.

### REPO-3: Add a .gitignore

*Level 1*

**Add a .gitignore** before your first commit.

`.gitignore`

```
# Python
__pycache__/
*.py[cod]
.venv/
.pytest_cache/
.ruff_cache/
.coverage

# Node
node_modules/

# Secrets and local settings
.env
.env.*
secrets.yaml
*.pem
*.key

# Editors and OS
.idea/
.DS_Store
```

### POL-2: Add a SECURITY.md

*Level 1 · Level marker*

**Add a SECURITY.md** that points to it. In an organization, one `SECURITY.md` in its public `.github` repository covers every repository that doesn't have its own (see [Organizations](https://ha-barkley.github.io/security/controls/organizations/)).

`SECURITY.md`

```
# Security policy

## Reporting a problem

Please don't open a public issue. Report it privately through
GitHub: https://github.com/OWNER/REPO/security/advisories/new

I'll reply within 7 days and keep you posted until it's fixed.

## Supported versions

Only the latest release gets security fixes.
```

### REPO-2: Turn off blank issues and link the private report

*Level 1*

`.github/ISSUE_TEMPLATE/config.yml`

```
blank_issues_enabled: false
contact_links:
  - name: Report a security problem
    url: https://github.com/OWNER/REPO/security/advisories/new
    about: Please report security problems privately, not as an issue.
```

### REPO-1: Add a bug report form

*Level 1*

`.github/ISSUE_TEMPLATE/bug_report.yml`

```
name: Bug report
description: Something isn't working
labels: [bug]
body:
  - type: input
    id: version
    attributes:
      label: App version
      placeholder: "1.4.2"
    validations:
      required: true
  - type: input
    id: ha-version
    attributes:
      label: Home Assistant version
      placeholder: "2026.11.2"
    validations:
      required: true
  - type: dropdown
    id: install
    attributes:
      label: Installation type
      options: [Home Assistant OS, Container, Other]
  - type: textarea
    id: what
    attributes:
      label: What happened, and what did you expect?
    validations:
      required: true
  - type: textarea
    id: logs
    attributes:
      label: Logs
      description: Remove tokens, passwords and addresses before pasting.
      render: shell
```

## Turn on GitHub's checks

*Only for: My own account*

They're free for public repositories, and they're all in the repository's Settings → Advanced Security.

### POL-1: Turn on private vulnerability reporting

*Level 1*

Settings → Advanced Security → Private vulnerability reporting → Enable. People then get a "Report a vulnerability" button on your Security and quality tab, and their report reaches you privately. You can ask questions, reject it, or accept it as a draft advisory to work in.

### CI-1: Turn on CodeQL default setup

*Level 1 (or a security workflow) · Level marker*

Settings → Advanced Security → Code scanning → CodeQL analysis → Set up → Default. It picks up Python, JavaScript and TypeScript, and runs on every pull request. Check that GitHub Actions is in its list of languages too, because that's the language that scans your workflow files, and default setup doesn't always include it. If it's missing, choose View CodeQL configuration, then Edit, select GitHub Actions under Languages, and choose Save changes.

### CI-3: Turn on secret scanning and push protection

*Level 1*

Settings → Advanced Security. Push protection stops a push that contains a known token format before it reaches GitHub.

### CI-2: Turn on Dependabot alerts and security updates

*Level 1 · Level marker*

**Turn on Dependabot alerts and security updates** in the same Settings page, then add version updates for your package files and your workflow actions.

`.github/dependabot.yml`

```
version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
  - package-ecosystem: "npm"        # cards: package.json and its lockfile
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
```

Dependabot doesn't read an integration's `manifest.json`. The workflow below checks those requirements with pip-audit instead.

`cooldown` makes Dependabot wait until a release is 7 days old before proposing it. It only delays version updates; security updates still arrive straight away.

### DEP-4: Wait at least 7 days before taking a new release

*Level 1*

**Why:** Malicious versions are usually found and removed fast. npm removed the September 2025 phishing versions the same day, and TanStack's within about four and a half hours. With a 7-day cooldown, Dependabot only offers a release once it has been public for a week, so versions like these have been removed before it offers them ([how it happened](https://ha-barkley.github.io/security/attacks/#phishing)).

Set `cooldown: default-days: 7` in `dependabot.yml` (Dependabot waits 3 days if you set nothing), or `"minimumReleaseAge": "7 days"` in Renovate. Security updates aren't delayed.

> The `dependabot.yml` above already sets a 7-day cooldown.

## Check what your organization turned on

*Only for: An organization with a security configuration*

Your organization's configuration turned most of these on when you created the repository. Open the repository's Settings → Advanced Security to see them, and tick each one you find.

### POL-1: Turn on private vulnerability reporting

*Level 1*

Settings → Advanced Security → Private vulnerability reporting → Enable. People then get a "Report a vulnerability" button on your Security and quality tab, and their report reaches you privately. You can ask questions, reject it, or accept it as a draft advisory to work in.

> Already on through your organization's configuration.

### CI-1: Turn on CodeQL default setup

*Level 1 (or a security workflow) · Level marker*

Settings → Advanced Security → Code scanning → CodeQL analysis → Set up → Default. It picks up Python, JavaScript and TypeScript, and runs on every pull request. Check that GitHub Actions is in its list of languages too, because that's the language that scans your workflow files, and default setup doesn't always include it. If it's missing, choose View CodeQL configuration, then Edit, select GitHub Actions under Languages, and choose Save changes.

> Already on through your organization's configuration.

### CI-3: Turn on secret scanning and push protection

*Level 1*

Settings → Advanced Security. Push protection stops a push that contains a known token format before it reaches GitHub.

> Already on through your organization's configuration.

### CI-2: Turn on Dependabot alerts and security updates

*Level 1 · Level marker*

**Turn on Dependabot alerts and security updates** in the same Settings page, then add version updates for your package files and your workflow actions.

`.github/dependabot.yml`

```
version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
  - package-ecosystem: "npm"        # cards: package.json and its lockfile
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
```

Dependabot doesn't read an integration's `manifest.json`. The workflow below checks those requirements with pip-audit instead.

`cooldown` makes Dependabot wait until a release is 7 days old before proposing it. It only delays version updates; security updates still arrive straight away.

> Alerts and security updates are already on. Add the `dependabot.yml` file yourself, because the configuration doesn't set up version updates.

### DEP-4: Wait at least 7 days before taking a new release

*Level 1*

**Why:** Malicious versions are usually found and removed fast. npm removed the September 2025 phishing versions the same day, and TanStack's within about four and a half hours. With a 7-day cooldown, Dependabot only offers a release once it has been public for a week, so versions like these have been removed before it offers them ([how it happened](https://ha-barkley.github.io/security/attacks/#phishing)).

Set `cooldown: default-days: 7` in `dependabot.yml` (Dependabot waits 3 days if you set nothing), or `"minimumReleaseAge": "7 days"` in Renovate. Security updates aren't delayed.

> The `dependabot.yml` above already sets a 7-day cooldown.

## Add your workflows

Every workflow runs with a token, so the first five steps are about writing them safely. Then add the two workflows and check them.

### CI-7: Give workflows read-only tokens

*Level 1*

Set `permissions: contents: read` at the top of every workflow and widen it only in the job that needs more. Then make read-only the default under Settings → Actions → General → Workflow permissions, and untick *Allow GitHub Actions to create and approve pull requests*. Repositories created since 2023 start read-only, but older ones may still give every workflow write access.

### CI-8: Keep untrusted text out of `run:` lines

*Level 1*

An issue title, a pull request title or a branch name is chosen by whoever opens it. Written straight into a `run:` line with `${{ }}`, it runs as a shell command with your token. Pass it through `env:` instead, so the shell treats it as text.

`Do pass it as a variable`

```
- name: Log the new issue
  env:
    TITLE: ${{ github.event.issue.title }}
  run: echo "New issue: $TITLE"
```

`Don't write it into the command`

```
- name: Log the new issue
  run: echo "New issue: ${{ github.event.issue.title }}"
```

### CI-9: Never run a pull request's code in a `pull_request_target` workflow

*Level 1*

That trigger runs with your secrets and a token that can write, so checking out the pull request's code hands both to whoever opened it. Use `pull_request` for anything that builds or tests contributed code. `actions/checkout` v7 refuses this by default.

### CI-10: Pin actions to a full commit SHA

*Level 2 · Only for: My own account*

A tag like `@v7` can be moved to different code by whoever controls the action, and your next run uses it with your token. The examples here use version tags and branch names so they're easier to read. Dependabot keeps pinned SHAs current when an action publishes new releases.

Some Home Assistant actions are updated on a branch instead. `hacs/action` hasn't tagged a release since 2022, and hassfest only started tagging in November 2026. Pin these to a commit SHA from their default branch, not to the old release, and check them for new commits every month or so.

### CI-10: Pin actions to a full commit SHA

*Level 2 · Only for: An organization with a security configuration*

A tag like `@v7` can be moved to different code by whoever controls the action, and your next run uses it with your token. The examples here use version tags and branch names so they're easier to read. Dependabot keeps pinned SHAs current when an action publishes new releases.

Some Home Assistant actions are updated on a branch instead. `hacs/action` hasn't tagged a release since 2022, and hassfest only started tagging in November 2026. Pin these to a commit SHA from their default branch, not to the old release, and check them for new commits every month or so.

> If your organization requires pinned actions, a workflow that uses a tag such as `@v7` fails, so pin the workflows below before you commit them.

### CI-11: Don't leave the token behind after checkout

*Level 2*

`actions/checkout` saves the token so later `git` commands work, which also hands it to every later step. Turn that off unless a later step pushes.

`.github/workflows/security.yaml (part)`

```
- uses: actions/checkout@v7
  with:
    persist-credentials: false
```

### CI-4: Add a security workflow

*Level 1 (or CodeQL) · Level marker · Only for: An integration or A dashboard card*

**Add a security workflow** that runs on pull requests and on main. This one is for an integration; for a card, swap pip-audit for `npm audit --omit=dev`.

`.github/workflows/security.yaml`

```
name: Security
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  dependency-review:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/dependency-review-action@v5
        with:
          fail-on-severity: moderate
  pip-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - run: pip install pip-audit==2.10.1
      - name: Check the integration's requirements
        run: |
          jq -r '.requirements // [] | .[]' custom_components/your_domain/manifest.json > requirements.txt
          if [ -s requirements.txt ]; then pip-audit -r requirements.txt; fi
  ruff-security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/ruff-action@v4.1.0
        with:
          args: check --select S
```

ruff-action has no `v4` tag, only exact versions such as `v4.1.0`, so it's pinned to one here.

pip-audit sometimes reports a vulnerability that has no fixed version yet, so there's nothing to upgrade to and the job keeps failing. Check whether it affects how your integration uses the library. If it doesn't, skip that one finding with `--ignore-vuln ID` and a comment saying why. An unpinned requirement resolves to its newest version on every run, so the result can change without a commit. [Dependencies](https://ha-barkley.github.io/security/controls/dependencies/) covers pinning.

### CI-4: Add a security workflow

*Level 1 (or CodeQL) · Level marker · Only for: An app (add-on)*

**Add a security workflow** that runs on pull requests and on main. This one is for an integration; for a card, swap pip-audit for `npm audit --omit=dev`.

`.github/workflows/security.yaml`

```
name: Security
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  dependency-review:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/dependency-review-action@v5
        with:
          fail-on-severity: moderate
  pip-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - run: pip install pip-audit==2.10.1
      - name: Check the integration's requirements
        run: |
          jq -r '.requirements // [] | .[]' custom_components/your_domain/manifest.json > requirements.txt
          if [ -s requirements.txt ]; then pip-audit -r requirements.txt; fi
  ruff-security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/ruff-action@v4.1.0
        with:
          args: check --select S
```

ruff-action has no `v4` tag, only exact versions such as `v4.1.0`, so it's pinned to one here.

pip-audit sometimes reports a vulnerability that has no fixed version yet, so there's nothing to upgrade to and the job keeps failing. Check whether it affects how your integration uses the library. If it doesn't, skip that one finding with `--ignore-vuln ID` and a comment saying why. An unpinned requirement resolves to its newest version on every run, so the result can change without a commit. [Dependencies](https://ha-barkley.github.io/security/controls/dependencies/) covers pinning.

> For an app, keep the dependency review job, and point the audit job at the app's own `requirements.txt` or `package.json`, if it has one. `manifest.json` is an integration's file.

### DEP-5: Check for known vulnerabilities in CI

*Level 1*

**Why:** Most vulnerable code in an app is an old version of a library that already has a fix. A check in CI tells you when a package you use gets an advisory, before a user reports it.

Use pip-audit or npm audit (see [Checks in CI](https://ha-barkley.github.io/security/controls/ci/)).

> The security workflow above does this.

### CI-5: Validate against Home Assistant's own rules

*Level 1 · Applies to integrations and cards · Only for: An integration or A dashboard card*

**Validate against Home Assistant's own rules** with hassfest and the Marketplace's validation action.

`.github/workflows/validate.yaml`

```
name: Validate
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  hassfest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: home-assistant/actions/hassfest@master
  marketplace:
    runs-on: ubuntu-latest
    steps:
      - uses: hacs/action@main
        with:
          category: integration
```

For a card, leave out the hassfest job, which only checks integrations, and set `category: plugin`, the Marketplace's name for dashboard cards.

### CI-5: Validate against Home Assistant's own rules

*Level 1 · Applies to integrations and cards · Only for: An app (add-on)*

**Validate against Home Assistant's own rules** with hassfest and the Marketplace's validation action.

`.github/workflows/validate.yaml`

```
name: Validate
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  hassfest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: home-assistant/actions/hassfest@master
  marketplace:
    runs-on: ubuntu-latest
    steps:
      - uses: hacs/action@main
        with:
          category: integration
```

For a card, leave out the hassfest job, which only checks integrations, and set `category: plugin`, the Marketplace's name for dashboard cards.

> For an app, leave out both jobs. hassfest only checks integrations, and the Marketplace action only checks integrations and cards. `frenck/action-addon-linter` checks an app's `config.yaml` instead.

### CI-13: Check your workflows with zizmor

*Level 2*

It finds the problems above, such as untrusted text in `run:` lines, broad tokens, unpinned actions and credentials left behind. Run `uvx zizmor .github/workflows/` before you push, or add it to your security workflow.

### CI-12: Use a GitHub App token instead of a personal access token

*Level 2*

When the built-in token can't do something, such as triggering another workflow, create a GitHub App with only the permissions it needs and install it on the repositories that need it. `actions/create-github-app-token` turns it into a token that expires after an hour. The app's private key is still a stored secret, but each token reaches only what you picked, and nothing is tied to your own account.

## Write the integration safely

*Only for: An integration*

Each of these closes a way an integration can leak a login or run code it shouldn't.

### INT-1: Never fetch code at run time

*Level 1 · Applies to integrations*

Don't run `pip install` from inside the integration, and don't download a script and run it. List packages in `manifest.json` with exact versions, and Home Assistant installs them.

`manifest.json (part)`

```
"requirements": ["examplelib==2.4.1"]
```

### INT-2: Keep the login on every page you add

*Level 1 · Applies to integrations*

`HomeAssistantView` requires a login unless you turn it off. Only turn it off when the situation calls for it and none of these safer options fits:

- For calls from a device or a cloud service, use a webhook. It uses an id nobody can guess and can be limited to the local network.
- For a link to something that can't log in, like a speaker playing a sound or an image in a notification, use a signed path from `async_sign_path`. The page keeps its login check, and the link expires.
- For signing in to a cloud account, use Home Assistant's OAuth2 config flow helper (`config_entry_oauth2_flow`), which provides the redirect page for you.
- For your card's or panel's JavaScript, use `hass.http.async_register_static_paths`. These files load without a login by design, so put code in them and keep data out.

`Do webhook for inbound calls`

```
from homeassistant.components import webhook

webhook.async_register(
    hass, DOMAIN, "Example device",
    entry.data[CONF_WEBHOOK_ID], handle_webhook,
    local_only=True,
)
```

`Don't a page with the login turned off for no reason`

```
class StatusView(HomeAssistantView):
    url = "/api/example/status"
    name = "api:example:status"
    requires_auth = False   # anyone on the network
```

If you do turn the login off, return nothing sensitive from that page, and check any token or signature yourself in the handler. Create a webhook id in the config flow with `webhook.async_generate_id()`.

### INT-3: Save settings and state with the storage helper, and never with pickle

*Level 1 · Applies to integrations*

The helper writes JSON safely, versions it, and keeps it where backups find it. Loading a pickle file runs any code inside it, so anything that can write that file can run code in Home Assistant.

For other kinds of data: large or binary files (images, firmware, models) go in plain files in your own folder, many records you query go in SQLite, and history belongs in entities, which the recorder already keeps.

`__init__.py`

```
from homeassistant.helpers.storage import Store

store = Store(hass, 1, f"{DOMAIN}.cache")
data = await store.async_load() or {}
await store.async_save(data)
```

### INT-4: Use Home Assistant's shared web session

*Level 1 · Applies to integrations*

**Use Home Assistant's shared web session** with certificate checks on. Only offer "don't verify SSL" for local devices with self-signed certificates, and default it to off.

`coordinator.py`

```
from homeassistant.helpers.aiohttp_client import async_get_clientsession

session = async_get_clientsession(hass)
```

### INT-5: Avoid the calls that turn data into code

*Level 1 · Applies to integrations*

`pickle.load`, `eval`, `exec`, `yaml.load` without a safe loader, and `subprocess` with `shell=True`.

### INT-6: Send each credential only to its own service

*Level 1 · Applies to integrations*

A Supervisor token goes to the Supervisor, a user's cloud token goes to that cloud, and nothing goes to your own server unless the README says so.

### SEC-1: Ask users for credentials in the config flow

*Level 1 · Applies to integrations*

**Ask users for credentials in the config flow,** with a password field, and read them from the config entry. Don't hard-code your own account's keys into the app.

`config_flow.py`

```
from homeassistant.helpers.selector import (
    TextSelector, TextSelectorConfig, TextSelectorType,
)

STEP_USER = vol.Schema({
    vol.Required(CONF_USERNAME): str,
    vol.Required(CONF_PASSWORD): TextSelector(
        TextSelectorConfig(type=TextSelectorType.PASSWORD)
    ),
})
```

### SEC-2: Redact diagnostics and keep secrets out of logs

*Level 1 · Applies to integrations*

Users paste diagnostics into public issues.

`diagnostics.py`

```
from homeassistant.components.diagnostics import async_redact_data

TO_REDACT = {CONF_PASSWORD, CONF_API_KEY, CONF_TOKEN, "serial_number"}

async def async_get_config_entry_diagnostics(hass, entry):
    return {"entry": async_redact_data(entry.as_dict(), TO_REDACT)}
```

## Write the card safely

*Only for: A dashboard card*

A card runs in the user's browser, logged in to their Home Assistant.

### CARD-1: Bundle your libraries into the card

*Level 1 · Applies to cards*

**Bundle your libraries into the card** at build time instead of loading them from a CDN when the card runs.

`Do bundled at build time`

```
import { formatDistance } from "date-fns";
```

`Don't loaded at run time`

```
const lib = await import(
  "https://cdn.example.com/lib@latest/index.js"
);
```

### CARD-2: Keep the login token where it is

*Level 1 · Applies to cards*

Talk to Home Assistant through the card's own connection. For an outside service, put the call in an integration and have the card ask the integration.

`Do the card's own connection`

```
const states = await this.hass.callWS({
  type: "get_states",
});
```

`Don't send the token anywhere`

```
fetch(url, { headers: {
  Authorization: `Bearer ${this.hass.auth.data.access_token}`,
}});
```

### CARD-3: Render with Lit templates, not innerHTML

*Level 1 · Applies to cards*

Entity names and attributes come from devices and other apps. Lit escapes them. `innerHTML` turns them into live HTML, and an attribute such as `onerror` can run script with the user's login.

### CARD-4: Keep build tools current

*Level 2 · Applies to cards*

**Keep build tools current,** commit the lockfile, and build with `npm ci`. Dependabot's npm updates cover development packages too.

## Write the app safely

*Only for: An app (add-on)*

Home Assistant shows users a security rating built from your app's config file. Ask for as little as the app needs from the first version, because taking access away later can break setups that rely on it.

### APP-1: Ask only for the access the app uses

*Level 1 · Applies to apps*

Leave out `privileged`, `full_access`, `host_network`, `host_pid` and `docker_api` unless the app can't work without them, and say why in the README when it does.

`config.yaml`

```
name: Example
version: "1.0.0"
slug: example
arch: [aarch64, amd64]
ingress: true
ingress_port: 8099
homeassistant_api: true   # only if the app calls Home Assistant's API
# Leave these out unless the app can't work without them:
# privileged, full_access, host_network, host_pid, docker_api
```

### APP-2: Use ingress instead of open ports

*Level 1 · Applies to apps*

Ingress puts the app's web page behind Home Assistant's login. An open port is reachable by anything on the network.

### APP-3: Keep AppArmor on

*Level 2 · Applies to apps*

**Keep AppArmor on** and ship a profile that allows only what the app does.

### APP-4: Build on Home Assistant's base images

*Level 2 · Applies to apps*

**Build on Home Assistant's base images,** pin their versions, rebuild when they update, and don't run as root inside the container when you don't need to.

## Choose dependencies carefully

Every package you add runs with the same access as your own code.

### DEP-1: Use what Home Assistant already ships first

*Level 1 · Applies to integrations · Only for: An integration*

**Why:** Each package you add is code from more people you have to trust, and one more account that can be taken over. Home Assistant already ships and updates the common ones, so using them doesn't add anyone new for your users to trust.

aiohttp, voluptuous and many device libraries are already installed. Don't list those in `requirements`. Home Assistant's own version wins, and a different pin can stop your integration from installing.

### DEP-2: Check a package before you add it

*Level 1*

**Why:** Some packages are published under a name one letter away from a popular one, so that a typo installs them. Others change hands without anyone noticing. In 2018, someone posing as a maintainer took over event-stream and added code aimed at one bitcoin wallet app ([how it happened](https://ha-barkley.github.io/security/attacks/#event-stream)).

Look for a release in the last year, more than one maintainer, a linked source repository, and the exact spelling of the name.

### DEP-3: Pin exact versions

*Level 1*

**Why:** With a range such as `>=2.0`, every new install takes whatever was published last, including a version published from a stolen account an hour ago. With an exact pin, a new version only reaches your users after you merge a pull request for it ([phished logins](https://ha-barkley.github.io/security/attacks/#phishing), [Shai-Hulud](https://ha-barkley.github.io/security/attacks/#shai-hulud)).

Use `==` in `manifest.json`, and commit the lockfile for a card. Dependabot proposes updates for a card's lockfile. For `manifest.json`, Renovate can do it with a custom manager, or pip-audit in CI tells you when a pinned version has a known vulnerability.

## Protect main

Do this after your workflows have run at least once. A check only shows up in the ruleset's list after it has run.

### BR-1: Add a branch ruleset for main

*Level 2 · Level marker*

Settings → Rules → Rulesets → New branch ruleset.

- Enforcement: *Active*.
- Target: the default branch.
- Turn on *Restrict deletions*.
- Turn on *Block force pushes*.
- Turn on *Require a pull request before merging*. Zero required approvals is fine if you work alone, because the pull request still runs your checks before anything lands.

### GATE-1: For CodeQL, require code scanning results

*Level 2 (or a required check) · Level marker*

In your main branch ruleset, turn on *Require code scanning results*, add CodeQL, and set it to block on security alerts of "High or higher". Requiring "Analyze (python)" only proves the scan ran.

### GATE-2: Require your other checks by job name

*Level 2 (or code scanning) · Level marker*

*Require status checks to pass* → add `dependency-review`, `pip-audit`, `ruff-security`, `hassfest` and `marketplace` from the workflows in [Checks in CI](https://ha-barkley.github.io/security/controls/ci/). A check only shows up in the list after it has run once.

### GATE-3: Make sure each check can fail

*Level 2 · Level marker*

Remove `continue-on-error: true`, `|| true` and `--exit-zero` from security steps. Some tools report without failing unless you ask them to. Trivy, for example, needs `exit-code: 1`.

### BR-3: Keep the bypass list short

*Level 2*

If you add yourself so you can merge in an emergency, every bypass is logged. Don't add bots or apps you don't control.

### GATE-4: Work through pull requests, even alone

*Level 2 · Level marker*

Push to a branch, open a pull request and merge it when the checks are green. It takes a minute longer and it's the only way the required checks see your code first.

## Set up releases before the first one

Protect your tags and turn on immutable releases first, because both only apply from then on. Then add the release workflow and publish.

### BR-4: Add a tag ruleset for your release tags

*Level 3 (or immutable releases) · Level marker*

Settings → Rules → Rulesets → New tag ruleset.

- Enforcement: *Active*. A disabled ruleset protects nothing.
- Target: `v*`, or however you name versions.
- Turn on *Restrict updates* and *Restrict deletions*, so a published version can't be moved to different code later.
- Turn on *Restrict creations* if only you should cut releases. Then add the Repository admin role to the bypass list, or you won't be able to push new tags either.

### REL-3: Turn on immutable releases

*Level 3 (or a tag ruleset) · Level marker*

**Turn on immutable releases** (Settings → General → Releases), so a published release's files and tag can't be swapped later. It applies to releases you publish after turning it on. Because assets can't be added after publishing, the workflow above creates the release and its file together.

### REL-1: Build and publish releases from a workflow

*Level 3 · Level marker · Only for: An integration or A dashboard card*

**Build and publish releases from a workflow** instead of your laptop. This one zips an integration, refuses a tag that isn't on main, adds a provenance attestation, and publishes the release with the zip in one step.

`.github/workflows/release.yaml`

```
name: Release
on:
  push:
    tags: ["v*"]
permissions:
  contents: write
  id-token: write
  attestations: write
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - name: Only release code that's on main
        run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main
      - name: Zip the integration
        run: |
          cd custom_components/your_domain
          zip -r "$GITHUB_WORKSPACE/your_domain.zip" .
      - uses: actions/attest-build-provenance@v4
        with:
          subject-path: your_domain.zip
      - name: Publish the release
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh release create "$GITHUB_REF_NAME" your_domain.zip --verify-tag --generate-notes
```

Tell the Marketplace to install the zip with `"zip_release": true` and `"filename": "your_domain.zip"` in `hacs.json`. For a card, build the bundle in the workflow and attach the built file instead.

The "Only release code that's on main" step catches a tag pushed from the wrong branch by mistake. It can't stop someone with write access. The workflow that runs is the one in the tagged commit, so they could tag a commit whose workflow leaves that step out. A tag ruleset with *Restrict creations* stops that, because only the people on its bypass list can create release tags (see [Branch and tag protection](https://ha-barkley.github.io/security/controls/branches-and-tags/)).

### REL-1: Build and publish releases from a workflow

*Level 3 · Level marker · Only for: An app (add-on)*

**Build and publish releases from a workflow** instead of your laptop. This one zips an integration, refuses a tag that isn't on main, adds a provenance attestation, and publishes the release with the zip in one step.

`.github/workflows/release.yaml`

```
name: Release
on:
  push:
    tags: ["v*"]
permissions:
  contents: write
  id-token: write
  attestations: write
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - name: Only release code that's on main
        run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main
      - name: Zip the integration
        run: |
          cd custom_components/your_domain
          zip -r "$GITHUB_WORKSPACE/your_domain.zip" .
      - uses: actions/attest-build-provenance@v4
        with:
          subject-path: your_domain.zip
      - name: Publish the release
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh release create "$GITHUB_REF_NAME" your_domain.zip --verify-tag --generate-notes
```

Tell the Marketplace to install the zip with `"zip_release": true` and `"filename": "your_domain.zip"` in `hacs.json`. For a card, build the bundle in the workflow and attach the built file instead.

The "Only release code that's on main" step catches a tag pushed from the wrong branch by mistake. It can't stop someone with write access. The workflow that runs is the one in the tagged commit, so they could tag a commit whose workflow leaves that step out. A tag ruleset with *Restrict creations* stops that, because only the people on its bypass list can create release tags (see [Branch and tag protection](https://ha-barkley.github.io/security/controls/branches-and-tags/)).

> For an app, the release is its container image. Build and push the image in this workflow and name it as `image` in `config.yaml`. Without `image`, each user's Home Assistant builds the Dockerfile itself, and nothing ties what they run to your workflow.

### REL-4: Don't commit build output you also release

*Level 3 · Only for: A dashboard card*

If a card's `dist/` is in the repository, make the release workflow fail when a fresh build doesn't match it.

### REL-2: Keep publishing secrets in a release environment

*Level 3*

If the release needs a secret, for example to push an image or publish a package, create an environment under Settings → Environments. Under Deployment branches and tags, allow only your release tags, add the secret to the environment instead of the repository, and add `environment: release` to the release job. A job started from any other branch or tag can't read it. With the tag ruleset above, only you can start one that can. Trusted publishing, where the registry supports it, needs no secret at all.

### SEC-4: In CI, prefer no secret at all

*Level 2*

Use the built-in `GITHUB_TOKEN` with the narrowest permissions, and trusted publishing (OpenID Connect) to publish to PyPI or npm instead of a long-lived token.

### Publish your first release from a tag on main

*Level 3*

Run `git tag -s v1.0.0 -m "v1.0.0"` and `git push origin v1.0.0`. When the workflow has finished, download the release's file and check it with `gh attestation verify`, as [Releases](https://ha-barkley.github.io/security/controls/releases/) shows.

## Tell people what to expect

Before you list it in the Marketplace.

### REPO-5: List the servers your app talks to

*Level 1*

**List the servers your app talks to** in the README, and what it sends to each. Users can't see that from the dashboard.

### ACC-6: Give the project a second maintainer, or at least a plan

*Level 2*

**Why:** When one person can publish, nobody notices an odd release from that account, and nobody can step in if that person loses access or moves on. If its maintainer leaves without a plan, a project can pass to whoever asks for it. In 2018, someone posing as a maintainer took over the event-stream package on npm and added code that stole from bitcoin wallets ([how it happened](https://ha-barkley.github.io/security/attacks/#event-stream)).

A free GitHub organization lets several people share a project and can require two-factor login for all of them. [Organizations](https://ha-barkley.github.io/security/controls/organizations/) covers when it's worth it. If you're on your own, write down in the README who can take over.

## Once people use it

These come up later, when reports, issues and old packages arrive.

### POL-4: When a report comes in

*Level 1*

**When a report comes in,** fix it in the advisory's private fork, release the fix, then publish the advisory. You can request a CVE from the advisory. If your code is also published as a package on PyPI or npm, Dependabot then alerts the projects that depend on it.

### REPO-4: Close issues with the fix

*Level 2*

Write `Fixes #123` in the pull request, and GitHub closes the issue when it merges. Close stale questions with a short note rather than leaving them open.

### DEP-6: Replace dead packages

*Level 2*

**Why:** A package nobody maintains gets no security fixes, and nobody is watching when it changes hands.

If a library hasn't had a release in years and has open security reports, switch to a maintained one or take over a fork in the open.

## Next

Check where you stand on the [checklist](https://ha-barkley.github.io/security/checklist/?level=3). It lists every step, including the few this walk-through leaves out.
