Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,9 @@ jobs:
fail-fast: false
matrix:
php: [ 8.3, 8.4, 8.5 ]
laravel: [ 11.*, 12.*, 13.* ]
laravel: [ 12.*, 13.* ]
dependency-version: [ stable, lowest ]
include:
# orchestra/testbench below 9.2 sets a static property it never declares,
# which fails every test, so the Laravel 11 floor starts there
- laravel: 11.*
testbench: ^9.2
- laravel: 12.*
testbench: ^10.0
- laravel: 13.*
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ format. This project adheres to [Semantic Versioning](https://semver.org/spec/v2

## [Unreleased]

### Added

- Sign in as a Linear OAuth app with the client credentials grant (`LINEAR_CLIENT_ID`, `LINEAR_CLIENT_SECRET`, `LINEAR_SCOPES`). The app token is cached until it expires, and replaced when Linear rejects it.

### Removed

- Laravel 11 support. Every Laravel 11 release now has unpatched security advisories, so Composer refuses to install it.

## [0.1.2] - 2026-09-20

### Added
Expand Down
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,32 @@ Linear changes their schema.
composer require glhd/linearavel
```

Then add your API key to your `.env` file:
Then add your personal API key to your `.env` file:

```dotenv
LINEAR_API_KEY=lin_api_...
```

You can create a key under **Settings → Security & access → Personal API keys** in
Linear. To publish the config file:
Linear.

To act as an app instead of as your own user, create an OAuth application in Linear
(**Settings → API → OAuth applications**), turn on **Client credentials**, and add
its credentials in place of a personal API key. Linear requires a redirect URI when
you create the app, but the client credentials grant never uses it, so any URL on
your own domain will do.

```dotenv
LINEAR_CLIENT_ID=...
LINEAR_CLIENT_SECRET=...
LINEAR_SCOPES=read,write
```

Linearavel requests an app token with the client credentials grant and keeps it in
your application cache until it expires (30 days). If Linear rejects the token,
Linearavel fetches a new one and sends the request again.

To publish the config file:

```shell
php artisan vendor:publish --tag=linearavel-config
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"require": {
"php": "^8.3",
"ext-json": "*",
"illuminate/support": "^11.0|^12.0|^13.0",
"illuminate/support": "^12.0|^13.0",
"guzzlehttp/guzzle": "^7.8|^8.0",
"nikic/php-parser": "^5.0",
"saloonphp/saloon": "^4.0",
Expand All @@ -29,7 +29,7 @@
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.34",
"mockery/mockery": "^1.6",
"orchestra/testbench": "^9.2|^10.0|^11.0",
"orchestra/testbench": "^10.0|^11.0",
"phpunit/phpunit": "^10.3|^11.0|^12.0|^13.0"
},
"autoload": {
Expand Down
16 changes: 16 additions & 0 deletions config/linearavel.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,20 @@

'api_key' => env('LINEAR_API_KEY'),
'base_url' => env('LINEAR_BASE_URL', 'https://api.linear.app/graphql'),

/*
|--------------------------------------------------------------------------
| OAuth app (client credentials)
|--------------------------------------------------------------------------
|
| To act as an OAuth app instead of a user, turn on "Client credentials
| tokens" for the app in Linear and set its client ID and secret. When a
| client ID is set, it's used in place of the API key. Scopes are a
| comma-separated list.
|
*/

'client_id' => env('LINEAR_CLIENT_ID'),
'client_secret' => env('LINEAR_CLIENT_SECRET'),
'scopes' => env('LINEAR_SCOPES', 'read,write'),
];
27 changes: 26 additions & 1 deletion src/Connectors/LinearConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

use Glhd\Linearavel\Exceptions\LinearRequestException;
use Saloon\Contracts\Authenticator;
use Saloon\Exceptions\Request\FatalRequestException;
use Saloon\Exceptions\Request\RequestException;
use Saloon\Http\Auth\TokenAuthenticator;
use Saloon\Http\Connector;
use Saloon\Http\Request;
use Saloon\Http\Response;
use Throwable;

Expand All @@ -15,9 +18,13 @@ class LinearConnector extends Connector
use MutatesLinear;

public function __construct(
protected string $api_key,
protected ?string $api_key = null,
protected string $base_url = 'https://api.linear.app/graphql',
protected ?LinearOAuthConnector $oauth = null,
) {
if ($this->oauth) {
$this->tries = 2;
}
}

public function resolveBaseUrl(): string
Expand Down Expand Up @@ -49,8 +56,26 @@ public function getRequestException(Response $response, ?Throwable $senderExcept
return null;
}

public function handleRetry(FatalRequestException|RequestException $exception, Request $request): bool
{
$was_unauthorized = $exception instanceof RequestException && 401 === $exception->getResponse()->status();
$was_graphql_request = $exception->getPendingRequest()->getConnector() === $this;

if ($was_unauthorized && $was_graphql_request) {
$this->oauth?->forgetAccessToken();

return true;
}

return false;
}

protected function defaultAuth(): ?Authenticator
{
if ($this->oauth) {
return new TokenAuthenticator($this->oauth->accessToken());
}

return new TokenAuthenticator($this->api_key, prefix: '');
}

Expand Down
59 changes: 59 additions & 0 deletions src/Connectors/LinearOAuthConnector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Glhd\Linearavel\Connectors;

use Illuminate\Support\Facades\Cache;
use Saloon\Helpers\OAuth2\OAuthConfig;
use Saloon\Http\Connector;
use Saloon\Traits\OAuth2\ClientCredentialsGrant;
use Saloon\Traits\Plugins\AcceptsJson;

class LinearOAuthConnector extends Connector
{
use AcceptsJson;
use ClientCredentialsGrant;

/** @param array<int, string> $scopes */
public function __construct(
protected string $client_id,
protected string $client_secret,
protected array $scopes,
) {
}

public function resolveBaseUrl(): string
{
return 'https://api.linear.app';
}

public function accessToken(): string
{
if ($token = Cache::get($this->cacheKey())) {
return $token;
}

$authenticator = $this->getAccessToken($this->scopes, ',');

Cache::put($this->cacheKey(), $authenticator->getAccessToken(), $authenticator->getExpiresAt()?->modify('-1 hour'));

return $authenticator->getAccessToken();
}

public function forgetAccessToken(): void
{
Cache::forget($this->cacheKey());
}

protected function defaultOauthConfig(): OAuthConfig
{
return OAuthConfig::make()
->setClientId($this->client_id)
->setClientSecret($this->client_secret)
->setTokenEndpoint('/oauth/token');
}

protected function cacheKey(): string
{
return 'linearavel:access-token:'.sha1($this->client_id.'|'.implode(',', $this->scopes));
}
}
6 changes: 6 additions & 0 deletions src/Support/LinearavelServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Glhd\Linearavel\Support;

use Glhd\Linearavel\Connectors\LinearConnector;
use Glhd\Linearavel\Connectors\LinearOAuthConnector;
use Glhd\Linearavel\Support\CodeGeneration\PhpStormMetaWriter;
use Glhd\Linearavel\Support\CodeGeneration\WriteQueue;
use Illuminate\Support\ServiceProvider;
Expand All @@ -22,6 +23,11 @@ public function register()
return new LinearConnector(
api_key: config('linearavel.api_key'),
base_url: config('linearavel.base_url', 'https://api.linear.app/graphql'),
oauth: config('linearavel.client_id') ? new LinearOAuthConnector(
client_id: config('linearavel.client_id'),
client_secret: config('linearavel.client_secret'),
scopes: array_map('trim', explode(',', config('linearavel.scopes'))),
) : null,
);
});

