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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"illuminate/console": "^13.0",
"illuminate/contracts": "^13.0",
"illuminate/database": "^13.0",
"illuminate/process": "^13.0",
"illuminate/support": "^13.0"
},
"require-dev": {
Expand Down
1 change: 1 addition & 0 deletions config/built-for-cloud.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@

'cloud' => [
'binary' => env('BUILT_FOR_CLOUD_BINARY', 'cloud'),
'application' => env('BUILT_FOR_CLOUD_APPLICATION'),
],

];
18 changes: 18 additions & 0 deletions src/BuiltForCloudServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,38 @@

namespace ArtisanBuild\BuiltForCloud;

use ArtisanBuild\BuiltForCloud\Commands\FallbackTokenGenerateCommand;
use ArtisanBuild\BuiltForCloud\Commands\TokenCreateCommand;
use ArtisanBuild\BuiltForCloud\Commands\TokenListCommand;
use ArtisanBuild\BuiltForCloud\Commands\TokenRevokeCommand;
use ArtisanBuild\BuiltForCloud\Commands\TokenRotateCommand;
use ArtisanBuild\BuiltForCloud\Commands\TokenUsageCommand;
use ArtisanBuild\BuiltForCloud\Contracts\UsageReporter;
use Illuminate\Support\ServiceProvider;

final class BuiltForCloudServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/built-for-cloud.php', 'built-for-cloud');

$this->app->singleton(UsageReporter::class, NullUsageReporter::class);
}

public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');

