PHPackages                             spaze/security-txt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. spaze/security-txt

ActiveLibrary[Security](/categories/security)

spaze/security-txt
==================

security.txt (RFC 9116) generator, parser, validator

v2.0.0(2mo ago)87.0k↓15.7%MITPHPPHP ^8.5CI passing

Since Apr 6Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/spaze/security-txt)[ Packagist](https://packagist.org/packages/spaze/security-txt)[ RSS](/packages/spaze-security-txt/feed)WikiDiscussions main Synced yesterday

READMEChangelog (2)Dependencies (10)Versions (7)Used By (0)

`security.txt` (RFC 9116) generator, parser, validator
======================================================

[](#securitytxt-rfc-9116-generator-parser-validator)

This package is a PHP library that can generate, parse, and validate `security.txt` files. It comes with an executable script that you can use from the command line, in a CI test, or in a pipeline (for example, in GitHub Actions).

The `security.txt` document represents a text file that's both human-readable and machine-parsable to help organizations describe their vulnerability disclosure practices to make it easier for researchers to report vulnerabilities. The format was created by EdOverflow and Yakov Shafranovich and is specified in [RFC 9116](https://www.rfc-editor.org/rfc/rfc9116). You can find more about `security.txt` at [securitytxt.org](https://securitytxt.org/).

I have also written a blogpost about `security.txt` and how it may be helpful when reporting vulnerabilities:

- [What's `security.txt` and why you should have one](https://www.michalspacek.com/what-is-security.txt-and-why-you-should-have-one) in English
- [K čemu je soubor `security.txt`](https://www.michalspacek.cz/k-cemu-je-soubor-security.txt) in Czech

Installation
============

[](#installation)

Install the package with Composer:

```
composer require spaze/security-txt

```

Requirements and supported versions
===================================

[](#requirements-and-supported-versions)

VersionRequirementsNotes2.xPHP 8.5
+ optional curl extension to fetch from remote hosts
+ optional gnupg extension to verify signaturesCurrent stable release1.xPHP 8.3, 8.4, 8.5
+ optional curl extension to fetch from remote hosts
+ optional gnupg extension to verify signaturesSecurity fixes onlyAs a validator
==============

[](#as-a-validator)

How does the validation work
----------------------------

[](#how-does-the-validation-work)

This package can validate `security.txt` file either by providing

- the file contents as a string by calling `Spaze\SecurityTxt\Parser\SecurityTxtParser::parseString()`
- a fetch result object of class `Spaze\SecurityTxt\Fetcher\SecurityTxtFetchResult` into `Spaze\SecurityTxt\Parser\SecurityTxtParser::parseFetchResult()`
    - the result object would possibly be stored or cached, or sent from a serverless service like AWS Lambda doing the fetch
- a `Uri\WhatWg\Url` object to `Spaze\SecurityTxt\Check\SecurityTxtCheckHost::check()`
    - you can create the object with e.g. `new Uri\WhatWg\Url('https://example.com/')`
    - only the host part (`example.com` in this case) and the port, if specified, will be used, the scheme, path etc. will be ignored
    - `Uri\WhatWg\Url` is from the `Uri` extension, which is always available starting with PHP 8.5

Each of the options above will call preceding method and add more validations which are only possible in that particular case.

There's also a command line script in `bin` which uses `Spaze\SecurityTxt\Check\SecurityTxtCheckHostCli::check()` mostly just to add command line output to `Spaze\SecurityTxt\Check\SecurityTxtCheckHost::check()`, see "Command line usage" below.

How to use the validator
------------------------

[](#how-to-use-the-validator)

`Spaze\SecurityTxt\Check\SecurityTxtCheckHost::check()` is probably what you'd want to use as it provides the most comprehensive checks, can pass a URL, not just a hostname, and also supports callbacks. It accepts these parameters:

`Uri\WhatWg\Url $url`

A URL where the file will be looked for, you can pass just `https://example.com`, no need to use the full path to the `security.txt` file as only the hostname and port, if specified, of the URL will be used for further checks

`?int $expiresWarningThreshold = null`

The validator will start throwing warnings if the file expires soon, and you can say what "soon" means by specifying the number of days here

`bool $strictMode = false`

If you enable strict mode, then the file will be considered invalid, meaning `SecurityTxtCheckHostResult::isValid()` will return `false` even when there are only warnings, with strict mode disabled, the file with only warnings would still be valid and `SecurityTxtCheckHostResult::isValid()` would return `true`

`bool $requireTopLevelLocation = false`

When specified, the top-level `/security.txt` location must also exist (or be redirected) in addition to `/.well-known/security.txt`, otherwise a warning will be issued

`bool $noIpv6 = false`

Because some environments do not support IPv6, looking at you GitHub Actions

`?int $maxAllowedRedirects = null`

Maximum number of redirects to follow when fetching `security.txt`. Set to `0` to disable redirects, `null` to use the default (`5`).

`Spaze\SecurityTxt\Check\SecurityTxtCheckHost::check()` returns a `Spaze\SecurityTxt\Check\SecurityTxtCheckHostResult` object with some obvious and less obvious properties. The less obvious ones can be obtained with the following methods. All of them return an array of `SecurityTxtSpecViolation` descendants.

### `getFetchErrors()`

[](#getfetcherrors)

Returns `list` and contains errors encountered when fetching the file from a server. For example but not limited to:

- When the content type or charset is wrong
- When the URL scheme is not HTTPS

### `getFetchWarnings()`

[](#getfetchwarnings)

Also returns `list` and has warnings when fetching the file, like for example but not limited to:

- When the files at `/security.txt` and `/.well-known/security.txt` differ
- When `/security.txt` does not redirect to `/.well-known/security.txt`

### `getLineErrors()`

[](#getlineerrors)

Returns `array` where the array `int` key is the line number. Contains errors discovered when parsing and validating the contents of the `security.txt` file. These errors are produced by any class that implements the `FieldProcessor` interface. The errors include but are not limited to:

- When a field uses incorrect separators
- When a field value is not URL or the URL doesn't use `https://` scheme

### `getLineWarnings()`

[](#getlinewarnings)

Also returns `array` where the array `int` key is the line number. Contains warnings generated by any class that implements the `FieldProcessor` interface, when parsing and validating the contents of the `security.txt` file. These warnings include but are not limited to:

- When the `Expires` field's value is too far into the future

### `getFileErrors()`

[](#getfileerrors)

Returns `list`, the list contains file-level errors which cannot be paired with any single line. These error are generated by `FieldValidator` child classes, and include:

- When mandatory fields like `Contact` or `Expires` are missing

### `getFileWarnings()`

[](#getfilewarnings)

Returns `list`, the list contains file-level warnings that cannot be paired with any single line. These warnings are generated by `FieldValidator` child classes, and include for example:

- When the file is signed, but there's no `Canonical` field

Callbacks
---------

[](#callbacks)

`SecurityTxtCheckHost::check()` supports callbacks that can be set with `SecurityTxtCheckHost::addOn*()` methods. You can use them to get the parsing information in "real time", and are used for example by the `bin/checksecuritytxt.php` script via the `\Spaze\SecurityTxt\Check\SecurityTxtCheckHostCli` class to print information as soon as it is available.

User agent
----------

[](#user-agent)

When fetching the `security.txt` file, the library uses a default `User-Agent` HTTP header. The default value contains a link back to the GitHub repository, but it is recommended you use a custom `User-Agent` header. You can set it in `SecurityTxtFetcherCurlClient` constructor (the `$userAgent` parameter), and then pass the client object to `SecurityTxtFetcher` constructor as one of its arguments.

Maximum file size
-----------------

[](#maximum-file-size)

The size of the file is limited when fetching the contents from remote hosts. By default, the limit is 10 000 bytes, but you can change it in `SecurityTxtFetcherCurlClient` constructor (the `$maxResponseLength` parameter). Then, when creating `SecurityTxtFetcher`, pass that customized client as its HTTP client argument together with the other constructor arguments required by `SecurityTxtFetcher`.

DNS lookups
-----------

[](#dns-lookups)

DNS resolution is handled by `SecurityTxtPhpDnsProvider`, which uses PHP's built-in `dns_get_record()`. This function has no timeout parameter, the system DNS timeout applies. If you need explicit DNS timeout control, or would like to use for example DNS-over-HTTPS, you can add a custom provider, which implements the `SecurityTxtDnsProvider` interface, and then pass it to `SecurityTxtFetcher` in the `$dnsLookupProvider` parameter.

Signature verification
----------------------

[](#signature-verification)

This library verifies that the signature is a valid OpenPGP cleartext signature, but cannot verify whether the signing key is trustworthy, for example when the key is not in local keyring etc. As the [`security.txt` RFC](https://www.rfc-editor.org/rfc/rfc9116#name-digital-signature) puts it: "it is always the security researcher's responsibility to make sure the key being used is indeed one they trust." Verify the key fingerprint or key id out-of-band, for example by checking it against the company's website or other trusted sources.

JSON
----

[](#json)

The `Spaze\SecurityTxt\Check\SecurityTxtCheckHostResult` object can be encoded to JSON with `json_encode()`, and decoded back with `Spaze\SecurityTxt\Json\SecurityTxtJson::createCheckHostResultFromJsonValues()`.

The primary use case for JSON-encoded objects is a result cache. But JSON can also be used when you want to fetch `security.txt` using serverless services like AWS Lambda, and then process the fetch result yourself.

If that's the case, then you may want to encode the `Spaze\SecurityTxt\Fetcher\SecurityTxtFetchResult` object created by `Spaze\SecurityTxt\Fetcher\SecurityTxtFetcher::fetch()`. `Spaze\SecurityTxt\Json\SecurityTxtJson::createFetchResultFromJsonValues()` then decodes it back from JSON.

Fetch exceptions can be recreated with `Spaze\SecurityTxt\Json\SecurityTxtJson::createFetcherExceptionFromJsonValues()`.

JSON is not versioned. Newer versions of this library will make a best effort to decode JSON created by previous versions, but compatibility cannot be guaranteed across refactors or format changes.

The other methods
-----------------

[](#the-other-methods)

The `Spaze\SecurityTxt\Parser\SecurityTxtParser::parseString()` method returns a `Spaze\SecurityTxt\Parser\SecurityTxtParseStringResult` object. `Spaze\SecurityTxt\Parser\SecurityTxtParser::parseFetchResult()` returns a `Spaze\SecurityTxt\Parser\SecurityTxtParseHostResult` object, which also contains a `Spaze\SecurityTxt\Fetcher\SecurityTxtFetchResult` object. All the result objects have similar methods as what's described above for `SecurityTxtCheckHostResult`.

As a writer
===========

[](#as-a-writer)

You can create a `security.txt` file programmatically:

1. Create a `SecurityTxt` object
2. Add what's needed
3. Pass it to `SecurityTxtWriter::write()` it will return the `security.txt` contents as a string

See below if you want to add an OpenPGP signature.

Value validation
----------------

[](#value-validation)

By default, values are validated when set, and an exception is thrown when they're invalid. You can set validation level in the `SecurityTxt` constructor using the `SecurityTxtValidationLevel` enum:

- `NoInvalidValues` (an exception will be thrown, and the value won't be set, this is the default setting)
- `AllowInvalidValues` (an exception will be thrown but the value will still be set)
- `AllowInvalidValuesSilently` (an exception will not be thrown, and the value will be set)

Content type
------------

[](#content-type)

You can use the following `SecurityTxtContentType` constants to serve the file with correct HTTP content type:

- `SecurityTxtContentType::MEDIA_TYPE`, the value to be sent as `Content-Type` header value (`text/plain; charset=utf-8`);
- `SecurityTxtContentType::CONTENT_TYPE`, the correct content type `text/plain`
- `SecurityTxtContentType::CHARSET`, the charset `utf-8`
- `SecurityTxtContentType::CHARSET_PARAMETER`, the correct charset parameter name and value as `charset=utf-8`

Example
-------

[](#example)

```
$securityTxt = new SecurityTxt();
$securityTxt->addContact(new SecurityTxtContact('https://contact.example'));
$securityTxt->addContact(SecurityTxtContact::phone('123456'));
$securityTxt->addContact(SecurityTxtContact::email('email@com.example'));
$securityTxt->addAcknowledgments(new SecurityTxtAcknowledgments('https://ack1.example'));
$securityTxt->setExpires(new SecurityTxtExpiresFactory()->create(new DateTimeImmutable('+3 months midnight')));
$securityTxt->addAcknowledgments(new SecurityTxtAcknowledgments('ftp://ack2.example'));
$securityTxt->setPreferredLanguages(new SecurityTxtPreferredLanguages(['en', 'cs-CZ']));
header('Content-Type: ' . SecurityTxtContentType::MEDIA_TYPE);
echo new SecurityTxtWriter()->write($securityTxt);
```

Signing the file
----------------

[](#signing-the-file)

One option to sign the file using an OpenPGP cleartext signature as per the `security.txt` [specification](https://www.rfc-editor.org/rfc/rfc9116#name-digital-signature) is to pre-sign the `security.txt` file using the `gpg` command line utility and store the result as a static file in your repository. I'd recommend creating the signatures that way as it doesn't expose your private keys to the web server and the web app. Allowing the app and the server to access your private keys brings a handful of new security problems to solve, which some of them are mentioned below.

Creating a new signing key is beyond the scope of this document, but you can refer to sources like [the GitHub Docs](https://docs.github.com/en/authentication/managing-commit-signature-verification/generating-a-new-gpg-key). Related challenges like key distribution, secure storage, and expiration, while interesting to address properly, are also not covered here.

Having said that, this library also allows you to create the signature programmatically by calling `Spaze\SecurityTxt\Signature\SecurityTxtSignature::sign()` (requires the `gnupg` PHP extension):

```
$gnuPgProvider = new SecurityTxtSignatureGnuPgProvider();
$signature = new SecurityTxtSignature($gnuPgProvider);
$securityTxt = new SecurityTxt();
// $securityTxt->addContact(...) etc.
$writer = new SecurityTxtWriter();
$contents = $writer->write($securityTxt);
$signingKeyFingerprint = '...'; // Or anything that refers to a unique key (user id, key id, ...)
$keyPassphrase = '...'; // Don't commit the passphrase to Git, please don't
echo $signature->sign($contents, $signingKeyFingerprint, $keyPassphrase);
```

The `SecurityTxtSignature::sign()` method makes use of the keyring of the current user (which may be a web server user). This keyring is normally located in the `.gnupg` directory in the user's home dir. To specify a custom location, pass the path to the keyring in the `Spaze\SecurityTxt\Signature\Providers\SecurityTxtSignatureGnuPgProvider` constructor, for example:

```
$gnuPgProvider = new SecurityTxtSignatureGnuPgProvider('/home/www');
```

If you wish, you can instead store the path to the keyring in the environment variable `GNUPGHOME`. Make sure the keyring is not publicly accessible, do not store keyring in `public_html` or similar directories. Also don't add the keyring to your Git repository.

If you're going to use a key for this library, I'd strongly recommend you create a key only to sign the file and do not use the key for anything else. You can then sign the key with your main key, if you want.

### Caching the signed file

[](#caching-the-signed-file)

If you're going to create the signature using this library, I don't recommend doing it on each request. Instead, you can cache the signed contents using for example the [Symfony Cache](https://symfony.com/doc/current/components/cache.html) component:

```
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\ItemInterface;

$cache = new FilesystemAdapter();
$cachedContents = $cache->get('securitytxt_file', function (ItemInterface $item) use ($securityTxt, $signature, $contents, $signingKeyFingerprint, $keyPassphrase): string {
    $item->expiresAt($securityTxt->getExpires()->getDateTime());
    return $signature->sign($contents, $signingKeyFingerprint, $keyPassphrase);
});

echo $cachedContents;
```

The following example uses the [Nette Cache](https://doc.nette.org/en/caching) library, the code is very similar to the example above:

```
use Nette\Caching\Cache;
use Nette\Caching\Storages\FileStorage;

$storage = new FileStorage('/tmp/cache');
$cache = new Cache($storage);
$cachedContents = $cache->load('securitytxt_file', function () use ($signature, $contents, $signingKeyFingerprint, $keyPassphrase): string {
    return $signature->sign($contents, $signingKeyFingerprint, $keyPassphrase);
}, [Cache::Expire => $securityTxt->getExpires()->getDateTime()]);

echo $cachedContents;
```

Command line usage
==================

[](#command-line-usage)

The `checksecuritytxt.php` script, located in the `bin` directory, prints progress and validation errors and warnings. It can be used from the command line or in automated tests.

Usage:

```
checksecuritytxt.php  [days] [--colors] [--strict] [--require-top-level-location] [--no-ipv6]
```

Parameters:

- `URL or hostname`: A URL, a hostname or a domain you want to check. If you provide just a hostname or a domain (e.g. `example.com`) then it cannot contain a port. If you provide a full URL (e.g., `https://example.com:4433/foo`), the script will extract and use only the hostname part and port if specified.
- `days`: If the file expires in less than *`days`* days, the script will print a warning.
- `--colors`: Enables colored output using red, green, and other colors for better readability.
- `--strict`: Upgrades all warnings to errors, enforcing stricter validation.
- `--require-top-level-location`: When specified, the `/security.txt` location must also exist or be redirected, otherwise a warning will be issued.
- `--no-ipv6`: Disables IPv6 usage. When this option is set, the script effectively ignores AAAA DNS records and uses only A records.

The script returns the following status codes:

- `0`: The file is valid.
- `1`: Returned if any of the following conditions are true:
    - The file has expired.
    - The file has errors.
    - The file has warnings when using `--strict`.
- `2`: No hostname or URL was passed.
- `3`: The file cannot be loaded.

CI Pipelines
============

[](#ci-pipelines)

If you'd like to check your `security.txt` file automatically using a CI (continuous integration) platform, such as GitHub Actions, you can use the command-line script described above. In general, you’ll need to follow these steps:

1. Install PHP if it is not already installed.
2. Install this package using Composer.
3. Run the `checksecuritytxt.php` script.

GitHub Actions' `ubuntu-24.04` runner (also as `ubuntu-latest` at the time of writing) has PHP 8.3 preinstalled, so you can use `checksecuritytxt.php` without installing anything else, the version 1.x of this lib can be used with PHP 8.3. Version 2.x requires PHP 8.5 or newer, and would require `ubuntu-26.04` which comes with PHP 8.5. You can also use [the `setup-php` GitHub action](https://github.com/marketplace/actions/setup-php-action) to install the required PHP version.

But unfortunately the `gnupg` PHP extension is not available on GitHub runners by default so you won't be able to verify the file signatures with just the GitHub-provided PHP. If you want to verify signatures you'll need to use [the `setup-php` GitHub action](https://github.com/marketplace/actions/setup-php-action) which can also set up the extension.

You can use my own checks as a template or for inspiration; see [the `securitytxt.yml` file](https://github.com/spaze/michalspacek.cz/blob/main/.github/workflows/securitytxt.yml) in my repository.

Exceptions
==========

[](#exceptions)

The messages in the exceptions as thrown by this library do not contain any sensitive information and are safe to display to the user using the `getMessage()` method. But please be aware that the messages contain server-supplied information, so please do not display the messages as HTML or do not feed them into a Markdown parser or similar. If you'd do that, a malicious server could inject content that would result in Cross-Site Scripting attack for example.

Formatting messages
-------------------

[](#formatting-messages)

If you'd like to format some of the values contained in the messages, you can use the exception's `getMessageFormat()` and `getMessageValues()` methods. The `getMessageFormat()` method will return an error message with `%s` placeholders, while `getMessageValues()` will return the values, including the server-supplied ones, which you can, **after a proper sanitization and/or escaping**, wrap in `` tags for example, and use them to replace the placeholders.

The same goes for formatting `SecurityTxtSpecViolation` object messages: you can use `getMessageFormat()` and `getMessageValues()`, and also `getHowToFixFormat()` and `getHowToFixValues()`.

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance89

Actively maintained with recent releases

Popularity28

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 99.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~9 days

Total

2

Last Release

78d ago

Major Versions

v1.0.0 → v2.0.02026-04-15

PHP version history (2 changes)v1.0.0PHP ^8.3

v2.0.0PHP ^8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/6777bd445610e6e458e4d41bdefa3070d2ed4e068323362353b061b15e9ff81b?d=identicon)[spaze](/maintainers/spaze)

---

Top Contributors

[![spaze](https://avatars.githubusercontent.com/u/1966648?v=4)](https://github.com/spaze "spaze (392 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")

---

Tags

generatorparsersecuritysecurity-txtsecuritytxtvalidator

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spaze-security-txt/health.svg)

```
[![Health](https://phpackages.com/badges/spaze-security-txt/health.svg)](https://phpackages.com/packages/spaze-security-txt)
```

###  Alternatives

[mews/purifier

Laravel 5/6/7/8/9/10 HtmlPurifier Package

2.0k18.7M143](/packages/mews-purifier)[paragonie/ecc

PHP Elliptic Curve Cryptography library

24820.0k37](/packages/paragonie-ecc)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