Expand Down
118 changes: 118 additions & 0 deletions tests/Feature/ClientCredentialsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php

namespace Glhd\Linearavel\Tests\Feature;

use Glhd\Linearavel\Requests\LinearRequest;
use Glhd\Linearavel\Tests\TestCase;
use Saloon\Exceptions\Request\RequestException;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Http\OAuth2\GetClientCredentialsTokenRequest;
use Saloon\Http\Request;
use Saloon\Http\Response;

class ClientCredentialsTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();

MockClient::destroyGlobal();

config([
'linearavel.api_key' => null,
'linearavel.client_id' => 'client-id',
'linearavel.client_secret' => 'client-secret',
]);
}

public function test_it_signs_in_as_the_app_with_a_client_credentials_token(): void
{
MockClient::global([
GetClientCredentialsTokenRequest::class => $this->token('app-token'),
LinearRequest::class => $this->viewer(),
]);

$this->assertSame('app-user', linear()->viewer()->get('id')->id);

$this->assertSaloonSent(fn(Request $request) => $request instanceof GetClientCredentialsTokenRequest
&& 'client_credentials' === $request->body()->get('grant_type')
&& 'client-id' === $request->body()->get('client_id')
&& 'client-secret' === $request->body()->get('client_secret')
&& 'read,write' === $request->body()->get('scope'));

$this->assertSaloonSent(fn(Request $request, Response $response) => $request instanceof LinearRequest
&& 'Bearer app-token' === $response->getPendingRequest()->headers()->get('Authorization'));
}

public function test_the_token_is_reused_for_later_requests(): void
{
MockClient::global([
GetClientCredentialsTokenRequest::class => $this->token('app-token'),
LinearRequest::class => $this->viewer(),
]);

linear()->viewer()->get('id');
linear()->viewer()->get('id');

MockClient::getGlobal()->assertSentCount(1, GetClientCredentialsTokenRequest::class);
MockClient::getGlobal()->assertSentCount(2, LinearRequest::class);
}

public function test_a_rejected_token_is_replaced_and_the_request_is_sent_again(): void
{
MockClient::global([
$this->token('revoked-token'),
MockResponse::make(['errors' => [['message' => 'Authentication required, not authenticated', 'extensions' => ['code' => 'AUTHENTICATION_ERROR']]]], 401),
$this->token('new-token'),
$this->viewer(),
]);

$this->assertSame('app-user', linear()->viewer()->get('id')->id);

$this->assertSaloonSent(fn(Request $request, Response $response) => $request instanceof LinearRequest
&& $response->successful()
&& 'Bearer new-token' === $response->getPendingRequest()->headers()->get('Authorization'));
}

public function test_a_rejected_client_secret_is_not_retried(): void
{
MockClient::global([
GetClientCredentialsTokenRequest::class => MockResponse::make(['error' => 'invalid_client'], 401),
]);

try {
linear()->viewer()->get('id');
$this->fail('Expected the token request to fail.');
} catch (RequestException) {
}

MockClient::getGlobal()->assertSentCount(1, GetClientCredentialsTokenRequest::class);
}

public function test_a_personal_api_key_is_sent_without_a_bearer_prefix(): void
{
config(['linearavel.api_key' => 'lin_api_key', 'linearavel.client_id' => null]);

MockClient::global([LinearRequest::class => $this->viewer()]);

linear()->viewer()->get('id');

$this->assertSaloonSent(fn(Request $request, Response $response) => 'lin_api_key' === $response->getPendingRequest()->headers()->get('Authorization'));
}

protected function token(string $access_token): MockResponse
{
return MockResponse::make([
'access_token' => $access_token,
'token_type' => 'Bearer',
'expires_in' => 2591999,
'scope' => 'read write',
]);
}

protected function viewer(): MockResponse
{
return MockResponse::make(['data' => ['viewer' => ['id' => 'app-user']]]);
}
}
Loading