if ($this->app->runningInConsole()) {
$this->commands([
FallbackTokenGenerateCommand::class,
TokenCreateCommand::class,
TokenListCommand::class,
TokenRevokeCommand::class,
TokenRotateCommand::class,
TokenUsageCommand::class,
]);

$this->publishes([
__DIR__.'/../config/built-for-cloud.php' => $this->app->configPath('built-for-cloud.php'),
], 'built-for-cloud-config');
Expand Down
170 changes: 170 additions & 0 deletions src/CloudCommandRunner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud;

use Illuminate\Support\Facades\Process;
use RuntimeException;

use function Laravel\Prompts\select;

final class CloudCommandRunner
{
public function resolveEnvironment(?string $explicit = null): string
{
if ($explicit !== null && $explicit !== '') {
return $explicit;
}

$application = $this->applicationId();

$result = Process::run([
$this->binary(),
'environment:list',
$application,
'--json',
'--fields=id,name',
]);

if (! $result->successful()) {
throw new RuntimeException('Unable to list Laravel Cloud environments: '.$result->errorOutput());
}

$environments = $this->decodeJsonArray($result->output());

if ($environments === []) {
throw new RuntimeException('No environments found for Laravel Cloud application '.$application.'.');
}

if (count($environments) === 1) {
return $this->environmentId($environments[0]);
}

/** @var array<string, string> $choices */
$choices = [];

foreach ($environments as $environment) {
$id = $this->environmentId($environment);
$name = (string) ($environment['name'] ?? $id);
$choices[$id] = $name;
}

return (string) select(
label: 'Select the Laravel Cloud environment',
options: $choices,
);
}

/**
* @return array{output: string, exitCode: int}
*/
public function run(string $environment, string $artisanCommand): array
{
$result = Process::run([
$this->binary(),
'command:run',
$environment,
'--cmd',
'php artisan '.$artisanCommand,
'--json',
'--fields=output,exitCode',
'--no-interaction',
]);

if (! $result->successful()) {
throw new RuntimeException('Laravel Cloud command failed: '.$result->errorOutput());
}

/** @var array{output?: mixed, exitCode?: mixed} $payload */
$payload = $this->decodeJsonObject($result->output());

if (! isset($payload['exitCode']) || ! is_numeric($payload['exitCode'])) {
throw new RuntimeException('Laravel Cloud returned a response without a valid exit code.');
}

return [
'output' => (string) ($payload['output'] ?? ''),
'exitCode' => (int) $payload['exitCode'],
];
}

/**
* @param array{id?: mixed, name?: mixed} $environment
*/
private function environmentId(array $environment): string
{
$id = $environment['id'] ?? null;

if (! is_string($id) && ! is_int($id)) {
throw new RuntimeException('Laravel Cloud returned an environment without a valid id.');
}

$id = (string) $id;

if ($id === '') {
throw new RuntimeException('Laravel Cloud returned an environment without a valid id.');
}

return $id;
}

private function binary(): string
{
return (string) config('built-for-cloud.cloud.binary', 'cloud');
}

private function applicationId(): string
{
$configured = config('built-for-cloud.cloud.application');

if (is_string($configured) && $configured !== '') {
return $configured;
}

$path = base_path('.cloud/config.json');

if (is_file($path)) {
/** @var mixed $decoded */
$decoded = json_decode((string) file_get_contents($path), true);

if (is_array($decoded) && isset($decoded['application_id']) && is_string($decoded['application_id']) && $decoded['application_id'] !== '') {
return $decoded['application_id'];
}
}

throw new RuntimeException('No Laravel Cloud application id configured. Set built-for-cloud.cloud.application or .cloud/config.json application_id.');
}

/**
* @return list<array{id: mixed, name?: mixed}>
*/
private function decodeJsonArray(string $json): array
{
/** @var mixed $decoded */
$decoded = json_decode($json, true);

if (! is_array($decoded) || ! array_is_list($decoded)) {
throw new RuntimeException('Laravel Cloud returned invalid JSON.');
}

/** @var list<array{id: mixed, name?: mixed}> $decoded */
return $decoded;
}

/**
* @return array<string, mixed>
*/
private function decodeJsonObject(string $json): array
{
/** @var mixed $decoded */
$decoded = json_decode($json, true);

if (! is_array($decoded) || array_is_list($decoded)) {
throw new RuntimeException('Laravel Cloud returned invalid JSON.');
}

/** @var array<string, mixed> $decoded */
return $decoded;
}
}
51 changes: 51 additions & 0 deletions src/Commands/FallbackTokenGenerateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud\Commands;

use ArtisanBuild\BuiltForCloud\TokenGenerator;
use Illuminate\Console\Command;

final class FallbackTokenGenerateCommand extends Command
{
protected $signature = 'fallback-token:generate {--show} {--path=}';

protected $description = 'Generate and store a local fallback token';

public function handle(TokenGenerator $generator): int
{
$generated = $generator->generate();
$path = $this->path();
$contents = is_file($path) ? (string) file_get_contents($path) : '';
$line = 'FALLBACK_TOKEN='.$generated->plaintext;

if (preg_match('/^FALLBACK_TOKEN=.*$/m', $contents) === 1) {
$contents = (string) preg_replace('/^FALLBACK_TOKEN=.*$/m', $line, $contents);
} else {
$contents = rtrim($contents, "\r\n");
$contents .= ($contents === '' ? '' : PHP_EOL).$line.PHP_EOL;
}

file_put_contents($path, $contents);

if ((bool) $this->option('show')) {
$this->line('FALLBACK_TOKEN='.$generated->plaintext);
} else {
$this->line('Fallback token written for local/bootstrap use. Re-run with --show if you need to display it.');
}

return self::SUCCESS;
}

private function path(): string
{
$path = $this->option('path');

if (is_string($path) && $path !== '') {
return $path;
}

return $this->laravel->environmentFilePath();
}
}
55 changes: 55 additions & 0 deletions src/Commands/TokenCreateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud\Commands;

use ArtisanBuild\BuiltForCloud\CloudCommandRunner;
use ArtisanBuild\BuiltForCloud\TokenGenerator;
use ArtisanBuild\BuiltForCloud\TokenRegistry;
use Illuminate\Console\Command;

final class TokenCreateCommand extends Command
{
protected $signature = 'token:create {name} {--execute} {--hash=} {--environment=}';

protected $description = 'Create a Built for Cloud API token';

public function handle(CloudCommandRunner $runner, TokenGenerator $generator, TokenRegistry $registry): int
{
$name = (string) $this->argument('name');

if ((bool) $this->option('execute')) {
$registry->store($name, (string) $this->option('hash'));
$this->line("Token {$name} stored.");

return self::SUCCESS;
}

$generated = $generator->generate();
$environment = $runner->resolveEnvironment($this->stringOption('environment'));
$result = $runner->run($environment, 'token:create '.$this->quote($name).' --execute --hash='.$generated->hash);

$this->line($result['output']);

if ($result['exitCode'] !== self::SUCCESS) {
return $result['exitCode'];
}

$this->line('Save this token - shown once: '.$generated->plaintext);

return self::SUCCESS;
}

private function stringOption(string $key): ?string
{
$value = $this->option($key);

return is_string($value) && $value !== '' ? $value : null;
}

private function quote(string $value): string
{
return escapeshellarg($value);
}
}
Loading