PHPackages                             sonrac/composer-authenticated-repository-plugin - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. sonrac/composer-authenticated-repository-plugin

ActiveComposer-plugin[HTTP &amp; Networking](/categories/http)

sonrac/composer-authenticated-repository-plugin
===============================================

Composer plugin for authenticated repository access with GitHub tokens and HTTP basic auth

0.2.21(9mo ago)19.2k[1 PRs](https://github.com/sonrac/composer-authenticated-repository-plugin/pulls)1MITPHPPHP ^8.0

Since Jul 24Pushed 9mo agoCompare

[ Source](https://github.com/sonrac/composer-authenticated-repository-plugin)[ Packagist](https://packagist.org/packages/sonrac/composer-authenticated-repository-plugin)[ RSS](/packages/sonrac-composer-authenticated-repository-plugin/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (25)Used By (1)

Composer Authenticated Repository Plugin
========================================

[](#composer-authenticated-repository-plugin)

A Composer plugin that provides automatic authentication support for GitHub repositories and HTTP basic auth when downloading packages. The plugin intercepts file downloads and adds authentication headers as needed.

Features
--------

[](#features)

- **Pre-Download Hook**: Intercepts file downloads using Composer's `PreFileDownloadEvent`
- **GitHub Token Support**: Automatic GitHub OAuth token injection for GitHub URLs
- **HTTP Basic Auth**: Support for HTTP basic authentication
- **Repository Configuration**: Configurable repository matching for authentication
- **Debug Logging**: Comprehensive debug output for troubleshooting
- **Composer Config Integration**: Uses existing Composer authentication configuration
- **Transparent Operation**: Works with existing Composer workflows

Installation
------------

[](#installation)

### Option 1: Install as a Composer Plugin

[](#option-1-install-as-a-composer-plugin)

```
composer require sonrac/composer-authenticated-repository-plugin
```

### Option 2: Manual Installation

[](#option-2-manual-installation)

1. Clone this repository to your project
2. Add the plugin to your `composer.json`:

```
{
    "require": {
        "sonrac/composer-authenticated-repository-plugin": "*"
    },
    "config": {
        "allow-plugins": {
            "sonrac/composer-authenticated-repository-plugin": true
        }
    }
}
```

Configuration
-------------

[](#configuration)

### 1. Configure Authentication

[](#1-configure-authentication)

First, configure your authentication credentials in Composer:

#### GitHub Token Authentication

[](#github-token-authentication)

```
# Configure GitHub token for specific host
composer config github-oauth.api.github.com YOUR_GITHUB_TOKEN

# Or for a custom GitHub Enterprise host
composer config github-oauth.github.yourcompany.com YOUR_GITHUB_TOKEN
```

#### HTTP Basic Authentication

[](#http-basic-authentication)

```
# Configure HTTP basic auth for specific host
composer config http-basic.your-repo.com username password

# Or for a custom repository host
composer config http-basic.artifacts.company.com username password
```

### 2. Configure Repository Matching

[](#2-configure-repository-matching)

Add configuration to composer `extra` section to specify which repositories should receive authentication:

```
{
  "extra": {
    "composer-authenticated-plugin": {
      "repositories": [
        {
          "owner": "MacPaw",
          "name": "platform-shared-clients",
          "url": "https://github.com/MacPaw/platform-shared-clients"
        },
        {
          "owner": "my-org",
          "name": "private-packages",
          "url": "https://github.com/my-org/private-packages"
        }
      ]
    }
  }
}
```

**Important**: The `owner` and `name` fields are required and must match the GitHub repository owner and name exactly.

How It Works
------------

[](#how-it-works)

### 1. Plugin Activation

[](#1-plugin-activation)

The plugin activates during Composer initialization and:

- Reads authentication credentials from Composer configuration
- Creates an authenticated HTTP downloader
- Registers custom repository types
- Subscribes to the `PreFileDownloadEvent`

### 2. Download Interception

[](#2-download-interception)

When Composer attempts to download a file, the plugin:

```
public function onDownload(PreFileDownloadEvent $preFileDownloadEvent): void
{
    $processedUrl = $preFileDownloadEvent->getProcessedUrl();

    // Check if URL needs authentication
    if ($this->httpDownloader->isNeedAuthHeaders($processedUrl)) {
        // Add authentication headers
        $transportOptions = $this->httpDownloader->addAuthenticationHeaders($processedUrl, $options);
        $preFileDownloadEvent->setTransportOptions($transportOptions);
    }
}
```

### 3. Repository Matching

[](#3-repository-matching)

The plugin matches URLs against configured repositories:

```
public function isNeedAuthHeaders(string $url): bool
{
    // Parse URL to extract owner/repo from GitHub URLs
    // Match against configured repositories
    // Return true if authentication is needed
}
```

### 4. Authentication Header Injection

[](#4-authentication-header-injection)

For matching URLs, the plugin adds appropriate headers:

```
public function addAuthenticationHeaders(string $url, array $options): array
{
    $headers = $options['http']['header'] ?? [];

    // Add GitHub token for GitHub URLs
    if ($this->githubToken && $this->isGitHubUrl($url)) {
        $headers[] = 'Authorization: token ' . $this->githubToken;
    }

    // Add HTTP basic auth
    if ($this->httpBasicAuth) {
        $auth = base64_encode($username . ':' . $password);
        $headers[] = 'Authorization: Basic ' . $auth;
    }

    $options['http']['header'] = $headers;
    return $options;
}
```

Environment Variables
---------------------

[](#environment-variables)

For security, use environment variables:

```
# Set environment variables
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export ARTIFACT_USERNAME=your-username
export ARTIFACT_PASSWORD=your-password

# Install packages
composer update
```

Or use Composer's environment variable substitution:

```
{
    "config": {
        "github-oauth": {
            "api.github.com": "%env(GITHUB_TOKEN)%"
        },
        "http-basic": {
            "artifacts.company.com": {
                "username": "%env(ARTIFACT_USERNAME)%",
                "password": "%env(ARTIFACT_PASSWORD)%"
            }
        }
    }
}
```

Debug Mode
----------

[](#debug-mode)

Enable debug logging to see what the plugin is doing:

```
composer install -vvv
```

The plugin will output debug information including:

- URLs being processed
- Whether authentication headers are needed
- Repository matching results
- Authentication header details

Security Considerations
-----------------------

[](#security-considerations)

- **Token Security**: Never commit authentication tokens to version control
- **Environment Variables**: Use environment variables for sensitive configuration
- **Token Scopes**: Use minimal required scopes for GitHub tokens
- **HTTPS Only**: All requests use HTTPS for security
- **Repository Matching**: Only URLs matching configured repositories receive authentication

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **401 Authentication Errors**:

    - Verify your tokens/credentials are correctly configured
    - Check that the repository is configured in the plugin's `extra` section
    - Ensure the `owner` and `name` match the GitHub repository exactly
2. **Repository Not Found**:

    - Ensure the repository URL is accessible with your credentials
    - Verify the repository is listed in the plugin configuration
3. **Package Not Found**:

    - Check that the package is listed in the repository manifest
    - Verify download URLs are accessible with authentication
4. **Permission Denied**:

    - Verify your GitHub token has the required scopes
    - Check repository visibility and access permissions

### Debug Steps

[](#debug-steps)

1. **Check authentication configuration**:

    ```
    composer config github-oauth
    composer config http-basic
    ```
2. **Enable verbose output**:

    ```
    composer install -vvv
    ```
3. **Test repository access**:

    ```
    curl -H "Authorization: token YOUR_TOKEN" https://api.github.com/repos/owner/repo
    ```
4. **Verify plugin configuration**: Check that your `composer.json` has the correct `extra.composer-authenticated-plugin.repositories` configuration.

Development
-----------

[](#development)

### Building the Plugin

[](#building-the-plugin)

```
cd composer-authenticated-repository-plugin
composer install
```

### Running Tests

[](#running-tests)

```
composer test
```

### Plugin Structure

[](#plugin-structure)

```
composer-authenticated-repository-plugin/
├── composer.json                           # Plugin package definition
├── src/
│   ├── Plugin.php                          # Main plugin class with PreFileDownloadEvent
│   └── Repository/
│       ├── AuthenticatedComposerRepository.php # Repository wrapper
│       └── AuthenticatedHttpDownloader.php     # HTTP downloader with auth
├── tests/
│   └── AuthenticatedRepositoryTest.php     # Unit tests
├── example/
│   └── composer.json                       # Example configuration

```

License
-------

[](#license)

MIT License - see LICENSE file for details.

Support
-------

[](#support)

For issues and questions, please create an issue in the GitHub repository.

Current State and Recent Updates
--------------------------------

[](#current-state-and-recent-updates)

### Implementation Overview

[](#implementation-overview)

The plugin currently implements authentication support through:

1. **PreFileDownloadEvent Hook**: Intercepts all file downloads and adds authentication headers as needed
2. **Repository Matching**: Only adds authentication for URLs matching configured repositories
3. **Debug Logging**: Comprehensive debug output for troubleshooting
4. **GitHub Token Support**: Automatic token injection for GitHub URLs
5. **HTTP Basic Auth**: Support for HTTP basic authentication

### Key Features

[](#key-features)

- **Security**: Repository-specific authentication prevents token exposure
- **Compatibility**: Works with existing Composer workflows
- **Debugging**: Extensive debug logging for troubleshooting
- **Flexibility**: Supports both GitHub tokens and HTTP basic auth

### Recent Changes

[](#recent-changes)

- **Repository Configuration**: Now requires explicit repository configuration in `extra.composer-authenticated-plugin.repositories`
- **Debug Logging**: Added comprehensive debug output for troubleshooting
- **URL Matching**: Improved repository matching logic with case-insensitive comparison
- **Documentation**: Updated all README files to reflect current implementation

### Known Limitations

[](#known-limitations)

- Only supports GitHub repositories and HTTP basic auth
- Requires explicit repository configuration
- Debug logging only available with `-vvv` flag

### Future Enhancements

[](#future-enhancements)

- Support for additional authentication methods (OAuth 2.0, API keys)
- Caching and rate limiting support
- Enhanced error handling and retry logic
- Performance monitoring and metrics

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance60

Regular maintenance activity

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

23

Last Release

284d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1245037f65b027a2c38d7aa0281cd04f53ac27eaf695a60da7311254fcc99350?d=identicon)[sonrac](/maintainers/sonrac)

---

Top Contributors

[![sonrac](https://avatars.githubusercontent.com/u/3766459?v=4)](https://github.com/sonrac "sonrac (15 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sonrac-composer-authenticated-repository-plugin/health.svg)

```
[![Health](https://phpackages.com/badges/sonrac-composer-authenticated-repository-plugin/health.svg)](https://phpackages.com/packages/sonrac-composer-authenticated-repository-plugin)
```

###  Alternatives

[php-http/discovery

Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations

1.3k309.5M1.2k](/packages/php-http-discovery)[friendsofsymfony/rest-bundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony

2.8k73.3M317](/packages/friendsofsymfony-rest-bundle)[react/http

Event-driven, streaming HTTP client and server implementation for ReactPHP

78126.4M414](/packages/react-http)[php-http/curl-client

PSR-18 and HTTPlug Async client with cURL

48247.0M383](/packages/php-http-curl-client)[smi2/phpclickhouse

PHP ClickHouse Client

83510.1M71](/packages/smi2-phpclickhouse)[paragonie/csp-builder

Easily add and update Content-Security-Policy headers for your project

5412.8M18](/packages/paragonie-csp-builder)

PHPackages © 2026

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