Base functionality and helpers used for building Chief Tools.
Keep in mind that this package is not meant to be used standalone, but as a base for building our own Chief Tools, this package is open-sourced for inspiration and to be used as a reference.
- Authentication through Account Chief (powered by Socialite)
- Configured Sentry client
- Lighthouse GraphQL with base schema and scalars
- Session protected endpoint
/api/graphql/web - Session protected (GraphiQL) playground
/api/playground - Access token protected endpoint
/api/graphql(tokens managed by Account Chief)
- Session protected endpoint
- Basic API documentation pages for GraphQL endpoint
- Account pages to show profile information and preferences
- Team pages to show team information, preferences and billing
- Redirects to Chief Tools for
/contact,/privacy,/terms - Account Chief webhook handler to be notified when user, team or tokens change
- Login event listener to update the
last_logincolumn on theuserstable - Health check queue job pinging
QUEUE_MONITOR_URLevery minute using the default queue (disabled whenQUEUE_MONITOR_URLis empty or unset)
ChiefTools\SDK\Middleware\AuthenticateChief
Validates a request comes from Chief Tools
Requireschief.webhook_signing_secret(CHIEF_WEBHOOK_SIGNING_SECRET) to be set to the signing secret of the app's endpoint in Account ChiefChiefTools\SDK\Middleware\AutoAuthenticate
Uses both theapiandwebguard and sets the first that is authenticatedChiefTools\SDK\Middleware\ForceSecure
Make sure the request is overhttps://ChiefTools\SDK\Middleware\MoveAccessTokenFromURLToHeader
Move the access token fromaccess_tokenGET paramater to theAuthorizationheaderChiefTools\SDK\Middleware\SecurityHeaders
Adds a default set of security headers, can be configured by settingchief.response.securityheaders(array) in the app configChiefTools\SDK\Middleware\TrustProxiesOnVapor
Configuresfideloper/proxyto be used on Laravel Vapor
ChiefTools\SDK\Rules\UUID
Valites the input value is a UUIDv4
active($whitelist = null, $blacklist = null, $active = 'active', $inactive = '')
Get active state based on whitelist. Used to indicate active menu'stimezones(): array
Return an key-value list of all timezonesvalidate($fields, $rules): bool
Validate fields against rules. Examplevalidate($id, new \ChiefTools\SDK\Rules\UUID)latest_ca_bundle_file_path(): string
Get the path to the most up-to-date CA bundle file, uses Certainty under the hood
Start with requiring the package:
composer require chieftools/sdkPublish the configuration files and optionally the migrations:
php artisan vendor:publish --tag=chief-config
# php artisan vendor:publish --tag=chief-migrationsRun the app migrations to create the users table:
php artisan migrateAdd the Chief service to the config/services.php:
<?php
return [
'chief' => [
'client_id' => env('CHIEF_CLIENT_ID'),
'client_secret' => env('CHIEF_CLIENT_SECRET'),
'base_url' => env('CHIEF_BASE_URL', 'https://account.chief.app'),
'verify' => env('CHIEF_VERIFY', true),
'redirect' => '/login/callback',
],
];That's all, you should be able to authenticate against Account Chief.
Apps send signed webhooks to the endpoints their teams add. The SDK stores events, delivers and retries them, and ships the settings pages, the REST API and the e-mails. An app only declares its events and calls them where things happen.
- List the events as a backed enum implementing
ChiefTools\SDK\Webhook\Outbound\Contracts\WebhookEventType, with#[WebhookObject]and#[WebhookData]on each case so the OpenAPI document describes the payloads. - Enable them in
config/chief.php. Only set what differs from the defaults inWebhookConfig, theUser-Agentdefaults to the app name, likeBackupChief-Webhooks/1.0:'webhooks' => [ 'enabled' => true, 'events' => App\Enums\Webhook\EventType::class, 'queue' => 'webhooks', 'breadcrumb_parent' => ['title' => 'Settings', 'route' => 'settings'], ],
- Give the queue its own Horizon supervisor with
triesset to 1, the SDK schedules retries on the delivery itself. - Extend
ChiefTools\SDK\Webhook\Outbound\EventSenderwith one method per event that renders the API resource and callssend(). Call those methods from the code that makes the change, before any e-mail about it. - Register the pages with
Route::chiefWebhooks('settings/webhooks')in the team route group and the API withRoute::chiefWebhooksApi('<app>:webhooks'). Add the<app>:webhooks:readand<app>:webhooks:writescopes and the webhooks capability to the app in Account Chief. - Put
<x-chief::webhooks.settings-card :team="$team" description="..." />on the settings page, with aclassfor the spacing between the page's cards. - Listen for
EndpointFailingandEndpointDisabledand sendChiefTools\SDK\Webhook\Outbound\Mail\EndpointFailingorEndpointDisabledto the team members whose notification preferences want it, with an idempotency key per endpoint and failure. - Test with
ChiefTools\SDK\Webhook\Outbound\Testing\Webhooks::subscribe($team)andWebhooks::sent().
Receivers often handle events from several apps, so events with the same meaning look the same everywhere.
- Name events
<resource>.<past tense verb>in snake case, likeserver.createdorip_list.updated. The resource matches its API resource and ID prefix. data.objectis the resource as the API returns it at the time of the event. A.deletedevent sends the resource as it was right before. Never send secrets or one-time tokens, like an enrollment token.- Every resource that can be created, changed and removed through the API or the app gets
.created,.updatedand.deleted..updatedcovers changes a person or integration makes, not counters or timestamps the app updates on its own. - A problem and its end are a pair, like
server.offlineandserver.onlineorbackup.failingandbackup.recovered. Send the opening event once per problem, not on every check, and the closing event only when the problem went away. A problem that ends for another reason, like a deleted rule, closes with a field that says why or without an event. - The closing event carries
<state>_since, likeoffline_sinceorfailing_since: when the app recorded the problem that the opening event announced, as an ISO 8601 UTC time. It is not the last contact or heartbeat. - Extra fields next to
objectare snake case and documented with#[WebhookData]. IDs of other resources use their API ID with prefix, likerun_id. Enumerated values are extensible enums, receivers treat unknown values as unknown. - Software the app updates on a server, like an agent or a proxy, sends
server.<update>_startedwhen an update is requested by a person, the API or the automatic rollout,server.<update>_succeededwhen the server reports the target version, andserver.<update>_failedonce per attempt that fails, with why as an extensible enum.<update>is the API's name for it, likeagent_updateorupgrade.data.objectis the server, the attempt is where the API shows it: in the server resource, or asdatafields with the attempt's API ID and result, likecommand_idandresult. A server that reports the target version after its attempt failed still sendsserver.<update>_succeeded. Every started update ends in one of these: an update without a result expires within a few hours and fails, with a result likeexpiredortimeout, so receivers never wait on an update that stays pending for days. Deleting a server during an update fails it withcancelledright beforeserver.deleted. Expired and cancelled updates do not count towards pausing a rollout. - An automatic rollout that pauses for a team after too many failed updates sends
<component>_rollout.paused, likeagent_rollout.paused, with the release as the API returns it asdata.objectandfailures, the failed updates since the rollout was last resumed. Resuming is a person's action and sends no event. - Group events in the enum like the app's settings and docs: the resource lifecycle first, then availability and alerts, then everything else.
You will need to create a routes/graphql/schema.graphql in your own project with the following contents:
#import ../../vendor/chieftools/sdk/routes/graphql/schema.graphqlAnything you want to add the the schema you can do thereafter, for example:
#import ../../vendor/chieftools/sdk/routes/graphql/schema.graphql
#import ./types/*.graphql
#import ./queries/*.graphqlKeep in mind that the User type is already provided so you will need to extend that if you want to append fields.
type OfType implements Entity {
id: ID!
}
extend type User {
relation: [OfType!]! @hasMany(type: "paginator")
}