diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..460c8e4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,21 @@ +.git +.github +.claude +.scribe +.idea +.vscode +.env +.env.* +!.env.example +node_modules +vendor +tests +storage/logs/* +storage/framework/cache/data/* +storage/framework/sessions/* +storage/framework/views/* +bootstrap/cache/*.php +database/*.sqlite +frankenphp +Dockerfile +.dockerignore diff --git a/.env.example b/.env.example index 97a107b..541ad29 100644 --- a/.env.example +++ b/.env.example @@ -4,6 +4,8 @@ APP_KEY= APP_DEBUG=true APP_URL=http://localhost SANCTUM_EXPIRATION=120 +API_KEY_DEFAULT_DAYS=90 +API_KEY_MAX_DAYS=365 IDEMPOTENCY_TTL=86400 SECURITY_FORCE_HTTPS=false SECURITY_HSTS_ENABLED=true @@ -48,6 +50,8 @@ BROADCAST_CONNECTION=log FILESYSTEM_DISK=local QUEUE_CONNECTION=database +OCTANE_SERVER=frankenphp + CACHE_STORE=database # CACHE_PREFIX= diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index ac54357..985b7b3 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -42,3 +42,55 @@ jobs: - name: Run test suite run: php artisan test + + # The test suite regenerates public/docs/openapi.yaml, so this grades the spec the code + # produces now, against .legible.yaml. + - name: Check the OpenAPI spec is agent-ready + env: + LEGIBLE_VERSION: 0.1.2 + run: | + archive="legible_${LEGIBLE_VERSION}_linux_amd64.tar.gz" + base="https://github.com/JustSteveKing/legible/releases/download/v${LEGIBLE_VERSION}" + curl -fsSLO "${base}/${archive}" + curl -fsSL "${base}/checksums.txt" | grep " ${archive}\$" | sha256sum -c - + tar xzf "${archive}" legible + ./legible check public/docs/openapi.yaml + + image: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Build the production image + run: docker build --tag kit:ci . + + # Boots with production settings, so ProductionSecurityChecks runs, then asks Octane for a + # health check and an API problem through a TLS-terminating proxy's headers. + - name: Boot it and make requests + run: | + docker run --detach --name kit --publish 8000:8000 \ + --env APP_KEY="base64:$(openssl rand -base64 32)" \ + --env APP_URL=https://api.example.test \ + --env SECURITY_FORCE_HTTPS=true \ + --env TRUSTED_HOSTS=api.example.test \ + --env CORS_ALLOWED_ORIGINS=https://app.example.test \ + --env DB_CONNECTION=sqlite \ + --env DB_DATABASE=/tmp/kit.sqlite \ + kit:ci + for attempt in $(seq 1 30); do + curl --silent --fail --header 'Host: api.example.test' --header 'X-Forwarded-Proto: https' \ + http://127.0.0.1:8000/up > /dev/null && break + sleep 1 + done + curl --silent --fail --header 'Host: api.example.test' --header 'X-Forwarded-Proto: https' \ + http://127.0.0.1:8000/up > /dev/null + curl --silent --include --header 'Host: api.example.test' --header 'X-Forwarded-Proto: https' \ + http://127.0.0.1:8000/v1/auth/me | tee response.txt + grep --quiet '^HTTP/1.1 401' response.txt + grep --quiet --ignore-case '^content-type: application/problem+json' response.txt + + - name: Show the container log + if: failure() + run: docker logs kit diff --git a/.github/workflows/dependency-updates.yml b/.github/workflows/dependency-updates.yml index 3447fb5..eab6410 100644 --- a/.github/workflows/dependency-updates.yml +++ b/.github/workflows/dependency-updates.yml @@ -25,7 +25,9 @@ jobs: coverage: none - name: Install current dependencies - run: composer install --no-interaction --no-progress --prefer-dist --no-scripts + run: | + composer install --no-interaction --no-progress --prefer-dist --no-scripts + cp composer.lock "${RUNNER_TEMP}/composer.lock.before" # Vet's plugin keeps every release younger than vet.json's minimum-release-age out of the # update. It then refuses to install what nobody has trusted yet and exits 1, after the lock @@ -40,19 +42,37 @@ jobs: - name: Install the updated lock without Vet run: composer install --no-plugins --no-interaction --no-progress --prefer-dist --no-scripts + # Laravel's own packages are trusted by policy (AGENTS.md, Dependencies). When they are the + # only packages the update changed, their trust is recorded here and the PR needs no review. + - name: Trust Laravel's own packages + run: | + decision=$(jq -rn --slurpfile old "${RUNNER_TEMP}/composer.lock.before" --slurpfile new composer.lock ' + def index(lock): [lock.packages[], lock["packages-dev"][]] | map({key: .name, value: (.version + "@" + (.dist.reference // .source.reference // ""))}) | from_entries; + (index($old[0])) as $before + | [index($new[0]) | to_entries[] | select($before[.key] != .value) | .key] + | if length > 0 and all(startswith("laravel/")) then "trust" else "review" end') + if [ "${decision}" = 'trust' ]; then + ./vendor/bin/vet --fresh --no-interaction --no-ansi + echo 'LARAVEL_ONLY=true' >> "${GITHUB_ENV}" + fi + - name: Audit with Vet run: | ./vendor/bin/vet --no-interaction --no-ansi > vet-report.txt 2>&1 || true { echo 'Automated weekly dependency refresh: `composer update`, holding back every release younger than `minimum-release-age` in `vet.json`.' echo + if [ "${LARAVEL_ONLY:-}" = 'true' ]; then + echo 'Every changed package is `laravel/*`, trusted by policy, so `vet.json` is updated in this PR and it needs no review.' + echo + fi echo '## Vet' echo echo '```' cat vet-report.txt echo '```' echo - echo 'Untrusted packages fail `composer install` in CI. To review, check out this branch, run `composer install --no-plugins`, then `./vendor/bin/vet` in a terminal: read each change, or hand them to your coding agent, and pick the packages you trust. Commit `vet.json` to this branch; that push runs CI.' + echo 'Otherwise, untrusted packages fail `composer install` in CI. To review, check out this branch, run `composer install --no-plugins`, then `./vendor/bin/vet` in a terminal: read each change, or hand them to your coding agent, and pick the packages you trust. Commit `vet.json` to this branch; that push runs CI.' } > pr-body.md rm update.log vet-report.txt @@ -65,5 +85,6 @@ jobs: add-paths: | composer.json composer.lock + vet.json branch: bot/dependency-updates delete-branch: true diff --git a/.gitignore b/.gitignore index b71b1ea..2206bf3 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,9 @@ Homestead.json Homestead.yaml Thumbs.db + +# Octane: a locally downloaded FrankenPHP binary and its Caddy state +/frankenphp +/public/frankenphp-worker.php +**/caddy +/.legible diff --git a/.legible.yaml b/.legible.yaml new file mode 100644 index 0000000..be399b2 --- /dev/null +++ b/.legible.yaml @@ -0,0 +1,18 @@ +# legible scores public/docs/openapi.yaml for agent readiness: what will trip up an LLM calling +# the API as tools. CI fails on any warning or a score under 95. `legible explain ` says why a +# rule matters. https://github.com/JustSteveKing/legible +fail-on: warning +fail-under: 95 + +ignore: + - rule: error-shape + operations: + - POST /v1/auth/register + - POST /v1/auth/login + - POST /v1/auth/password/forgot + - POST /v1/auth/password/reset + - GET /v1/auth/password/reset/* + - POST /v1/auth/tokens + reason: > + Validation problems add an errors member keyed by field, which apiguide.dev's + validation-failed type defines. Every problem shares type, title, status and detail. diff --git a/.scribe/endpoints.cache/00.yaml b/.scribe/endpoints.cache/00.yaml index 0e5b8af..0d2291c 100644 --- a/.scribe/endpoints.cache/00.yaml +++ b/.scribe/endpoints.cache/00.yaml @@ -15,7 +15,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: Register - description: 'Create a new account and issue a Sanctum bearer token.' + description: 'Create an account and issue its first bearer token. Use it once per new user; send an Idempotency-Key so a retried request cannot create a second account. Returns the user with the token, its type and expiry in meta, and sends a verification email.' authenticated: false deprecated: false headers: @@ -80,7 +80,7 @@ endpoints: - custom: [] status: 201 - content: '{"data":{"id":"01m5cb6hssde51qe3kn813thmv","name":"Justina Gaylord","email":"lafayette.considine@example.com","email_verified_at":"2026-10-20T09:45:06+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' + content: '{"data":{"id":"01m5cdfjnp16kbfqq3s4xsnvb5","name":"Justina Gaylord","email":"lafayette.considine@example.com","email_verified_at":"2026-10-20T10:24:59+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' headers: [] description: 'Registration succeeded.' - @@ -106,7 +106,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: Login - description: 'Authenticate a user and issue a Sanctum bearer token.' + description: 'Exchange an email and password for a bearer token. Use it when a user signs in on a new device, naming the device in device_name. Returns the user with the token, its type and expiry in meta; wrong credentials are a 422 on the email field.' authenticated: false deprecated: false headers: @@ -159,7 +159,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cb6ht2em5q96y8t1rffqv6","name":"Justina Gaylord","email":"cormier.nick@example.com","email_verified_at":"2026-10-20T09:45:06+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' + content: '{"data":{"id":"01m5cdfjp0cmx0zgvvy8a4z5zj","name":"Justina Gaylord","email":"cormier.nick@example.com","email_verified_at":"2026-10-20T10:24:59+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' headers: [] description: 'Login succeeded.' - @@ -185,7 +185,7 @@ endpoints: subgroup: 'Password Reset' subgroupDescription: '' title: 'Request Password Reset' - description: 'Send a password reset link to the provided email if an account exists.' + description: 'Email a password reset link to an address, if an account uses it. Use it from a forgot-password form. The response is the same whether or not the account exists, so it cannot be used to discover accounts; send an Idempotency-Key so a retry does not send a second email.' authenticated: false deprecated: false headers: @@ -217,6 +217,18 @@ endpoints: content: '{"message":"If the account exists, a password reset link has been sent."}' headers: [] description: 'Password reset request accepted.' + - + custom: [] + status: 422 + content: '{"type":"https:\/\/apiguide.dev\/errors\/validation-failed","title":"Validation Failed","status":422,"detail":"The email field must be a valid email address.","errors":{"email":["The email field must be a valid email address."]}}' + headers: [] + description: 'The email was missing or not an email address.' + - + custom: [] + status: 429 + content: '{"type":"https:\/\/apiguide.dev\/errors\/rate-limit-exceeded","title":"Rate Limit Exceeded","status":429,"detail":"Too many requests. Please try again later."}' + headers: [] + description: 'Too many reset requests for this address; retry after the Retry-After header.' responseFields: [] auth: [] controller: null @@ -234,7 +246,7 @@ endpoints: subgroup: 'Password Reset' subgroupDescription: '' title: 'Reset Password' - description: 'Reset the user password using a valid reset token.' + description: 'Set a new password using the token from a password reset email. Use it to finish the forgot-password flow. Returns a confirmation message; an invalid or expired token is a 422 on the email field.' authenticated: false deprecated: false headers: @@ -325,7 +337,7 @@ endpoints: subgroup: 'Password Reset' subgroupDescription: '' title: 'Read Reset Token Payload' - description: 'Return reset token and email payload for API clients handling email reset links.' + description: 'Return the token and email from a password reset link, for a client that opens the link and shows its own reset form. It does not check the token; Reset Password does. Returns the token and the email, if the link carried one.' authenticated: false deprecated: false headers: @@ -359,32 +371,8 @@ endpoints: deprecated: false cleanQueryParameters: email: jane@example.com - bodyParameters: - token: - custom: [] - name: token - description: '' - required: true - example: architecto - type: string - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - email: - custom: [] - name: email - description: 'Must be a valid email address. Must not be greater than 255 characters.' - required: false - example: zbailey@example.net - type: string - enumValues: [] - exampleWasSpecified: false - nullable: true - deprecated: false - cleanBodyParameters: - token: architecto - email: zbailey@example.net + bodyParameters: [] + cleanBodyParameters: [] fileParameters: [] responses: - @@ -393,6 +381,12 @@ endpoints: content: '{"token":"reset-token-value","email":"jane@example.com"}' headers: [] description: 'Reset payload data.' + - + custom: [] + status: 422 + content: '{"type":"https:\/\/apiguide.dev\/errors\/validation-failed","title":"Validation Failed","status":422,"detail":"The email field must be a valid email address.","errors":{"email":["The email field must be a valid email address."]}}' + headers: [] + description: 'The email query parameter was not an email address.' responseFields: [] auth: [] controller: null @@ -410,7 +404,7 @@ endpoints: subgroup: 'Email Verification' subgroupDescription: '' title: 'Verify Email' - description: 'Verify a user email using the signed verification link parameters.' + description: "Mark the user's email as verified using the signed link from the verification email. Clients do not build this URL; they follow the one in the email, which expires. Returns a confirmation message; a link that is invalid, expired or altered is a 403." authenticated: false deprecated: false headers: @@ -444,32 +438,8 @@ endpoints: hash: 8c4f4370e5db9b5be6d0f4c95495f49f998fa32a queryParameters: [] cleanQueryParameters: [] - bodyParameters: - id: - custom: [] - name: id - description: 'Must match an existing stored value.' - required: true - example: architecto - type: string - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - hash: - custom: [] - name: hash - description: 'Must be 40 characters.' - required: true - example: ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld - type: string - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - cleanBodyParameters: - id: architecto - hash: ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld + bodyParameters: [] + cleanBodyParameters: [] fileParameters: [] responses: - @@ -501,7 +471,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'Get Current User' - description: 'Return the authenticated user for the current bearer token.' + description: "Return the user the bearer token belongs to. Use it to check a token still works and to read the account's profile and verification state. The response carries an ETag: send it back in If-None-Match and an unchanged user returns 304 with no body." authenticated: true deprecated: false headers: @@ -519,7 +489,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cb6htrjmdsahn6h774frrz","name":"Morgan Hirthe","email":"dare.emelie@example.com","email_verified_at":"2026-10-20T09:45:06+00:00","created_at":null,"updated_at":null}}' + content: '{"data":{"id":"01m5cdfjpm8vqdmrdwtq6fqe98","name":"Morgan Hirthe","email":"dare.emelie@example.com","email_verified_at":"2026-10-20T10:24:59+00:00","created_at":null,"updated_at":null}}' headers: [] description: 'Authenticated user profile.' - @@ -548,7 +518,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: Logout - description: 'Revoke the current Sanctum token.' + description: "Revoke the bearer token that made this request, and only that one. Use it when a client signs out; the user's other tokens keep working. Returns 204 with no body." authenticated: true deprecated: false headers: @@ -572,7 +542,7 @@ endpoints: - custom: [] status: 401 - content: '{"message":"Unauthenticated."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' headers: [] description: 'Authentication failed.' responseFields: [] @@ -595,7 +565,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'List Tokens' - description: 'List personal access tokens for the authenticated user.' + description: 'List the authenticated user''s personal access tokens, newest first, 25 to a page. Use it to show signed-in devices or to find a token ID to revoke. Returns an array of tokens, with is_current marking the one making the request; follow the Link header''s rel="next" for the next page.' authenticated: true deprecated: false headers: @@ -648,6 +618,105 @@ endpoints: controller: null method: null route: null + - + custom: [] + httpMethods: + - POST + uri: v1/auth/tokens + metadata: + custom: [] + groupName: Authentication + groupDescription: '' + subgroup: 'Token Authentication' + subgroupDescription: '' + title: 'Create API Key' + description: 'Create a long-lived personal access token with chosen abilities, for a script, integration or agent that should not sign in with a password. It can only hold abilities the token making this request holds, and expires on expires_at, or after the configured default when that is left out. Returns the token with its plain-text value in meta.token, which is shown once and cannot be read again.' + authenticated: true + deprecated: false + headers: + Authorization: 'Bearer {YOUR_BEARER_TOKEN}' + Content-Type: application/json + Accept: application/json + urlParameters: [] + cleanUrlParameters: [] + queryParameters: [] + cleanQueryParameters: [] + bodyParameters: + name: + custom: [] + name: name + description: 'A label for the key, shown when listing tokens.' + required: true + example: deploy-bot + type: string + enumValues: [] + exampleWasSpecified: false + nullable: false + deprecated: false + abilities: + custom: [] + name: abilities + description: 'Abilities to grant, each one held by the token making this request.' + required: true + example: + - 'auth:me' + - 'auth:tokens:read' + type: 'string[]' + enumValues: [] + exampleWasSpecified: false + nullable: false + deprecated: false + expires_at: + custom: [] + name: expires_at + description: 'ISO 8601 expiry, in the future and no later than the configured maximum (365 days by default). Leave it out for the default (90 days).' + required: false + example: '2027-01-01T00:00:00+00:00' + type: string + enumValues: [] + exampleWasSpecified: false + nullable: false + deprecated: false + cleanBodyParameters: + name: deploy-bot + abilities: + - 'auth:me' + - 'auth:tokens:read' + expires_at: '2027-01-01T00:00:00+00:00' + fileParameters: [] + responses: + - + custom: [] + status: 201 + content: '{"data":{"id":"7","name":"deploy-bot","abilities":["auth:me","auth:tokens:read"],"last_used_at":null,"expires_at":"2027-01-01T00:00:00+00:00","created_at":"2026-10-20T12:00:00+00:00","updated_at":"2026-10-20T12:00:00+00:00","is_current":false},"meta":{"token":"7|example-token","token_type":"Bearer"}}' + headers: [] + description: 'API key created. meta.token is the only time its value is returned.' + - + custom: [] + status: 401 + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' + headers: [] + description: 'Authentication failed.' + - + custom: [] + status: 403 + content: '{"type":"https:\/\/apiguide.dev\/errors\/forbidden","title":"Forbidden","status":403,"detail":"Forbidden."}' + headers: [] + description: 'Token is missing the auth:tokens:create ability.' + - + custom: [] + status: 422 + content: '{"type":"https:\/\/apiguide.dev\/errors\/validation-failed","title":"Validation Failed","status":422,"detail":"You can only grant abilities your current token holds.","errors":{"abilities.0":["You can only grant abilities your current token holds."]}}' + headers: [] + description: 'A requested ability is not held by this token, or the expiry is invalid.' + responseFields: [] + auth: + - headers + - Authorization + - 'Bearer 6g43cv8PD1aE5beadkZfhV6' + controller: null + method: null + route: null - custom: [] httpMethods: @@ -660,7 +729,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'Revoke All Tokens' - description: 'Revoke all personal access tokens for the authenticated user.' + description: 'Revoke every personal access token the authenticated user holds, including the one making this request. Use it to sign out everywhere after a suspected compromise. Returns 204 with no body; every later request with these tokens is a 401.' authenticated: true deprecated: false headers: @@ -684,13 +753,13 @@ endpoints: - custom: [] status: 401 - content: '{"message":"Unauthenticated."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' headers: [] description: 'Authentication failed.' - custom: [] status: 403 - content: '{"message":"Forbidden."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/forbidden","title":"Forbidden","status":403,"detail":"Forbidden."}' headers: [] description: 'Token is missing required ability.' responseFields: [] @@ -713,7 +782,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'Revoke Token' - description: 'Revoke one personal access token owned by the authenticated user.' + description: "Revoke one of the authenticated user's personal access tokens by its ID, such as a lost device's. Use List Tokens to find the ID. Returns 204 with no body; a token the user does not own, or that no longer exists, is a 404." authenticated: true deprecated: false headers: @@ -736,20 +805,8 @@ endpoints: token_id: 42 queryParameters: [] cleanQueryParameters: [] - bodyParameters: - token_id: - custom: [] - name: token_id - description: '' - required: true - example: 16 - type: integer - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - cleanBodyParameters: - token_id: 16 + bodyParameters: [] + cleanBodyParameters: [] fileParameters: [] responses: - @@ -761,19 +818,19 @@ endpoints: - custom: [] status: 401 - content: '{"message":"Unauthenticated."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' headers: [] description: 'Authentication failed.' - custom: [] status: 403 - content: '{"message":"Forbidden."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/forbidden","title":"Forbidden","status":403,"detail":"Forbidden."}' headers: [] description: 'Token is missing required ability.' - custom: [] status: 404 - content: '{"message":"Token not found."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/resource-not-found","title":"Resource Not Found","status":404,"detail":"Token not found."}' headers: [] description: 'Token does not belong to current user or no longer exists.' responseFields: [] @@ -796,7 +853,7 @@ endpoints: subgroup: 'Email Verification' subgroupDescription: '' title: 'Send Verification Email' - description: 'Send (or resend) an email verification link to the authenticated user.' + description: 'Send the authenticated user a new email verification link. Use it when the first link expired or never arrived; it is limited to six requests a minute. Returns a message saying the link was sent, or that the email is already verified.' authenticated: true deprecated: false headers: diff --git a/.scribe/endpoints/00.yaml b/.scribe/endpoints/00.yaml index 7c11609..d0750aa 100644 --- a/.scribe/endpoints/00.yaml +++ b/.scribe/endpoints/00.yaml @@ -13,7 +13,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: Register - description: 'Create a new account and issue a Sanctum bearer token.' + description: 'Create an account and issue its first bearer token. Use it once per new user; send an Idempotency-Key so a retried request cannot create a second account. Returns the user with the token, its type and expiry in meta, and sends a verification email.' authenticated: false deprecated: false headers: @@ -78,7 +78,7 @@ endpoints: - custom: [] status: 201 - content: '{"data":{"id":"01m5cb6hssde51qe3kn813thmv","name":"Justina Gaylord","email":"lafayette.considine@example.com","email_verified_at":"2026-10-20T09:45:06+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' + content: '{"data":{"id":"01m5cdfjnp16kbfqq3s4xsnvb5","name":"Justina Gaylord","email":"lafayette.considine@example.com","email_verified_at":"2026-10-20T10:24:59+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' headers: [] description: 'Registration succeeded.' - @@ -104,7 +104,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: Login - description: 'Authenticate a user and issue a Sanctum bearer token.' + description: 'Exchange an email and password for a bearer token. Use it when a user signs in on a new device, naming the device in device_name. Returns the user with the token, its type and expiry in meta; wrong credentials are a 422 on the email field.' authenticated: false deprecated: false headers: @@ -157,7 +157,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cb6ht2em5q96y8t1rffqv6","name":"Justina Gaylord","email":"cormier.nick@example.com","email_verified_at":"2026-10-20T09:45:06+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' + content: '{"data":{"id":"01m5cdfjp0cmx0zgvvy8a4z5zj","name":"Justina Gaylord","email":"cormier.nick@example.com","email_verified_at":"2026-10-20T10:24:59+00:00","created_at":null,"updated_at":null},"meta":{"token":"1|example-token","token_type":"Bearer","expires_at":null}}' headers: [] description: 'Login succeeded.' - @@ -183,7 +183,7 @@ endpoints: subgroup: 'Password Reset' subgroupDescription: '' title: 'Request Password Reset' - description: 'Send a password reset link to the provided email if an account exists.' + description: 'Email a password reset link to an address, if an account uses it. Use it from a forgot-password form. The response is the same whether or not the account exists, so it cannot be used to discover accounts; send an Idempotency-Key so a retry does not send a second email.' authenticated: false deprecated: false headers: @@ -215,6 +215,18 @@ endpoints: content: '{"message":"If the account exists, a password reset link has been sent."}' headers: [] description: 'Password reset request accepted.' + - + custom: [] + status: 422 + content: '{"type":"https:\/\/apiguide.dev\/errors\/validation-failed","title":"Validation Failed","status":422,"detail":"The email field must be a valid email address.","errors":{"email":["The email field must be a valid email address."]}}' + headers: [] + description: 'The email was missing or not an email address.' + - + custom: [] + status: 429 + content: '{"type":"https:\/\/apiguide.dev\/errors\/rate-limit-exceeded","title":"Rate Limit Exceeded","status":429,"detail":"Too many requests. Please try again later."}' + headers: [] + description: 'Too many reset requests for this address; retry after the Retry-After header.' responseFields: [] auth: [] controller: null @@ -232,7 +244,7 @@ endpoints: subgroup: 'Password Reset' subgroupDescription: '' title: 'Reset Password' - description: 'Reset the user password using a valid reset token.' + description: 'Set a new password using the token from a password reset email. Use it to finish the forgot-password flow. Returns a confirmation message; an invalid or expired token is a 422 on the email field.' authenticated: false deprecated: false headers: @@ -323,7 +335,7 @@ endpoints: subgroup: 'Password Reset' subgroupDescription: '' title: 'Read Reset Token Payload' - description: 'Return reset token and email payload for API clients handling email reset links.' + description: 'Return the token and email from a password reset link, for a client that opens the link and shows its own reset form. It does not check the token; Reset Password does. Returns the token and the email, if the link carried one.' authenticated: false deprecated: false headers: @@ -357,32 +369,8 @@ endpoints: deprecated: false cleanQueryParameters: email: jane@example.com - bodyParameters: - token: - custom: [] - name: token - description: '' - required: true - example: architecto - type: string - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - email: - custom: [] - name: email - description: 'Must be a valid email address. Must not be greater than 255 characters.' - required: false - example: zbailey@example.net - type: string - enumValues: [] - exampleWasSpecified: false - nullable: true - deprecated: false - cleanBodyParameters: - token: architecto - email: zbailey@example.net + bodyParameters: [] + cleanBodyParameters: [] fileParameters: [] responses: - @@ -391,6 +379,12 @@ endpoints: content: '{"token":"reset-token-value","email":"jane@example.com"}' headers: [] description: 'Reset payload data.' + - + custom: [] + status: 422 + content: '{"type":"https:\/\/apiguide.dev\/errors\/validation-failed","title":"Validation Failed","status":422,"detail":"The email field must be a valid email address.","errors":{"email":["The email field must be a valid email address."]}}' + headers: [] + description: 'The email query parameter was not an email address.' responseFields: [] auth: [] controller: null @@ -408,7 +402,7 @@ endpoints: subgroup: 'Email Verification' subgroupDescription: '' title: 'Verify Email' - description: 'Verify a user email using the signed verification link parameters.' + description: "Mark the user's email as verified using the signed link from the verification email. Clients do not build this URL; they follow the one in the email, which expires. Returns a confirmation message; a link that is invalid, expired or altered is a 403." authenticated: false deprecated: false headers: @@ -442,32 +436,8 @@ endpoints: hash: 8c4f4370e5db9b5be6d0f4c95495f49f998fa32a queryParameters: [] cleanQueryParameters: [] - bodyParameters: - id: - custom: [] - name: id - description: 'Must match an existing stored value.' - required: true - example: architecto - type: string - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - hash: - custom: [] - name: hash - description: 'Must be 40 characters.' - required: true - example: ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld - type: string - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - cleanBodyParameters: - id: architecto - hash: ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld + bodyParameters: [] + cleanBodyParameters: [] fileParameters: [] responses: - @@ -499,7 +469,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'Get Current User' - description: 'Return the authenticated user for the current bearer token.' + description: "Return the user the bearer token belongs to. Use it to check a token still works and to read the account's profile and verification state. The response carries an ETag: send it back in If-None-Match and an unchanged user returns 304 with no body." authenticated: true deprecated: false headers: @@ -517,7 +487,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cb6htrjmdsahn6h774frrz","name":"Morgan Hirthe","email":"dare.emelie@example.com","email_verified_at":"2026-10-20T09:45:06+00:00","created_at":null,"updated_at":null}}' + content: '{"data":{"id":"01m5cdfjpm8vqdmrdwtq6fqe98","name":"Morgan Hirthe","email":"dare.emelie@example.com","email_verified_at":"2026-10-20T10:24:59+00:00","created_at":null,"updated_at":null}}' headers: [] description: 'Authenticated user profile.' - @@ -546,7 +516,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: Logout - description: 'Revoke the current Sanctum token.' + description: "Revoke the bearer token that made this request, and only that one. Use it when a client signs out; the user's other tokens keep working. Returns 204 with no body." authenticated: true deprecated: false headers: @@ -570,7 +540,7 @@ endpoints: - custom: [] status: 401 - content: '{"message":"Unauthenticated."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' headers: [] description: 'Authentication failed.' responseFields: [] @@ -593,7 +563,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'List Tokens' - description: 'List personal access tokens for the authenticated user.' + description: 'List the authenticated user''s personal access tokens, newest first, 25 to a page. Use it to show signed-in devices or to find a token ID to revoke. Returns an array of tokens, with is_current marking the one making the request; follow the Link header''s rel="next" for the next page.' authenticated: true deprecated: false headers: @@ -646,6 +616,105 @@ endpoints: controller: null method: null route: null + - + custom: [] + httpMethods: + - POST + uri: v1/auth/tokens + metadata: + custom: [] + groupName: Authentication + groupDescription: '' + subgroup: 'Token Authentication' + subgroupDescription: '' + title: 'Create API Key' + description: 'Create a long-lived personal access token with chosen abilities, for a script, integration or agent that should not sign in with a password. It can only hold abilities the token making this request holds, and expires on expires_at, or after the configured default when that is left out. Returns the token with its plain-text value in meta.token, which is shown once and cannot be read again.' + authenticated: true + deprecated: false + headers: + Authorization: 'Bearer {YOUR_BEARER_TOKEN}' + Content-Type: application/json + Accept: application/json + urlParameters: [] + cleanUrlParameters: [] + queryParameters: [] + cleanQueryParameters: [] + bodyParameters: + name: + custom: [] + name: name + description: 'A label for the key, shown when listing tokens.' + required: true + example: deploy-bot + type: string + enumValues: [] + exampleWasSpecified: false + nullable: false + deprecated: false + abilities: + custom: [] + name: abilities + description: 'Abilities to grant, each one held by the token making this request.' + required: true + example: + - 'auth:me' + - 'auth:tokens:read' + type: 'string[]' + enumValues: [] + exampleWasSpecified: false + nullable: false + deprecated: false + expires_at: + custom: [] + name: expires_at + description: 'ISO 8601 expiry, in the future and no later than the configured maximum (365 days by default). Leave it out for the default (90 days).' + required: false + example: '2027-01-01T00:00:00+00:00' + type: string + enumValues: [] + exampleWasSpecified: false + nullable: false + deprecated: false + cleanBodyParameters: + name: deploy-bot + abilities: + - 'auth:me' + - 'auth:tokens:read' + expires_at: '2027-01-01T00:00:00+00:00' + fileParameters: [] + responses: + - + custom: [] + status: 201 + content: '{"data":{"id":"7","name":"deploy-bot","abilities":["auth:me","auth:tokens:read"],"last_used_at":null,"expires_at":"2027-01-01T00:00:00+00:00","created_at":"2026-10-20T12:00:00+00:00","updated_at":"2026-10-20T12:00:00+00:00","is_current":false},"meta":{"token":"7|example-token","token_type":"Bearer"}}' + headers: [] + description: 'API key created. meta.token is the only time its value is returned.' + - + custom: [] + status: 401 + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' + headers: [] + description: 'Authentication failed.' + - + custom: [] + status: 403 + content: '{"type":"https:\/\/apiguide.dev\/errors\/forbidden","title":"Forbidden","status":403,"detail":"Forbidden."}' + headers: [] + description: 'Token is missing the auth:tokens:create ability.' + - + custom: [] + status: 422 + content: '{"type":"https:\/\/apiguide.dev\/errors\/validation-failed","title":"Validation Failed","status":422,"detail":"You can only grant abilities your current token holds.","errors":{"abilities.0":["You can only grant abilities your current token holds."]}}' + headers: [] + description: 'A requested ability is not held by this token, or the expiry is invalid.' + responseFields: [] + auth: + - headers + - Authorization + - 'Bearer 6g43cv8PD1aE5beadkZfhV6' + controller: null + method: null + route: null - custom: [] httpMethods: @@ -658,7 +727,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'Revoke All Tokens' - description: 'Revoke all personal access tokens for the authenticated user.' + description: 'Revoke every personal access token the authenticated user holds, including the one making this request. Use it to sign out everywhere after a suspected compromise. Returns 204 with no body; every later request with these tokens is a 401.' authenticated: true deprecated: false headers: @@ -682,13 +751,13 @@ endpoints: - custom: [] status: 401 - content: '{"message":"Unauthenticated."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' headers: [] description: 'Authentication failed.' - custom: [] status: 403 - content: '{"message":"Forbidden."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/forbidden","title":"Forbidden","status":403,"detail":"Forbidden."}' headers: [] description: 'Token is missing required ability.' responseFields: [] @@ -711,7 +780,7 @@ endpoints: subgroup: 'Token Authentication' subgroupDescription: '' title: 'Revoke Token' - description: 'Revoke one personal access token owned by the authenticated user.' + description: "Revoke one of the authenticated user's personal access tokens by its ID, such as a lost device's. Use List Tokens to find the ID. Returns 204 with no body; a token the user does not own, or that no longer exists, is a 404." authenticated: true deprecated: false headers: @@ -734,20 +803,8 @@ endpoints: token_id: 42 queryParameters: [] cleanQueryParameters: [] - bodyParameters: - token_id: - custom: [] - name: token_id - description: '' - required: true - example: 16 - type: integer - enumValues: [] - exampleWasSpecified: false - nullable: false - deprecated: false - cleanBodyParameters: - token_id: 16 + bodyParameters: [] + cleanBodyParameters: [] fileParameters: [] responses: - @@ -759,19 +816,19 @@ endpoints: - custom: [] status: 401 - content: '{"message":"Unauthenticated."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/unauthorized","title":"Unauthorized","status":401,"detail":"Unauthenticated."}' headers: [] description: 'Authentication failed.' - custom: [] status: 403 - content: '{"message":"Forbidden."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/forbidden","title":"Forbidden","status":403,"detail":"Forbidden."}' headers: [] description: 'Token is missing required ability.' - custom: [] status: 404 - content: '{"message":"Token not found."}' + content: '{"type":"https:\/\/apiguide.dev\/errors\/resource-not-found","title":"Resource Not Found","status":404,"detail":"Token not found."}' headers: [] description: 'Token does not belong to current user or no longer exists.' responseFields: [] @@ -794,7 +851,7 @@ endpoints: subgroup: 'Email Verification' subgroupDescription: '' title: 'Send Verification Email' - description: 'Send (or resend) an email verification link to the authenticated user.' + description: 'Send the authenticated user a new email verification link. Use it when the first link expired or never arrived; it is limited to six requests a minute. Returns a message saying the link was sent, or that the email is already verified.' authenticated: true deprecated: false headers: diff --git a/AGENTS.md b/AGENTS.md index 85d9ad1..82c5c42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,15 +12,32 @@ this file is how to change it. composer lint # Pint, the PER preset plus the rules in pint.json composer stan # PHPStan with Larastan at level 10 php artisan test # Pest, including the OpenAPI contract tests +legible check public/docs/openapi.yaml # agent readiness, against .legible.yaml ``` -CI runs all three. A change that fails any of them is not finished. Fix style with +CI runs all four, and builds and boots the production image. A change that fails any of them is +not finished. [legible](https://github.com/JustSteveKing/legible) is a single binary from its +releases; CI pins the version in `.github/workflows/ci-tests.yml`. Fix style with `vendor/bin/pint --dirty`, never by loosening `pint.json` or `phpstan.neon`. ## Adding an endpoint -Every endpoint is the same six pieces. Copy the nearest existing one in -`app/Http/Controllers/Api/V1/Auth/` rather than starting from a blank file. +Start with the generator, never a blank file: + +```bash +php artisan make:endpoint Projects/CreateProject --method=POST --uri=/projects +php artisan make:endpoint Projects/ShowProject --method=GET --uri=/projects/{project} +``` + +It writes the six pieces below, appends the route, formats them with Pint and prints the steps it +leaves to you. `--ability=` overrides the default (`projects:write`, or `projects:read` for a GET), +`--guest` leaves the route public, and `--force` overwrites. The templates are in +`stubs/endpoint/`. + +What it cannot know stays visible until you write it: the controller answers `501`, path +parameters carry a TODO to constrain them, and the description is three TODO sentences. CI fails +while any of that documentation remains, through `OpenApiContractTest` and legible, so finish every +TODO before calling the endpoint done. The pieces, and what to put in each: 1. **Route** in `routes/api/v1.php`. URLs have no `/api` prefix: `routes/api/routes.php` adds `v1`. Name it `v1.{domain}.{action}`. Protected routes sit behind `auth:sanctum`, a named rate limiter @@ -38,11 +55,18 @@ Every endpoint is the same six pieces. Copy the nearest existing one in goes into `sanctum.abilities.default` in `config/sanctum.php`, or no token issued at login can call the route. -2. **Form Request** in `app/Http/Requests/{Domain}/`: final, `authorize()` and `rules()` only. + Path parameters are validated here, by route constraints (`whereNumber`, `whereUlid`, + `where('slug', '[a-z0-9-]+')`), never by the Form Request. A Form Request that validates a path + parameter documents it as a body field too, which legible reports as an argument collision. + +2. **Form Request** in `app/Http/Requests/{Domain}/`: final, `authorize()` and `rules()` for body or + query input only. A GET's Form Request also has a `queryParameters()` method, or Scribe documents + its rules as a request body. A DELETE usually needs none. 3. **Payload** in `app/Http/Payloads/V1/`: a `final readonly` class with `fromRequest()` that reads - the validated data with typed accessors (`Arr::string()`, `Arr::integer()`), never casts from - `mixed`. Controllers work with the payload, not with `$request->input()`. + the validated data with typed accessors (`Arr::string()`, `Arr::integer()`) and path parameters + with `App\Http\Payloads\RouteParameter`, never casting from `mixed`. Controllers work with the + payload, not with `$request->input()`. 4. **Controller** in `app/Http/Controllers/Api/V1/{Domain}/`: final, invokable, no base class. Document it with Scribe attributes, not docblocks: `#[Group]`, `#[Endpoint]`, a `#[BodyParam]` or @@ -66,7 +90,11 @@ php artisan scribe:generate --no-interaction `OpenApiContractTest` compares every `v1/` route with the generated spec, so a route Scribe cannot see fails the build. Scribe documents a route even without attributes, though, so the attributes -are what make its documentation worth reading. +are what make its documentation worth reading: legible fails a one-sentence description, an error +status with no documented response, and a description shared by two operations. + +An endpoint whose validation problems carry `errors` joins the `error-shape` ignore in +`.legible.yaml`, which says why. ## Errors @@ -127,8 +155,14 @@ client can read goes through `__()`: - Call `SecurityAudit::log('domain.action.outcome', [...])` for anything security-relevant: sign-in, tokens, permission changes, destructive actions. Log IDs and `SecurityAudit::hashEmail()`, never raw emails, passwords or tokens. -- Grant each token the least it needs: one ability per endpoint group, added to the defaults only if - every client needs it. +- Grant each token the least it needs. Every ability a route checks is listed in + `sanctum.abilities.available`; session tokens from register and login get + `sanctum.abilities.default`. Add a new ability to the first, and to the second only if every + signed-in client needs it. +- Machines get API keys, not passwords: `POST /v1/auth/tokens` creates a key holding a subset of the + calling token's abilities, expiring within `API_KEY_MAX_DAYS`. Issue tokens through + `App\Support\AccessTokens`, which sets every token's own `expires_at`; `sanctum.expiration` is + off on purpose, or no key could outlive a session. - `ProductionSecurityChecks` refuses to boot in production without HTTPS enforcement, a `https://` `APP_URL`, `APP_DEBUG=false`, explicit CORS origins and trusted hosts. Configure them; do not remove the check. @@ -143,6 +177,19 @@ client can read goes through `__()`: matching it by hand. - User IDs are ULIDs, so treat them as strings. +## Running in production + +The `Dockerfile` runs Octane on FrankenPHP: the application stays in memory between requests. + +- Keep request state out of singletons and static properties. Use `scoped()` bindings, which Octane + resets per request, as api-toolbox does for its request ID and trace. +- Resolve request state when the request is served, not in a closure that captured the + application at boot: Octane serves each request from a sandboxed copy of it. +- Emails are queued, so production needs a worker as well as the server: the same image runs one + with `php artisan queue:work`. Locally, run `php artisan queue:work` beside `php artisan serve`. +- Dev packages are not installed in the image. Config that references one, as `config/scribe.php` + does, must return early without it; the image build in CI fails otherwise. + ## Dependencies [Laravel Vet](https://github.com/laravel/vet) guards `composer install`: `vet.json` records every @@ -151,6 +198,9 @@ package someone has read, and releases younger than 7 days are held back. - Do not add or upgrade a package without being asked to. - After `composer require` or `composer update`, run `./vendor/bin/vet` in a terminal, review each change (or have it handed to you to read), and commit `vet.json` with `composer.lock`. +- `laravel/*` packages are trusted by policy: they skip the release-age hold, and when they are the + only packages that changed, record them with `./vendor/bin/vet --fresh` rather than reviewing + them. The weekly bot does exactly that. Anything else that changed alongside them is reviewed. - Never edit `vet.json` by hand, and never use `--no-plugins` to get past Vet. The one exception is the documented review of a bot PR, which installs the new lock without the plugin precisely so that Vet can audit it. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..df0a422 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,44 @@ +# syntax=docker/dockerfile:1 + +# Production image: Laravel Octane on FrankenPHP, one process serving HTTP on port 8000. +# The same image runs a queue worker: `docker run php artisan queue:work`. +FROM dunglas/frankenphp:1.13.1-php8.5-trixie AS base + +RUN install-php-extensions intl opcache pcntl pdo_mysql pdo_pgsql zip + +WORKDIR /app + +# Dependencies without dev packages. Vet audited this lock in CI, where it is installed with dev +# packages and the plugin enabled; production installs a subset of the same trusted lock. +FROM base AS vendor + +COPY --from=composer:2.9 /usr/bin/composer /usr/bin/composer +COPY composer.json composer.lock ./ +RUN composer install --no-dev --no-scripts --no-autoloader --no-interaction --prefer-dist --no-progress + +COPY . . +RUN composer dump-autoload --no-dev --classmap-authoritative --no-scripts \ + && APP_ENV=build php artisan package:discover --ansi \ + && cp vendor/laravel/octane/src/Commands/stubs/frankenphp-worker.php public/frankenphp-worker.php + +FROM base + +ENV APP_ENV=production \ + APP_DEBUG=false \ + LOG_CHANNEL=stderr \ + OCTANE_SERVER=frankenphp \ + PHP_INI_SCAN_DIR=":$PHP_INI_DIR/app.conf.d" + +COPY docker/php.ini $PHP_INI_DIR/app.conf.d/app.ini +COPY --from=vendor /app /app + +RUN useradd --create-home --uid 1000 app \ + && chown -R app:app /app/storage /app/bootstrap/cache /data/caddy /config/caddy + +USER app + +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=3s --start-period=10s CMD ["php", "docker/healthcheck.php"] + +ENTRYPOINT ["docker/entrypoint.sh"] diff --git a/README.md b/README.md index 5886aa2..1f95c5f 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,8 @@ API design, HTTP standards, documentation, testing and security. - PHP `8.5` + Laravel `13` - SQLite-first local development (`DB_CONNECTION=sqlite`) -- Sanctum personal access token authentication +- Sanctum token authentication: session tokens on sign-in, and scoped, long-lived API keys for + scripts, integrations and agents - Versioned API routes with no `/api` prefix (`/v1/...`) - Invokable controllers only - Form Request validation + DTO-style request payload objects @@ -22,7 +23,10 @@ API design, HTTP standards, documentation, testing and security. - An RFC 9727 API catalog at `/.well-known/api-catalog` - API localization via `Accept-Language` + `Content-Language` - Scribe (attribute-based) API docs + OpenAPI generation -- OpenAPI contract tests to keep docs and runtime behaviour in sync +- OpenAPI contract tests to keep docs and runtime behaviour in sync, and a + [legible](https://github.com/JustSteveKing/legible) gate that keeps the spec agent-ready +- `php artisan make:endpoint` scaffolds an endpoint the way the rest of Kit is built +- A production image: Laravel Octane on FrankenPHP, with the same image as the queue worker - GitHub Actions for style, static analysis, tests, security audits and weekly, Vet-audited dependency update PRs - An [`AGENTS.md`](AGENTS.md) that tells coding agents, and you, how to build on Kit the way it is built @@ -34,7 +38,7 @@ API design, HTTP standards, documentation, testing and security. - HTTP standards: `juststeveking/api-toolbox` - Docs/OpenAPI: `knuckleswtf/scribe` (attributes, not docblocks) - Test Runner: Pest + Laravel test tooling -- Static Analysis / Quality: PHPStan (Larastan, level 10), Pint, Rector +- Static Analysis / Quality: PHPStan (Larastan, level 10), Pint ## Quick Start @@ -73,8 +77,11 @@ composer run setup ```bash php artisan serve +php artisan queue:work # in a second terminal: verification and reset emails are queued ``` +Mail goes to the log (`MAIL_MAILER=log`) until you configure a mailer. + API base path is versioned and has no global `/api` prefix: - `http://127.0.0.1:8000/v1/...` @@ -97,6 +104,7 @@ Framework routing is configured with `apiPrefix: ''` in `bootstrap/app.php`, so | GET | `/v1/auth/me` | Bearer | Current authenticated user | | POST | `/v1/auth/logout` | Bearer | Revoke current token | | GET | `/v1/auth/tokens` | Bearer | List the user's tokens, cursor paginated | +| POST | `/v1/auth/tokens` | Bearer | Create an API key with chosen abilities | | DELETE | `/v1/auth/tokens` | Bearer | Revoke every token | | DELETE | `/v1/auth/tokens/{token_id}` | Bearer | Revoke one token | | POST | `/v1/auth/email/verification-notification` | Bearer | Send/resend verification email | @@ -199,7 +207,8 @@ Relevant config/env: - `APP_LOCALE` - `APP_FALLBACK_LOCALE` - `APP_SUPPORTED_LOCALES` (default: `en,es`) -- `SANCTUM_EXPIRATION` (default: `120` minutes) +- `SANCTUM_EXPIRATION`: session token lifetime (default: `120` minutes) +- `API_KEY_DEFAULT_DAYS` / `API_KEY_MAX_DAYS`: API key lifetime (defaults: `90` / `365` days) ## Architecture Conventions @@ -210,15 +219,46 @@ Relevant config/env: - Entity output lives in plain API resources (`app/Http/Resources`) - HTTP standards are switched on in `config/api-toolbox.php`, one feature per standard -[AGENTS.md](AGENTS.md#adding-an-endpoint) walks through adding an endpoint end to end: route, -ability and rate limit, Form Request, payload, controller with its Scribe attributes, resource, -tests, and regenerated docs. +## Adding Endpoints + +```bash +php artisan make:endpoint Projects/CreateProject --method=POST --uri=/projects +``` + +The generator writes the controller with its Scribe attributes and documented problems, the Form +Request, the payload, a Pest test whose authentication and ability cases pass straight away, and +the route with auth, rate limit, ability and name (plus `idempotent` on a POST). It leaves what it +cannot know as TODO: the controller answers `501`, and CI fails while the documentation still says +TODO, so an endpoint cannot ship half written. Change what it generates in `stubs/endpoint/`. + +[AGENTS.md](AGENTS.md#adding-an-endpoint) covers each piece and the steps the generator prints for +you: the ability in `config/sanctum.php`, the contract test's runtime check, and the docs. + +## API Keys + +Sign-in gives a session token with the default abilities. For a script, an integration or an +agent, create an API key instead, from any token that holds `auth:tokens:create`: + +```bash +curl -X POST http://127.0.0.1:8000/v1/auth/tokens \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{"name": "deploy-bot", "abilities": ["auth:me"], "expires_at": "2027-01-01T00:00:00Z"}' +``` + +- A key can only hold abilities the token creating it holds, out of those a route checks + (`sanctum.abilities.available`), so a narrow key can never mint a broader one. +- It expires on `expires_at`, at most `API_KEY_MAX_DAYS` away, or after `API_KEY_DEFAULT_DAYS`. +- `meta.token` in the response is the only time its value is returned. Revoke it like any token. +- Send an `Idempotency-Key` and a retried request returns the same key rather than a second one. ## Security Defaults - ULID primary keys for users - Password hashing via model casts - Email verification required model contract (`MustVerifyEmail`) +- Every token carries its own expiry: session tokens after `SANCTUM_EXPIRATION` minutes, API keys + on the date they were given - Rate limits configured in `AppServiceProvider`: - `auth-register`: 10/minute per IP - `auth-login`: 10/minute per IP + email @@ -251,6 +291,10 @@ After `composer update`, review what changed and record what you trust: ./vendor/bin/vet # in a terminal: read each change, or hand them to your coding agent ``` +Laravel's own packages (`laravel/*`) are trusted by policy: they skip the 7-day hold, and when +they are the only packages an update changed, `./vendor/bin/vet --fresh` records them without a +review. The weekly bot does this itself, so a Laravel-only update PR needs no review. + Commit `vet.json` with `composer.lock`. If you build your own project from Kit, `vet.json` is the trust Kit recorded; run `./vendor/bin/vet --fresh` to take it over as your own, or remove `laravel/vet` if you do not want the gate. @@ -302,13 +346,32 @@ Behaviour: - `GET /v1/auth/me` sends an `ETag`; repeat the request with `If-None-Match` and an unchanged user gets `304 Not Modified` +## Deployment + +The `Dockerfile` builds a production image: Laravel Octane on FrankenPHP, PHP 8.5, running as a +non-root user on port 8000, with OPcache tuned for production and a health check on `/up`. + +```bash +docker build -t my-api . +docker run -p 8000:8000 --env-file .env.production my-api # the API +docker run --env-file .env.production my-api php artisan queue:work # a queue worker +``` + +At start the container caches config, routes and events from its environment. Production refuses +to boot without `APP_KEY`, an `https://` `APP_URL`, `SECURITY_FORCE_HTTPS=true`, `TRUSTED_HOSTS` +and explicit `CORS_ALLOWED_ORIGINS`; put TLS in front of it and forward `X-Forwarded-Proto`. Run +migrations as a release step (`php artisan migrate --force`). CI builds the image and boots it on +every push. + ## API Documentation (Scribe + OpenAPI) Scribe is configured for this no-prefix API shape: - Route matching uses `v1/*` prefixes (`config/scribe.php`) - Endpoints are documented via PHP attributes -- Error responses are documented as `application/problem+json` (`App\Support\ProblemDetailsOpenApiGenerator`) +- Error responses are documented as `application/problem+json` (`App\Support\ProblemDetailsOpenApiGenerator`), + and `204`s with no content (`App\Support\NoContentOpenApiGenerator`) +- Path parameters keep the names the routes give them, rather than Scribe's guessed `{id}` - OpenAPI output is generated to `public/docs/openapi.yaml`, and advertised from the API catalog at `/.well-known/api-catalog` @@ -318,6 +381,10 @@ Generate docs/spec: php artisan scribe:generate --no-interaction ``` +[legible](https://github.com/JustSteveKing/legible) scores the spec for agent readiness: what will +trip up an LLM calling the API as tools. `.legible.yaml` fails CI on any warning or a score under +95, and lists the findings accepted on purpose with the reason. + Generated artifacts: - `public/docs/index.html` @@ -376,12 +443,14 @@ Boost's block appended below Kit's guide, which it leaves alone. GitHub Actions workflows: - `.github/workflows/ci-tests.yml` - - Runs Pint, PHPStan and the test suite on every push and pull request + - Runs Pint, PHPStan, the test suite and legible on every push and pull request + - Builds the production image, boots it with production settings and makes requests to it - `.github/workflows/dependency-updates.yml` - Runs weekly, Mondays at `03:00 UTC` - Executes `composer update`, holding back releases younger than 7 days - Opens/updates PR titled `bot: dependency updates` with Vet's report of what needs review - - The PR cannot pass CI until `vet.json` is updated on its branch: check it out, run + - When only `laravel/*` packages changed, it records their trust itself and the PR needs no review + - Otherwise the PR cannot pass CI until `vet.json` is updated on its branch: check it out, run `composer install --no-plugins`, then `./vendor/bin/vet`, and commit `vet.json` - `.github/workflows/security-gate.yml` - Runs Composer security audit @@ -392,14 +461,18 @@ GitHub Actions workflows: ```text AGENTS.md how to build on Kit, for agents and people +Dockerfile the production image (Octane on FrankenPHP), with docker/ vet.json packages trusted by Laravel Vet +.legible.yaml the agent-readiness gate app/ + Console/Commands/ make:endpoint Http/ Controllers/Api/V1/Auth/ Middleware/ Payloads/V1/ Requests/Auth/ Resources/ + Notifications/ queued verification and reset emails Support/ routes/ api/ @@ -407,8 +480,10 @@ routes/ v1.php tests/ Feature/ +stubs/endpoint/ templates for make:endpoint config/ api-toolbox.php + octane.php sanctum.php scribe.php security.php diff --git a/app/Console/Commands/EndpointBlueprint.php b/app/Console/Commands/EndpointBlueprint.php new file mode 100644 index 0000000..90e184c --- /dev/null +++ b/app/Console/Commands/EndpointBlueprint.php @@ -0,0 +1,56 @@ + 'store', + 'Store' => 'store', + 'List' => 'index', + 'Index' => 'index', + 'Show' => 'show', + 'Get' => 'show', + 'Update' => 'update', + 'Delete' => 'destroy', + 'Destroy' => 'destroy', + ]; + + public function __construct( + public string $domain, + public string $action, + public string $method, + public string $uri, + public ?string $ability, + public bool $hasRequest, + ) {} + + /** + * v1.{domain}.{action}, with dashes rather than dots inside each part, and the action named the + * way Laravel's resource routes are where the verb says which one it is. + */ + public function routeName(): string + { + $verb = Str::before(Str::snake($this->action), '_'); + $action = self::ACTIONS[Str::studly($verb)] ?? Str::kebab($this->action); + + return 'v1.' . Str::kebab($this->domain) . '.' . $action; + } + + /** + * @return list + */ + public function pathParameters(): array + { + preg_match_all('/\{(\w+)\??\}/', $this->uri, $matches); + + return $matches[1]; + } +} diff --git a/app/Console/Commands/MakeEndpointCommand.php b/app/Console/Commands/MakeEndpointCommand.php new file mode 100644 index 0000000..ab57ebf --- /dev/null +++ b/app/Console/Commands/MakeEndpointCommand.php @@ -0,0 +1,405 @@ +stringArgument('name'); + + if (1 !== preg_match('/^([A-Z][A-Za-z0-9]*)\/([A-Z][A-Za-z0-9]*)$/', $name, $parts)) { + $this->components->error('The name is a domain and an action in StudlyCase, such as Projects/CreateProject.'); + + return self::FAILURE; + } + + [, $domain, $action] = $parts; + $action = Str::replaceEnd('Controller', '', $action); + $method = mb_strtoupper($this->stringOption('method') ?: 'GET'); + + if ( ! in_array($method, self::METHODS, true)) { + $this->components->error('The method is one of ' . implode(', ', self::METHODS) . '.'); + + return self::FAILURE; + } + + $uri = '/' . mb_ltrim($this->stringOption('uri') ?: Str::kebab($domain), '/'); + $guest = (bool) $this->option('guest'); + $ability = $guest ? null : ($this->stringOption('ability') ?: Str::kebab($domain) . ':' . ('GET' === $method ? 'read' : 'write')); + $hasRequest = 'DELETE' !== $method; + + $endpoint = new EndpointBlueprint($domain, $action, $method, $uri, $ability, $hasRequest); + + $files = [ + app_path("Http/Controllers/Api/V1/{$domain}/{$action}Controller.php") => $this->controller($endpoint), + base_path("tests/Feature/{$domain}/{$action}Test.php") => $this->test($endpoint), + ]; + + if ($hasRequest) { + $files[app_path("Http/Requests/{$domain}/{$action}Request.php")] = $this->request($endpoint); + $files[app_path("Http/Payloads/V1/{$action}Payload.php")] = $this->payload($endpoint); + } + + $existing = array_filter(array_keys($files), $this->files->exists(...)); + + if ([] !== $existing && ! $this->option('force')) { + $this->components->error('These files already exist; pass --force to overwrite them:'); + $this->components->bulletList(array_map($this->relative(...), $existing)); + + return self::FAILURE; + } + + foreach ($files as $path => $contents) { + $this->files->ensureDirectoryExists(dirname($path)); + $this->files->put($path, $contents); + } + + $this->addRoute($endpoint); + $this->format([...array_keys($files), base_path('routes/api/v1.php')]); + + $this->components->info("Scaffolded {$method} /v1{$uri}."); + $this->components->bulletList([...array_map($this->relative(...), array_keys($files)), 'routes/api/v1.php']); + $this->nextSteps($endpoint); + + return self::SUCCESS; + } + + /** + * @return array + */ + protected function promptForMissingArgumentsUsing(): array + { + return [ + 'name' => fn(): string => text( + label: 'Which domain and action?', + placeholder: 'Projects/CreateProject', + required: true, + ), + ]; + } + + protected function afterPromptingForMissingArguments(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output): void + { + if (null === $input->getOption('method')) { + $input->setOption('method', select('Which HTTP method?', self::METHODS, default: 'POST')); + } + + if (null === $input->getOption('uri')) { + $name = $input->getArgument('name'); + $domain = Str::before(is_string($name) ? $name : '', '/'); + $input->setOption('uri', text('Which path under /v1?', default: '/' . Str::kebab($domain), required: true)); + } + } + + private function controller(EndpointBlueprint $endpoint): string + { + $imports = [ + 'Illuminate\Http\JsonResponse', + 'Knuckles\Scribe\Attributes\Endpoint', + 'Knuckles\Scribe\Attributes\Group', + 'Knuckles\Scribe\Attributes\Response', + ]; + $attributes = []; + $parameters = []; + $body = []; + + if ($endpoint->hasRequest) { + $imports[] = "App\\Http\\Requests\\{$endpoint->domain}\\{$endpoint->action}Request"; + $imports[] = "App\\Http\\Payloads\\V1\\{$endpoint->action}Payload"; + $parameters[] = "{$endpoint->action}Request \$request"; + $body[] = " \$payload = {$endpoint->action}Payload::fromRequest(\$request);"; + $body[] = ''; + } + + foreach ($endpoint->pathParameters() as $parameter) { + $imports[] = 'Knuckles\Scribe\Attributes\UrlParam'; + $attributes[] = "#[UrlParam('{$parameter}', type: 'string', description: 'TODO: Describe {$parameter}.', required: true, example: 'TODO')]"; + } + + if (null === $endpoint->ability) { + $imports[] = 'Knuckles\Scribe\Attributes\Unauthenticated'; + $attributes[] = '#[Unauthenticated]'; + } else { + $imports[] = 'Knuckles\Scribe\Attributes\Authenticated'; + $attributes[] = '#[Authenticated]'; + $attributes[] = $this->problemAttribute(401, 'unauthorized', 'Unauthorized', 'Unauthenticated.', 'Authentication failed.'); + $attributes[] = $this->problemAttribute(403, 'forbidden', 'Forbidden', 'Forbidden.', "Token is missing the {$endpoint->ability} ability."); + } + + if ($endpoint->hasRequest) { + $attributes[] = $this->problemAttribute(422, 'validation-failed', 'Validation Failed', 'TODO: An example validation message.', 'TODO: Say what input is refused.', withErrors: true); + } + + if ([] === $parameters) { + $imports[] = 'Illuminate\Http\Request'; + $parameters[] = 'Request $request'; + } + + sort($imports); + + return $this->render('controller', [ + 'namespace' => "App\\Http\\Controllers\\Api\\V1\\{$endpoint->domain}", + 'imports' => implode("\n", array_map(static fn(string $import): string => "use {$import};", array_unique($imports))), + 'group' => Str::headline($endpoint->domain), + 'title' => Str::headline($endpoint->action), + 'attributes' => implode("\n", $attributes), + 'class' => "{$endpoint->action}Controller", + 'parameters' => implode(', ', $parameters), + 'body' => implode("\n", $body), + ]); + } + + private function request(EndpointBlueprint $endpoint): string + { + // Scribe documents a Form Request's rules as body parameters unless it has a + // queryParameters() method, and a GET has no body. + $queryParameters = 'GET' !== $endpoint->method ? '' : <<<'PHP' + + /** + * Read by Scribe, so this GET's rules are documented as query parameters, not a body. + * + * @return array + */ + public function queryParameters(): array + { + return [ + // 'status' => ['description' => 'Only projects in this status.', 'example' => 'active'], + ]; + } + +PHP; + + return $this->render('request', [ + 'namespace' => "App\\Http\\Requests\\{$endpoint->domain}", + 'class' => "{$endpoint->action}Request", + 'queryParameters' => $queryParameters, + ]); + } + + private function payload(EndpointBlueprint $endpoint): string + { + return $this->render('payload', [ + 'namespace' => 'App\Http\Payloads\V1', + 'class' => "{$endpoint->action}Payload", + ]); + } + + private function test(EndpointBlueprint $endpoint): string + { + $call = $this->testCall($endpoint); + $guardTests = ''; + + if (null !== $endpoint->ability) { + $guardTests = <<{$call} + ->assertProblem(401); +}); + +it('requires the {$endpoint->ability} ability', function (): void { + \$token = User::factory()->create()->createToken('test', ['auth:me'])->plainTextToken; + + \$this->withToken(\$token) + ->{$call} + ->assertProblem(403); +}); + +PHP; + } + + return $this->render('test', [ + 'successDescription' => mb_strtolower(Str::headline($endpoint->action)) . ' successfully', + 'method' => $endpoint->method, + 'uri' => '/v1' . $endpoint->uri, + 'abilityOrNone' => $endpoint->ability ?? 'no ability (the route is public)', + 'guardTests' => $guardTests, + ]); + } + + private function testCall(EndpointBlueprint $endpoint): string + { + $uri = preg_replace('/\{(\w+)\}/', '1', '/v1' . $endpoint->uri); + $verb = mb_strtolower($endpoint->method); + + return in_array($endpoint->method, ['POST', 'PUT', 'PATCH'], true) + ? "{$verb}Json('{$uri}', [])" + : "{$verb}Json('{$uri}')"; + } + + private function addRoute(EndpointBlueprint $endpoint): void + { + $path = base_path('routes/api/v1.php'); + $routes = $this->files->get($path); + $controller = "App\\Http\\Controllers\\Api\\V1\\{$endpoint->domain}\\{$endpoint->action}Controller"; + + $middleware = []; + + if (null !== $endpoint->ability) { + $middleware = ['auth:sanctum', 'throttle:auth-protected', "abilities:{$endpoint->ability}"]; + } + + if ('POST' === $endpoint->method) { + $middleware[] = 'idempotent'; + } + + $route = "\nRoute::" . mb_strtolower($endpoint->method) . "('{$endpoint->uri}', {$endpoint->action}Controller::class)"; + + foreach ($endpoint->pathParameters() as $parameter) { + $route .= "\n // TODO: Constrain {$parameter}, such as ->whereNumber('{$parameter}') or ->whereUlid('{$parameter}')."; + } + + if ([] !== $middleware) { + $route .= "\n ->middleware(['" . implode("', '", $middleware) . "'])"; + } + + $route .= "\n ->name('{$endpoint->routeName()}');\n"; + + $routes = preg_replace('/^(use [^;]+;\n)(?!use )/m', "$1use {$controller};\n", $routes, 1) ?? $routes; + + $this->files->put($path, mb_rtrim($routes) . "\n" . $route); + } + + /** + * Runs the project's Pint over what was written, so the output follows pint.json whatever the + * stubs look like. + * + * @param list $paths + */ + private function format(array $paths): void + { + $pint = base_path('vendor/bin/pint'); + + if ( ! $this->files->exists($pint)) { + return; + } + + Process::path(base_path())->run([PHP_BINARY, $pint, '--quiet', ...$paths]); + } + + private function nextSteps(EndpointBlueprint $endpoint): void + { + $steps = [ + 'Write the rules, the payload, the work and the response in place of each TODO and the 501.', + 'Replace the TODO description: what it does, when to call it, what it returns. CI fails while it says TODO.', + ]; + + if ([] !== $endpoint->pathParameters()) { + $steps[] = 'Constrain the path parameters in routes/api/v1.php; validate them there, not in the Form Request.'; + } + + if (null !== $endpoint->ability) { + $steps[] = "Add '{$endpoint->ability}' to sanctum.abilities.available in config/sanctum.php, and to default if every session token should hold it."; + } + + $steps[] = "Add a runtime check for {$endpoint->method} /v1{$endpoint->uri} to OpenApiContractTest."; + + if ($endpoint->hasRequest) { + $steps[] = "Add {$endpoint->method} /v1{$endpoint->uri} to the error-shape ignore in .legible.yaml: its validation problems carry errors."; + } + $steps[] = 'Run: php artisan scribe:generate, then composer stan and php artisan test.'; + + $this->newLine(); + $this->components->twoColumnDetail('Next'); + $this->components->bulletList($steps); + } + + private function problemAttribute(int $status, string $slug, string $title, string $detail, string $description, bool $withErrors = false): string + { + $errors = $withErrors ? "\n 'errors' => ['field' => ['{$detail}']]," : ''; + + return << 'https://apiguide.dev/errors/{$slug}', + 'title' => '{$title}', + 'status' => {$status}, + 'detail' => '{$detail}',{$errors} + ], + status: {$status}, + description: '{$description}', +)] +PHP; + } + + /** + * @param array $replacements + */ + private function render(string $stub, array $replacements): string + { + $path = base_path("stubs/endpoint/{$stub}.stub"); + + if ( ! $this->files->exists($path)) { + throw new InvalidArgumentException("The stub [stubs/endpoint/{$stub}.stub] is missing."); + } + + $contents = $this->files->get($path); + + foreach ($replacements as $key => $value) { + $contents = str_replace('{{ ' . $key . ' }}', $value, $contents); + } + + return $contents; + } + + private function relative(string $path): string + { + return mb_ltrim(Str::after($path, base_path()), '/'); + } + + private function stringArgument(string $name): string + { + $value = $this->argument($name); + + return is_string($value) ? mb_trim($value) : ''; + } + + private function stringOption(string $name): string + { + $value = $this->option($name); + + return is_string($value) ? mb_trim($value) : ''; + } +} diff --git a/app/Http/Controllers/Api/V1/Auth/CreateTokenController.php b/app/Http/Controllers/Api/V1/Auth/CreateTokenController.php new file mode 100644 index 0000000..be5c36f --- /dev/null +++ b/app/Http/Controllers/Api/V1/Auth/CreateTokenController.php @@ -0,0 +1,107 @@ + [ + 'id' => '7', + 'name' => 'deploy-bot', + 'abilities' => ['auth:me', 'auth:tokens:read'], + 'last_used_at' => null, + 'expires_at' => '2027-01-01T00:00:00+00:00', + 'created_at' => '2026-10-20T12:00:00+00:00', + 'updated_at' => '2026-10-20T12:00:00+00:00', + 'is_current' => false, + ], + 'meta' => ['token' => '7|example-token', 'token_type' => 'Bearer'], + ], + status: 201, + description: 'API key created. meta.token is the only time its value is returned.', +)] +#[Response( + content: [ + 'type' => 'https://apiguide.dev/errors/validation-failed', + 'title' => 'Validation Failed', + 'status' => 422, + 'detail' => 'You can only grant abilities your current token holds.', + 'errors' => ['abilities.0' => ['You can only grant abilities your current token holds.']], + ], + status: 422, + description: 'A requested ability is not held by this token, or the expiry is invalid.', +)] +#[Response( + content: [ + 'type' => 'https://apiguide.dev/errors/forbidden', + 'title' => 'Forbidden', + 'status' => 403, + 'detail' => 'Forbidden.', + ], + status: 403, + description: 'Token is missing the auth:tokens:create ability.', +)] +#[Response( + content: [ + 'type' => 'https://apiguide.dev/errors/unauthorized', + 'title' => 'Unauthorized', + 'status' => 401, + 'detail' => 'Unauthenticated.', + ], + status: 401, + description: 'Authentication failed.', +)] +final class CreateTokenController +{ + public function __invoke(CreateTokenRequest $request, #[CurrentUser] User $user, AccessTokens $tokens): JsonResponse + { + $payload = CreateTokenPayload::fromRequest($request); + + $token = $tokens->issueApiKey( + $user, + $payload->name, + $payload->abilities, + $payload->expiresAt ?? $tokens->defaultApiKeyExpiry(), + ); + + SecurityAudit::log('auth.tokens.created', [ + 'user_id' => $user->id, + 'token_id' => (string) $token->accessToken->id, + 'abilities' => $payload->abilities, + 'expires_at' => $token->accessToken->expires_at?->toAtomString(), + ]); + + return PersonalAccessTokenResource::make($token->accessToken)->additional([ + 'meta' => [ + 'token' => $token->plainTextToken, + 'token_type' => 'Bearer', + ], + ])->response()->setStatusCode(201); + } +} diff --git a/app/Http/Controllers/Api/V1/Auth/DeleteAllTokensController.php b/app/Http/Controllers/Api/V1/Auth/DeleteAllTokensController.php index 1baad1d..3b224b0 100644 --- a/app/Http/Controllers/Api/V1/Auth/DeleteAllTokensController.php +++ b/app/Http/Controllers/Api/V1/Auth/DeleteAllTokensController.php @@ -16,11 +16,32 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'Revoke All Tokens', description: 'Revoke all personal access tokens for the authenticated user.')] +#[Endpoint( + title: 'Revoke All Tokens', + description: 'Revoke every personal access token the authenticated user holds, including the one making this request. Use it to sign out everywhere after a suspected compromise. Returns 204 with no body; every later request with these tokens is a 401.', +)] #[Authenticated] #[ScribeResponse(content: null, status: 204, description: 'All tokens revoked.')] -#[ScribeResponse(content: ['message' => 'Forbidden.'], status: 403, description: 'Token is missing required ability.')] -#[ScribeResponse(content: ['message' => 'Unauthenticated.'], status: 401, description: 'Authentication failed.')] +#[ScribeResponse( + content: [ + 'type' => 'https://apiguide.dev/errors/forbidden', + 'title' => 'Forbidden', + 'status' => 403, + 'detail' => 'Forbidden.', + ], + status: 403, + description: 'Token is missing required ability.', +)] +#[ScribeResponse( + content: [ + 'type' => 'https://apiguide.dev/errors/unauthorized', + 'title' => 'Unauthorized', + 'status' => 401, + 'detail' => 'Unauthenticated.', + ], + status: 401, + description: 'Authentication failed.', +)] final class DeleteAllTokensController { public function __invoke(#[CurrentUser] User $user): Response diff --git a/app/Http/Controllers/Api/V1/Auth/DeleteTokenController.php b/app/Http/Controllers/Api/V1/Auth/DeleteTokenController.php index d92c790..b95c197 100644 --- a/app/Http/Controllers/Api/V1/Auth/DeleteTokenController.php +++ b/app/Http/Controllers/Api/V1/Auth/DeleteTokenController.php @@ -5,10 +5,10 @@ namespace App\Http\Controllers\Api\V1\Auth; use App\Http\Payloads\V1\DeleteTokenPayload; -use App\Http\Requests\Auth\DeleteTokenRequest; use App\Models\User; use App\Support\SecurityAudit; use Illuminate\Container\Attributes\CurrentUser; +use Illuminate\Http\Request; use Illuminate\Http\Response; use Knuckles\Scribe\Attributes\Authenticated; use Knuckles\Scribe\Attributes\Endpoint; @@ -19,16 +19,46 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'Revoke Token', description: 'Revoke one personal access token owned by the authenticated user.')] +#[Endpoint( + title: 'Revoke Token', + description: 'Revoke one of the authenticated user\'s personal access tokens by its ID, such as a lost device\'s. Use List Tokens to find the ID. Returns 204 with no body; a token the user does not own, or that no longer exists, is a 404.', +)] #[Authenticated] #[UrlParam('token_id', type: 'integer', description: 'Personal access token id.', required: true, example: 42)] #[ScribeResponse(content: null, status: 204, description: 'Token revoked.')] -#[ScribeResponse(content: ['message' => 'Token not found.'], status: 404, description: 'Token does not belong to current user or no longer exists.')] -#[ScribeResponse(content: ['message' => 'Forbidden.'], status: 403, description: 'Token is missing required ability.')] -#[ScribeResponse(content: ['message' => 'Unauthenticated.'], status: 401, description: 'Authentication failed.')] +#[ScribeResponse( + content: [ + 'type' => 'https://apiguide.dev/errors/resource-not-found', + 'title' => 'Resource Not Found', + 'status' => 404, + 'detail' => 'Token not found.', + ], + status: 404, + description: 'Token does not belong to current user or no longer exists.', +)] +#[ScribeResponse( + content: [ + 'type' => 'https://apiguide.dev/errors/forbidden', + 'title' => 'Forbidden', + 'status' => 403, + 'detail' => 'Forbidden.', + ], + status: 403, + description: 'Token is missing required ability.', +)] +#[ScribeResponse( + content: [ + 'type' => 'https://apiguide.dev/errors/unauthorized', + 'title' => 'Unauthorized', + 'status' => 401, + 'detail' => 'Unauthenticated.', + ], + status: 401, + description: 'Authentication failed.', +)] final class DeleteTokenController { - public function __invoke(DeleteTokenRequest $request, #[CurrentUser] User $user): Response + public function __invoke(Request $request, #[CurrentUser] User $user): Response { $payload = DeleteTokenPayload::fromRequest($request); diff --git a/app/Http/Controllers/Api/V1/Auth/ForgotPasswordController.php b/app/Http/Controllers/Api/V1/Auth/ForgotPasswordController.php index 72b1921..fb9a42f 100644 --- a/app/Http/Controllers/Api/V1/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Api/V1/Auth/ForgotPasswordController.php @@ -18,7 +18,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Password Reset')] -#[Endpoint(title: 'Request Password Reset', description: 'Send a password reset link to the provided email if an account exists.')] +#[Endpoint( + title: 'Request Password Reset', + description: 'Email a password reset link to an address, if an account uses it. Use it from a forgot-password form. The response is the same whether or not the account exists, so it cannot be used to discover accounts; send an Idempotency-Key so a retry does not send a second email.', +)] #[Unauthenticated] #[BodyParam('email', type: 'string', description: 'Account email address.', required: true, example: 'jane@example.com')] #[Response( @@ -26,6 +29,27 @@ status: 200, description: 'Password reset request accepted.', )] +#[Response( + content: [ + 'type' => 'https://apiguide.dev/errors/validation-failed', + 'title' => 'Validation Failed', + 'status' => 422, + 'detail' => 'The email field must be a valid email address.', + 'errors' => ['email' => ['The email field must be a valid email address.']], + ], + status: 422, + description: 'The email was missing or not an email address.', +)] +#[Response( + content: [ + 'type' => 'https://apiguide.dev/errors/rate-limit-exceeded', + 'title' => 'Rate Limit Exceeded', + 'status' => 429, + 'detail' => 'Too many requests. Please try again later.', + ], + status: 429, + description: 'Too many reset requests for this address; retry after the Retry-After header.', +)] final class ForgotPasswordController { public function __invoke(ForgotPasswordRequest $request): JsonResponse diff --git a/app/Http/Controllers/Api/V1/Auth/ListTokensController.php b/app/Http/Controllers/Api/V1/Auth/ListTokensController.php index fca2934..b51460a 100644 --- a/app/Http/Controllers/Api/V1/Auth/ListTokensController.php +++ b/app/Http/Controllers/Api/V1/Auth/ListTokensController.php @@ -20,7 +20,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'List Tokens', description: 'List personal access tokens for the authenticated user.')] +#[Endpoint( + title: 'List Tokens', + description: 'List the authenticated user\'s personal access tokens, newest first, 25 to a page. Use it to show signed-in devices or to find a token ID to revoke. Returns an array of tokens, with is_current marking the one making the request; follow the Link header\'s rel="next" for the next page.', +)] #[Authenticated] #[QueryParam('cursor', type: 'string', description: 'Opaque cursor from a Link header. Omit it for the first page.', required: false, example: null)] #[Response( diff --git a/app/Http/Controllers/Api/V1/Auth/LoginController.php b/app/Http/Controllers/Api/V1/Auth/LoginController.php index ed0cbc2..55f3127 100644 --- a/app/Http/Controllers/Api/V1/Auth/LoginController.php +++ b/app/Http/Controllers/Api/V1/Auth/LoginController.php @@ -8,6 +8,7 @@ use App\Http\Requests\Auth\LoginRequest; use App\Http\Resources\UserResource; use App\Models\User; +use App\Support\AccessTokens; use App\Support\SecurityAudit; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Hash; @@ -22,7 +23,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'Login', description: 'Authenticate a user and issue a Sanctum bearer token.')] +#[Endpoint( + title: 'Login', + description: 'Exchange an email and password for a bearer token. Use it when a user signs in on a new device, naming the device in device_name. Returns the user with the token, its type and expiry in meta; wrong credentials are a 422 on the email field.', +)] #[Unauthenticated] #[BodyParam('email', type: 'string', description: 'User email address.', required: true, example: 'jane@example.com')] #[BodyParam('password', type: 'string', description: 'User password.', required: true, example: 'password123')] @@ -47,7 +51,7 @@ )] final class LoginController { - public function __invoke(LoginRequest $request): JsonResponse + public function __invoke(LoginRequest $request, AccessTokens $tokens): JsonResponse { $payload = LoginPayload::fromRequest($request); @@ -64,7 +68,8 @@ public function __invoke(LoginRequest $request): JsonResponse ]); } - [$token, $expiresAt] = $this->issueToken($user, $payload->deviceName); + $token = $tokens->issueSession($user, $payload->deviceName); + $expiresAt = $token->accessToken->expires_at; SecurityAudit::log('auth.login.succeeded', [ 'user_id' => $user->id, @@ -75,48 +80,10 @@ public function __invoke(LoginRequest $request): JsonResponse return UserResource::make($user)->additional([ 'meta' => [ - 'token' => $token, + 'token' => $token->plainTextToken, 'token_type' => 'Bearer', 'expires_at' => $expiresAt?->toAtomString(), ], ])->response(); } - - /** - * @return array{0:string,1:\Illuminate\Support\Carbon|null} - */ - private function issueToken(User $user, string $deviceName): array - { - $configuredExpiration = config('sanctum.expiration'); - $expirationMinutes = filter_var( - $configuredExpiration, - FILTER_VALIDATE_INT, - ['options' => ['min_range' => 1]], - ); - - $expiresAt = false !== $expirationMinutes - ? now()->addMinutes($expirationMinutes) - : null; - - $token = $user->createToken($deviceName, $this->defaultAbilities(), $expiresAt); - - return [$token->plainTextToken, $expiresAt]; - } - - /** - * @return list - */ - private function defaultAbilities(): array - { - $abilities = config('sanctum.abilities.default', []); - - if ( ! is_array($abilities)) { - return []; - } - - return array_values(array_filter( - array_map(static fn(mixed $ability): string => is_string($ability) ? mb_trim($ability) : '', $abilities), - static fn(string $ability): bool => '' !== $ability, - )); - } } diff --git a/app/Http/Controllers/Api/V1/Auth/LogoutController.php b/app/Http/Controllers/Api/V1/Auth/LogoutController.php index 256839d..f247c7c 100644 --- a/app/Http/Controllers/Api/V1/Auth/LogoutController.php +++ b/app/Http/Controllers/Api/V1/Auth/LogoutController.php @@ -18,10 +18,22 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'Logout', description: 'Revoke the current Sanctum token.')] +#[Endpoint( + title: 'Logout', + description: 'Revoke the bearer token that made this request, and only that one. Use it when a client signs out; the user\'s other tokens keep working. Returns 204 with no body.', +)] #[Authenticated] #[ScribeResponse(content: null, status: 204, description: 'Token revoked.')] -#[ScribeResponse(content: ['message' => 'Unauthenticated.'], status: 401, description: 'Authentication failed.')] +#[ScribeResponse( + content: [ + 'type' => 'https://apiguide.dev/errors/unauthorized', + 'title' => 'Unauthorized', + 'status' => 401, + 'detail' => 'Unauthenticated.', + ], + status: 401, + description: 'Authentication failed.', +)] final class LogoutController { public function __invoke(Request $request, #[CurrentUser] User $user): Response diff --git a/app/Http/Controllers/Api/V1/Auth/MeController.php b/app/Http/Controllers/Api/V1/Auth/MeController.php index 4bc7bc2..3db1e3d 100644 --- a/app/Http/Controllers/Api/V1/Auth/MeController.php +++ b/app/Http/Controllers/Api/V1/Auth/MeController.php @@ -18,7 +18,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'Get Current User', description: 'Return the authenticated user for the current bearer token.')] +#[Endpoint( + title: 'Get Current User', + description: 'Return the user the bearer token belongs to. Use it to check a token still works and to read the account\'s profile and verification state. The response carries an ETag: send it back in If-None-Match and an unchanged user returns 304 with no body.', +)] #[Authenticated] #[ResponseFromApiResource(name: UserResource::class, model: User::class, status: 200, description: 'Authenticated user profile.')] #[Response( diff --git a/app/Http/Controllers/Api/V1/Auth/RegisterController.php b/app/Http/Controllers/Api/V1/Auth/RegisterController.php index e309b85..f4fc729 100644 --- a/app/Http/Controllers/Api/V1/Auth/RegisterController.php +++ b/app/Http/Controllers/Api/V1/Auth/RegisterController.php @@ -8,6 +8,7 @@ use App\Http\Requests\Auth\RegisterRequest; use App\Http\Resources\UserResource; use App\Models\User; +use App\Support\AccessTokens; use App\Support\SecurityAudit; use Illuminate\Auth\Events\Registered; use Illuminate\Http\JsonResponse; @@ -21,7 +22,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Token Authentication')] -#[Endpoint(title: 'Register', description: 'Create a new account and issue a Sanctum bearer token.')] +#[Endpoint( + title: 'Register', + description: 'Create an account and issue its first bearer token. Use it once per new user; send an Idempotency-Key so a retried request cannot create a second account. Returns the user with the token, its type and expiry in meta, and sends a verification email.', +)] #[Unauthenticated] #[BodyParam('name', type: 'string', description: 'Display name for the account.', required: true, example: 'Jane Doe')] #[BodyParam('email', type: 'string', description: 'Unique email address for login.', required: true, example: 'jane@example.com')] @@ -47,7 +51,7 @@ )] final class RegisterController { - public function __invoke(RegisterRequest $request): JsonResponse + public function __invoke(RegisterRequest $request, AccessTokens $tokens): JsonResponse { $payload = RegisterPayload::fromRequest($request); @@ -59,7 +63,8 @@ public function __invoke(RegisterRequest $request): JsonResponse event(new Registered($user)); - [$token, $expiresAt] = $this->issueToken($user, $payload->deviceName); + $token = $tokens->issueSession($user, $payload->deviceName); + $expiresAt = $token->accessToken->expires_at; SecurityAudit::log('auth.register.succeeded', [ 'user_id' => $user->id, @@ -70,48 +75,10 @@ public function __invoke(RegisterRequest $request): JsonResponse return UserResource::make($user)->additional([ 'meta' => [ - 'token' => $token, + 'token' => $token->plainTextToken, 'token_type' => 'Bearer', 'expires_at' => $expiresAt?->toAtomString(), ], ])->response()->setStatusCode(201); } - - /** - * @return array{0:string,1:\Illuminate\Support\Carbon|null} - */ - private function issueToken(User $user, string $deviceName): array - { - $configuredExpiration = config('sanctum.expiration'); - $expirationMinutes = filter_var( - $configuredExpiration, - FILTER_VALIDATE_INT, - ['options' => ['min_range' => 1]], - ); - - $expiresAt = false !== $expirationMinutes - ? now()->addMinutes($expirationMinutes) - : null; - - $token = $user->createToken($deviceName, $this->defaultAbilities(), $expiresAt); - - return [$token->plainTextToken, $expiresAt]; - } - - /** - * @return list - */ - private function defaultAbilities(): array - { - $abilities = config('sanctum.abilities.default', []); - - if ( ! is_array($abilities)) { - return []; - } - - return array_values(array_filter( - array_map(static fn(mixed $ability): string => is_string($ability) ? mb_trim($ability) : '', $abilities), - static fn(string $ability): bool => '' !== $ability, - )); - } } diff --git a/app/Http/Controllers/Api/V1/Auth/ResetPasswordController.php b/app/Http/Controllers/Api/V1/Auth/ResetPasswordController.php index 8ca5ea8..e40c0b4 100644 --- a/app/Http/Controllers/Api/V1/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Api/V1/Auth/ResetPasswordController.php @@ -22,7 +22,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Password Reset')] -#[Endpoint(title: 'Reset Password', description: 'Reset the user password using a valid reset token.')] +#[Endpoint( + title: 'Reset Password', + description: 'Set a new password using the token from a password reset email. Use it to finish the forgot-password flow. Returns a confirmation message; an invalid or expired token is a 422 on the email field.', +)] #[Unauthenticated] #[BodyParam('token', type: 'string', description: 'Password reset token.', required: true, example: 'reset-token-value')] #[BodyParam('email', type: 'string', description: 'Account email associated with token.', required: true, example: 'jane@example.com')] diff --git a/app/Http/Controllers/Api/V1/Auth/SendEmailVerificationNotificationController.php b/app/Http/Controllers/Api/V1/Auth/SendEmailVerificationNotificationController.php index 45dbb66..b2c111f 100644 --- a/app/Http/Controllers/Api/V1/Auth/SendEmailVerificationNotificationController.php +++ b/app/Http/Controllers/Api/V1/Auth/SendEmailVerificationNotificationController.php @@ -16,7 +16,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Email Verification')] -#[Endpoint(title: 'Send Verification Email', description: 'Send (or resend) an email verification link to the authenticated user.')] +#[Endpoint( + title: 'Send Verification Email', + description: 'Send the authenticated user a new email verification link. Use it when the first link expired or never arrived; it is limited to six requests a minute. Returns a message saying the link was sent, or that the email is already verified.', +)] #[Authenticated] #[Response(content: ['message' => 'Verification link sent.'], status: 200, description: 'Verification email queued/sent.')] #[Response(content: ['message' => 'Email is already verified.'], status: 200, description: 'User already verified.')] diff --git a/app/Http/Controllers/Api/V1/Auth/ShowResetPasswordTokenController.php b/app/Http/Controllers/Api/V1/Auth/ShowResetPasswordTokenController.php index 127819b..c403453 100644 --- a/app/Http/Controllers/Api/V1/Auth/ShowResetPasswordTokenController.php +++ b/app/Http/Controllers/Api/V1/Auth/ShowResetPasswordTokenController.php @@ -17,11 +17,25 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Password Reset')] -#[Endpoint(title: 'Read Reset Token Payload', description: 'Return reset token and email payload for API clients handling email reset links.')] +#[Endpoint( + title: 'Read Reset Token Payload', + description: 'Return the token and email from a password reset link, for a client that opens the link and shows its own reset form. It does not check the token; Reset Password does. Returns the token and the email, if the link carried one.', +)] #[Unauthenticated] #[UrlParam('token', type: 'string', description: 'Password reset token from reset link.', required: true, example: 'reset-token-value')] #[QueryParam('email', type: 'string', description: 'Account email from the reset link.', required: false, example: 'jane@example.com')] #[Response(content: ['token' => 'reset-token-value', 'email' => 'jane@example.com'], status: 200, description: 'Reset payload data.')] +#[Response( + content: [ + 'type' => 'https://apiguide.dev/errors/validation-failed', + 'title' => 'Validation Failed', + 'status' => 422, + 'detail' => 'The email field must be a valid email address.', + 'errors' => ['email' => ['The email field must be a valid email address.']], + ], + status: 422, + description: 'The email query parameter was not an email address.', +)] final class ShowResetPasswordTokenController { public function __invoke(ShowResetPasswordTokenRequest $request): JsonResponse diff --git a/app/Http/Controllers/Api/V1/Auth/VerifyEmailController.php b/app/Http/Controllers/Api/V1/Auth/VerifyEmailController.php index 8582d88..f53562b 100644 --- a/app/Http/Controllers/Api/V1/Auth/VerifyEmailController.php +++ b/app/Http/Controllers/Api/V1/Auth/VerifyEmailController.php @@ -5,11 +5,11 @@ namespace App\Http\Controllers\Api\V1\Auth; use App\Http\Payloads\V1\VerifyEmailPayload; -use App\Http\Requests\Auth\VerifyEmailRequest; use App\Models\User; use App\Support\SecurityAudit; use Illuminate\Auth\Events\Verified; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response; @@ -19,7 +19,10 @@ #[Group(name: 'Authentication')] #[Subgroup(name: 'Email Verification')] -#[Endpoint(title: 'Verify Email', description: 'Verify a user email using the signed verification link parameters.')] +#[Endpoint( + title: 'Verify Email', + description: 'Mark the user\'s email as verified using the signed link from the verification email. Clients do not build this URL; they follow the one in the email, which expires. Returns a confirmation message; a link that is invalid, expired or altered is a 403.', +)] #[Unauthenticated] #[UrlParam('id', type: 'string', description: 'User ULID from the signed verification link.', required: true, example: '01HZX3W3T4J8Q57XNZD5BPHJ92')] #[UrlParam('hash', type: 'string', description: 'SHA-1 hash of the email from the signed verification link.', required: true, example: '8c4f4370e5db9b5be6d0f4c95495f49f998fa32a')] @@ -36,7 +39,7 @@ )] final class VerifyEmailController { - public function __invoke(VerifyEmailRequest $request): JsonResponse + public function __invoke(Request $request): JsonResponse { $payload = VerifyEmailPayload::fromRequest($request); diff --git a/app/Http/Payloads/RouteParameter.php b/app/Http/Payloads/RouteParameter.php new file mode 100644 index 0000000..c2826be --- /dev/null +++ b/app/Http/Payloads/RouteParameter.php @@ -0,0 +1,32 @@ +route($name); + + if ( ! is_string($value)) { + throw new LogicException("The route has no [{$name}] parameter."); + } + + return $value; + } + + public static function integer(Request $request, string $name): int + { + return (int) self::string($request, $name); + } +} diff --git a/app/Http/Payloads/V1/CreateTokenPayload.php b/app/Http/Payloads/V1/CreateTokenPayload.php new file mode 100644 index 0000000..039f4c3 --- /dev/null +++ b/app/Http/Payloads/V1/CreateTokenPayload.php @@ -0,0 +1,44 @@ + $abilities + */ + public function __construct( + public string $name, + public array $abilities, + public ?Carbon $expiresAt, + ) {} + + public static function fromRequest(Request $request): self + { + $data = self::validatedData($request); + + return new self( + name: Arr::string($data, 'name'), + abilities: array_values(array_filter(Arr::array($data, 'abilities'), is_string(...))), + expiresAt: isset($data['expires_at']) ? Carbon::parse(Arr::string($data, 'expires_at')) : null, + ); + } + + /** + * @return array + */ + private static function validatedData(Request $request): array + { + /** @var array $data */ + $data = $request instanceof FormRequest ? $request->validated() : $request->all(); + + return $data; + } +} diff --git a/app/Http/Payloads/V1/DeleteTokenPayload.php b/app/Http/Payloads/V1/DeleteTokenPayload.php index 29f5b43..bafaddb 100644 --- a/app/Http/Payloads/V1/DeleteTokenPayload.php +++ b/app/Http/Payloads/V1/DeleteTokenPayload.php @@ -4,9 +4,8 @@ namespace App\Http\Payloads\V1; -use Illuminate\Foundation\Http\FormRequest; +use App\Http\Payloads\RouteParameter; use Illuminate\Http\Request; -use Illuminate\Support\Arr; final readonly class DeleteTokenPayload { @@ -16,21 +15,8 @@ public function __construct( public static function fromRequest(Request $request): self { - $data = self::validatedData($request); - return new self( - tokenId: (int) Arr::string($data, 'token_id'), + tokenId: RouteParameter::integer($request, 'token_id'), ); } - - /** - * @return array - */ - private static function validatedData(Request $request): array - { - /** @var array $data */ - $data = $request instanceof FormRequest ? $request->validated() : $request->all(); - - return $data; - } } diff --git a/app/Http/Payloads/V1/ShowResetPasswordTokenPayload.php b/app/Http/Payloads/V1/ShowResetPasswordTokenPayload.php index fe5806e..8cd688a 100644 --- a/app/Http/Payloads/V1/ShowResetPasswordTokenPayload.php +++ b/app/Http/Payloads/V1/ShowResetPasswordTokenPayload.php @@ -4,6 +4,7 @@ namespace App\Http\Payloads\V1; +use App\Http\Payloads\RouteParameter; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Request; use Illuminate\Support\Arr; @@ -20,7 +21,7 @@ public static function fromRequest(Request $request): self $data = self::validatedData($request); return new self( - token: Arr::string($data, 'token'), + token: RouteParameter::string($request, 'token'), email: isset($data['email']) ? Arr::string($data, 'email') : null, ); } diff --git a/app/Http/Payloads/V1/VerifyEmailPayload.php b/app/Http/Payloads/V1/VerifyEmailPayload.php index c8aac90..e7a5fab 100644 --- a/app/Http/Payloads/V1/VerifyEmailPayload.php +++ b/app/Http/Payloads/V1/VerifyEmailPayload.php @@ -4,9 +4,8 @@ namespace App\Http\Payloads\V1; -use Illuminate\Foundation\Http\FormRequest; +use App\Http\Payloads\RouteParameter; use Illuminate\Http\Request; -use Illuminate\Support\Arr; final readonly class VerifyEmailPayload { @@ -17,22 +16,9 @@ public function __construct( public static function fromRequest(Request $request): self { - $data = self::validatedData($request); - return new self( - id: Arr::string($data, 'id'), - hash: Arr::string($data, 'hash'), + id: RouteParameter::string($request, 'id'), + hash: RouteParameter::string($request, 'hash'), ); } - - /** - * @return array - */ - private static function validatedData(Request $request): array - { - /** @var array $data */ - $data = $request instanceof FormRequest ? $request->validated() : $request->all(); - - return $data; - } } diff --git a/app/Http/Requests/Auth/CreateTokenRequest.php b/app/Http/Requests/Auth/CreateTokenRequest.php new file mode 100644 index 0000000..1caf14d --- /dev/null +++ b/app/Http/Requests/Auth/CreateTokenRequest.php @@ -0,0 +1,56 @@ + + */ + public function rules(AccessTokens $tokens): array + { + $current = $this->user()?->currentAccessToken(); + + return [ + 'name' => ['required', 'string', 'max:255'], + 'abilities' => ['required', 'array', 'min:1'], + 'abilities.*' => [ + 'required', + 'string', + 'distinct', + Rule::in($current instanceof PersonalAccessToken ? $tokens->grantableBy($current) : []), + ], + 'expires_at' => [ + 'nullable', + 'date', + 'after:now', + 'before_or_equal:' . $tokens->latestApiKeyExpiry()->toAtomString(), + ], + ]; + } + + /** + * @return array + */ + public function messages(): array + { + return [ + 'abilities.*.in' => __('api.auth.ability_not_grantable'), + ]; + } +} diff --git a/app/Http/Requests/Auth/DeleteTokenRequest.php b/app/Http/Requests/Auth/DeleteTokenRequest.php deleted file mode 100644 index 8e93ac0..0000000 --- a/app/Http/Requests/Auth/DeleteTokenRequest.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ - public function rules(): array - { - return [ - 'token_id' => ['required', 'integer'], - ]; - } - - /** - * @return array - */ - public function validationData(): array - { - /** @var array $data */ - $data = array_merge($this->all(), [ - 'token_id' => $this->route('token_id'), - ]); - - return $data; - } -} diff --git a/app/Http/Requests/Auth/ShowResetPasswordTokenRequest.php b/app/Http/Requests/Auth/ShowResetPasswordTokenRequest.php index 4ae9fae..c13d615 100644 --- a/app/Http/Requests/Auth/ShowResetPasswordTokenRequest.php +++ b/app/Http/Requests/Auth/ShowResetPasswordTokenRequest.php @@ -19,21 +19,23 @@ public function authorize(): bool public function rules(): array { return [ - 'token' => ['required', 'string'], 'email' => ['nullable', 'string', 'email', 'max:255'], ]; } /** - * @return array + * Read by Scribe: the request is a GET, so its rules describe query parameters, and the token is + * a path parameter validated by the route. + * + * @return array */ - public function validationData(): array + public function queryParameters(): array { - /** @var array $data */ - $data = array_merge($this->all(), [ - 'token' => $this->route('token'), - ]); - - return $data; + return [ + 'email' => [ + 'description' => 'Account email from the reset link.', + 'example' => 'jane@example.com', + ], + ]; } } diff --git a/app/Http/Requests/Auth/VerifyEmailRequest.php b/app/Http/Requests/Auth/VerifyEmailRequest.php deleted file mode 100644 index ece6521..0000000 --- a/app/Http/Requests/Auth/VerifyEmailRequest.php +++ /dev/null @@ -1,41 +0,0 @@ -|string> - */ - public function rules(): array - { - return [ - 'id' => ['required', 'ulid', Rule::exists('users', 'id')], - 'hash' => ['required', 'string', 'size:40'], - ]; - } - - /** - * @return array - */ - public function validationData(): array - { - /** @var array $data */ - $data = array_merge($this->all(), [ - 'id' => $this->route('id'), - 'hash' => $this->route('hash'), - ]); - - return $data; - } -} diff --git a/app/Models/User.php b/app/Models/User.php index 4537a1e..b252d03 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -4,6 +4,8 @@ namespace App\Models; +use App\Notifications\ResetPassword; +use App\Notifications\VerifyEmail; use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Concerns\HasUlids; @@ -11,6 +13,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; +use SensitiveParameter; /** * @property \Illuminate\Support\Carbon|null $email_verified_at @@ -35,6 +38,23 @@ final class User extends Authenticatable implements MustVerifyEmail */ protected $hidden = ['password', 'remember_token']; + /** + * Queued, in the locale of the request that asked for it: a queued job otherwise runs in the + * application's default locale. + */ + public function sendEmailVerificationNotification(): void + { + $this->notify((new VerifyEmail())->locale(app()->getLocale())); + } + + /** + * @param string $token + */ + public function sendPasswordResetNotification(#[SensitiveParameter] $token): void + { + $this->notify((new ResetPassword($token))->locale(app()->getLocale())); + } + /** @return array */ protected function casts(): array { diff --git a/app/Notifications/ResetPassword.php b/app/Notifications/ResetPassword.php new file mode 100644 index 0000000..14f0e4e --- /dev/null +++ b/app/Notifications/ResetPassword.php @@ -0,0 +1,18 @@ +environment()); + // Document path parameters as the routes name them. Scribe otherwise renames {project} + // to {id} when it guesses at route model binding, and the spec stops matching the routes. + // Scribe is a dev dependency, so production skips this. + if (class_exists(Scribe::class)) { + Scribe::normalizeEndpointUrlUsing(static fn(string $uri): string => $uri); + } + RateLimiter::for('auth-register', fn(Request $request) => [ Limit::perMinute(10)->by($request->ip()), ]); diff --git a/app/Support/AccessTokens.php b/app/Support/AccessTokens.php new file mode 100644 index 0000000..3eed88f --- /dev/null +++ b/app/Support/AccessTokens.php @@ -0,0 +1,84 @@ +integer('sanctum.lifetimes.session_minutes', 120); + + return $user->createToken( + $deviceName, + $this->configuredAbilities('sanctum.abilities.default'), + $minutes > 0 ? now()->addMinutes($minutes) : null, + ); + } + + /** + * An API key with the given abilities, which the caller has already checked with grantableBy(). + * + * @param list $abilities + */ + public function issueApiKey(User $user, string $name, array $abilities, Carbon $expiresAt): NewAccessToken + { + return $user->createToken($name, $abilities, $expiresAt); + } + + /** + * The abilities a token can grant to an API key: those it holds itself, out of the abilities + * routes check. A token holding "*" can grant any of them. + * + * @return list + */ + public function grantableBy(PersonalAccessToken $token): array + { + $available = $this->configuredAbilities('sanctum.abilities.available'); + $held = array_filter( + is_array($token->abilities) ? $token->abilities : [], + is_string(...), + ); + + if (in_array('*', $held, true)) { + return $available; + } + + return array_values(array_intersect($available, $held)); + } + + public function defaultApiKeyExpiry(): Carbon + { + return now()->addDays(config()->integer('sanctum.lifetimes.api_key_default_days', 90)); + } + + public function latestApiKeyExpiry(): Carbon + { + return now()->addDays(config()->integer('sanctum.lifetimes.api_key_max_days', 365)); + } + + /** + * @return list + */ + private function configuredAbilities(string $key): array + { + return array_values(array_filter( + config()->array($key, []), + static fn(mixed $ability): bool => is_string($ability) && '' !== mb_trim($ability), + )); + } +} diff --git a/app/Support/NoContentOpenApiGenerator.php b/app/Support/NoContentOpenApiGenerator.php new file mode 100644 index 0000000..fe7a301 --- /dev/null +++ b/app/Support/NoContentOpenApiGenerator.php @@ -0,0 +1,39 @@ + $pathItem + * @param array $groupedEndpoints + * @return array + */ + public function pathItem(array $pathItem, array $groupedEndpoints, OutputEndpointData $endpoint): array + { + if ( ! is_array($pathItem['responses'] ?? null)) { + return $pathItem; + } + + foreach ($pathItem['responses'] as $status => $response) { + if (in_array((int) $status, self::STATUSES, true) && is_array($response)) { + unset($response['content']); + $pathItem['responses'][$status] = $response; + } + } + + return $pathItem; + } +} diff --git a/composer.json b/composer.json index 8e41ef3..9c182dd 100644 --- a/composer.json +++ b/composer.json @@ -15,12 +15,12 @@ "php": "^8.5", "juststeveking/api-toolbox": "^0.3", "laravel/framework": "^13.30", + "laravel/octane": "^2.21", "laravel/sanctum": "^4.3", "laravel/tinker": "^3.0", "readalizer/readalizer": "^1.0" }, "require-dev": { - "driftingly/rector-laravel": "^2.1", "fakerphp/faker": "^1.23", "knuckleswtf/scribe": "^5.11", "larastan/larastan": "^3.9", @@ -35,7 +35,6 @@ "pestphp/pest-plugin-laravel": "^4.1", "pestphp/pest-plugin-type-coverage": "^4.0", "phpstan/phpstan": "^2.1", - "rector/rector": "^2.3", "roave/security-advisories": "dev-latest" }, "autoload": { diff --git a/composer.lock b/composer.lock index 60ded5c..dfadf79 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "e637552c13afa7f0c3f8279d8ca36d76", + "content-hash": "c4ca03980990fae86779c14abbf7bd3f", "packages": [ { "name": "brick/math", @@ -1124,6 +1124,95 @@ }, "time": "2026-10-20T09:42:04+00:00" }, + { + "name": "laminas/laminas-diactoros", + "version": "3.9.0", + "source": { + "type": "git", + "url": "https://github.com/laminas/laminas-diactoros.git", + "reference": "4ab9fe10869ac0cd46fa78e641b6d0f4389bc6b4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laminas/laminas-diactoros/zipball/4ab9fe10869ac0cd46fa78e641b6d0f4389bc6b4", + "reference": "4ab9fe10869ac0cd46fa78e641b6d0f4389bc6b4", + "shasum": "" + }, + "require": { + "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^1.1 || ^2.0" + }, + "conflict": { + "amphp/amp": "<2.6.4" + }, + "provide": { + "psr/http-factory-implementation": "^1.0", + "psr/http-message-implementation": "^1.1 || ^2.0" + }, + "require-dev": { + "boundwize/structarmed": "^0.17.7", + "ext-curl": "*", + "ext-dom": "*", + "ext-gd": "*", + "ext-libxml": "*", + "http-interop/http-factory-tests": "^2.2.0", + "laminas/laminas-coding-standard": "~3.1.0", + "php-http/psr7-integration-tests": "^1.4.0", + "phpunit/phpunit": "^10.5.36", + "psalm/plugin-phpunit": "^0.19.5", + "vimeo/psalm": "^6.13" + }, + "type": "library", + "extra": { + "laminas": { + "module": "Laminas\\Diactoros", + "config-provider": "Laminas\\Diactoros\\ConfigProvider" + } + }, + "autoload": { + "files": [ + "src/functions/create_uploaded_file.php", + "src/functions/marshal_headers_from_sapi.php", + "src/functions/marshal_method_from_sapi.php", + "src/functions/marshal_protocol_version_from_sapi.php", + "src/functions/normalize_server.php", + "src/functions/normalize_uploaded_files.php", + "src/functions/parse_cookie_header.php" + ], + "psr-4": { + "Laminas\\Diactoros\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "PSR HTTP Message implementations", + "homepage": "https://laminas.dev", + "keywords": [ + "http", + "laminas", + "psr", + "psr-17", + "psr-7" + ], + "support": { + "chat": "https://laminas.dev/chat", + "docs": "https://docs.laminas.dev/laminas-diactoros/", + "forum": "https://discourse.laminas.dev", + "issues": "https://github.com/laminas/laminas-diactoros/issues", + "rss": "https://github.com/laminas/laminas-diactoros/releases.atom", + "source": "https://github.com/laminas/laminas-diactoros" + }, + "funding": [ + { + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" + } + ], + "time": "2026-10-08T08:19:47+00:00" + }, { "name": "laravel/framework", "version": "v13.35.0", @@ -1355,6 +1444,95 @@ }, "time": "2026-10-06T13:52:37+00:00" }, + { + "name": "laravel/octane", + "version": "v2.22.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/octane.git", + "reference": "c49ff458e94bf14b382f6414c6b9ddb39ac82b28" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/octane/zipball/c49ff458e94bf14b382f6414c6b9ddb39ac82b28", + "reference": "c49ff458e94bf14b382f6414c6b9ddb39ac82b28", + "shasum": "" + }, + "require": { + "laminas/laminas-diactoros": "^3.0", + "laravel/framework": "^10.10.1|^11.0|^12.0|^13.0", + "laravel/prompts": "^0.1.24|^0.2.0|^0.3.0", + "laravel/serializable-closure": "^1.3|^2.0", + "nesbot/carbon": "^2.66.0|^3.0", + "php": "^8.1.0", + "symfony/console": "^6.0|^7.0|^8.0", + "symfony/psr-http-message-bridge": "^2.2.0|^6.4|^7.0|^8.0" + }, + "conflict": { + "spiral/roadrunner": "<2023.1.0", + "spiral/roadrunner-cli": "<2.6.0", + "spiral/roadrunner-http": "<3.3.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^7.6.1", + "inertiajs/inertia-laravel": "^1.3.2|^2.0", + "laravel/scout": "^10.2.1", + "laravel/socialite": "^5.6.1", + "livewire/livewire": "^2.12.3|^3.0", + "nunomaduro/collision": "^6.4.0|^7.5.2|^8.0", + "orchestra/testbench": "^8.21|^9.0|^10.0|^11.0", + "phpstan/phpstan": "^2.1.7", + "phpunit/phpunit": "^10.4|^11.5|^12.0|^13.0", + "spiral/roadrunner-cli": "^2.6.0", + "spiral/roadrunner-http": "^3.3.0" + }, + "bin": [ + "bin/roadrunner-worker", + "bin/swoole-server" + ], + "type": "library", + "extra": { + "laravel": { + "aliases": { + "Octane": "Laravel\\Octane\\Facades\\Octane" + }, + "providers": [ + "Laravel\\Octane\\OctaneServiceProvider" + ] + }, + "branch-alias": { + "dev-master": "2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\Octane\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Supercharge your Laravel application's performance.", + "keywords": [ + "frankenphp", + "laravel", + "octane", + "roadrunner", + "swoole" + ], + "support": { + "issues": "https://github.com/laravel/octane/issues", + "source": "https://github.com/laravel/octane" + }, + "time": "2026-10-14T15:54:28+00:00" + }, { "name": "laravel/prompts", "version": "v0.3.26", @@ -5408,6 +5586,93 @@ ], "time": "2026-10-08T16:57:43+00:00" }, + { + "name": "symfony/psr-http-message-bridge", + "version": "v8.1.9", + "source": { + "type": "git", + "url": "https://github.com/symfony/psr-http-message-bridge.git", + "reference": "cfa8f3ac693fec234a91d8745b45ed9a81a0b799" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/psr-http-message-bridge/zipball/cfa8f3ac693fec234a91d8745b45ed9a81a0b799", + "reference": "cfa8f3ac693fec234a91d8745b45ed9a81a0b799", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "psr/http-message": "^1.0|^2.0", + "symfony/http-foundation": "^7.4|^8.0" + }, + "conflict": { + "php-http/discovery": "<1.15" + }, + "require-dev": { + "nyholm/psr7": "^1.1", + "php-http/discovery": "^1.15", + "psr/log": "^1.1.4|^2|^3", + "symfony/browser-kit": "^7.4|^8.0", + "symfony/config": "^7.4|^8.0", + "symfony/event-dispatcher": "^7.4|^8.0", + "symfony/framework-bundle": "^7.4|^8.0", + "symfony/http-kernel": "^7.4|^8.0", + "symfony/runtime": "^7.4|^8.0" + }, + "type": "symfony-bridge", + "autoload": { + "psr-4": { + "Symfony\\Bridge\\PsrHttpMessage\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "PSR HTTP message bridge", + "homepage": "https://symfony.com", + "keywords": [ + "http", + "http-message", + "psr-17", + "psr-7" + ], + "support": { + "source": "https://github.com/symfony/psr-http-message-bridge/tree/v8.1.9" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-10-07T08:21:34+00:00" + }, { "name": "symfony/routing", "version": "v8.1.9", @@ -6580,64 +6845,6 @@ }, "time": "2026-02-07T07:09:04+00:00" }, - { - "name": "driftingly/rector-laravel", - "version": "2.6.2", - "source": { - "type": "git", - "url": "https://github.com/driftingly/rector-laravel.git", - "reference": "c0f9a2ff7365cec45d4dc64223608e7cec74604a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/c0f9a2ff7365cec45d4dc64223608e7cec74604a", - "reference": "c0f9a2ff7365cec45d4dc64223608e7cec74604a", - "shasum": "" - }, - "require": { - "php": ">=8.3", - "rector/rector": "^2.6.4", - "symplify/rule-doc-generator-contracts": "^11.2", - "webmozart/assert": "^1.11 || ^2.0" - }, - "require-dev": { - "boundwize/structarmed": "^0.16", - "nette/utils": "^4.0", - "nikic/php-parser": "^5.6", - "phpstan/extension-installer": "^1.3", - "phpstan/phpstan": "^2.2", - "phpstan/phpstan-deprecation-rules": "^2.0", - "phpstan/phpstan-strict-rules": "^2.0", - "phpstan/phpstan-webmozart-assert": "^2.0", - "phpunit/phpunit": "^10.5", - "symplify/rule-doc-generator": "^12.2", - "tightenco/duster": "^3.1", - "tracy/tracy": "^2.10" - }, - "type": "rector-extension", - "extra": { - "rector": { - "includes": [ - "config/config.php" - ] - } - }, - "autoload": { - "psr-4": { - "RectorLaravel\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "description": "Rector upgrades rules for Laravel Framework", - "support": { - "issues": "https://github.com/driftingly/rector-laravel/issues", - "source": "https://github.com/driftingly/rector-laravel/tree/2.6.2" - }, - "time": "2026-08-29T21:42:57+00:00" - }, { "name": "entropy/entropy", "version": "0.4.30", @@ -9462,63 +9669,6 @@ ], "time": "2026-07-28T13:58:09+00:00" }, - { - "name": "rector/rector", - "version": "2.7.0", - "source": { - "type": "git", - "url": "https://github.com/rectorphp/rector.git", - "reference": "4d6a39b7fff302cac0ce90cd959a53c2f6a32776" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/rectorphp/rector/zipball/4d6a39b7fff302cac0ce90cd959a53c2f6a32776", - "reference": "4d6a39b7fff302cac0ce90cd959a53c2f6a32776", - "shasum": "" - }, - "require": { - "php": "^7.4|^8.0", - "phpstan/phpstan": "^2.3.0" - }, - "conflict": { - "rector/rector-doctrine": "*", - "rector/rector-downgrade-php": "*", - "rector/rector-phpunit": "*", - "rector/rector-symfony": "*" - }, - "bin": [ - "bin/rector" - ], - "type": "library", - "autoload": { - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "description": "Instant Upgrade and Automated Refactoring of any PHP code", - "homepage": "https://getrector.com/", - "keywords": [ - "automation", - "dev", - "migration", - "refactoring" - ], - "support": { - "issues": "https://github.com/rectorphp/rector/issues", - "source": "https://github.com/rectorphp/rector/tree/2.7.0" - }, - "funding": [ - { - "url": "https://github.com/tomasvotruba", - "type": "github" - } - ], - "time": "2026-10-06T08:46:45+00:00" - }, { "name": "roave/security-advisories", "version": "dev-latest", @@ -11967,66 +12117,6 @@ ], "time": "2026-10-12T12:37:13+00:00" }, - { - "name": "symplify/rule-doc-generator-contracts", - "version": "11.2.0", - "source": { - "type": "git", - "url": "https://github.com/symplify/rule-doc-generator-contracts.git", - "reference": "479cfcfd46047f80624aba931d9789e50475b5c6" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symplify/rule-doc-generator-contracts/zipball/479cfcfd46047f80624aba931d9789e50475b5c6", - "reference": "479cfcfd46047f80624aba931d9789e50475b5c6", - "shasum": "" - }, - "require": { - "php": ">=8.1" - }, - "require-dev": { - "php-parallel-lint/php-parallel-lint": "^1.3", - "phpstan/extension-installer": "^1.2", - "rector/rector": "^0.15.10", - "symplify/easy-ci": "^11.1", - "symplify/easy-coding-standard": "^11.1", - "symplify/easy-testing": "^11.1", - "symplify/phpstan-extensions": "^11.1", - "symplify/phpstan-rules": "11.2.3.72", - "tomasvotruba/unused-public": "^0.0.34" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "11.2-dev" - } - }, - "autoload": { - "psr-4": { - "Symplify\\RuleDocGenerator\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "description": "Contracts for production code of RuleDocGenerator", - "support": { - "source": "https://github.com/symplify/rule-doc-generator-contracts/tree/11.2.0" - }, - "funding": [ - { - "url": "https://www.paypal.me/rectorphp", - "type": "custom" - }, - { - "url": "https://github.com/tomasvotruba", - "type": "github" - } - ], - "abandoned": true, - "time": "2024-03-18T22:02:54+00:00" - }, { "name": "ta-tikoma/phpunit-architecture-test", "version": "0.8.7", diff --git a/config/octane.php b/config/octane.php new file mode 100644 index 0000000..647d8aa --- /dev/null +++ b/config/octane.php @@ -0,0 +1,256 @@ + env('OCTANE_SERVER', 'frankenphp'), + + /* + |-------------------------------------------------------------------------- + | Force HTTPS + |-------------------------------------------------------------------------- + | + | When this configuration value is set to "true", Octane will inform the + | framework that all absolute links must be generated using the HTTPS + | protocol. Otherwise your links may be generated using plain HTTP. + | + */ + + 'https' => env('OCTANE_HTTPS', false), + + /* + |-------------------------------------------------------------------------- + | Octane Listeners + |-------------------------------------------------------------------------- + | + | All of the event listeners for Octane's events are defined below. These + | listeners are responsible for resetting your application's state for + | the next request. You may even add your own listeners to the list. + | + */ + + 'listeners' => [ + WorkerStarting::class => [ + EnsureUploadedFilesAreValid::class, + EnsureUploadedFilesCanBeMoved::class, + ], + + RequestReceived::class => [ + ...Octane::prepareApplicationForNextOperation(), + ...Octane::prepareApplicationForNextRequest(), + + ], + + RequestHandled::class => [ + + ], + + RequestTerminated::class => [ + // FlushUploadedFiles::class, + ], + + TaskReceived::class => [ + ...Octane::prepareApplicationForNextOperation(), + + ], + + TaskTerminated::class => [ + + ], + + TickReceived::class => [ + ...Octane::prepareApplicationForNextOperation(), + + ], + + TickTerminated::class => [ + + ], + + OperationTerminated::class => [ + FlushOnce::class, + FlushTemporaryContainerInstances::class, + // DisconnectFromDatabases::class, + // CollectGarbage::class, + ], + + WorkerErrorOccurred::class => [ + ReportException::class, + StopWorkerIfNecessary::class, + ], + + WorkerStopping::class => [ + CloseMonologHandlers::class, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Warm / Flush Bindings + |-------------------------------------------------------------------------- + | + | The bindings listed below will either be pre-warmed when a worker boots + | or they will be flushed before every new request. Flushing a binding + | will force the container to resolve that binding again when asked. + | + */ + + 'warm' => [ + ...Octane::defaultServicesToWarm(), + ], + + 'flush' => [ + + ], + + /* + |-------------------------------------------------------------------------- + | Octane Swoole Tables + |-------------------------------------------------------------------------- + | + | While using Swoole, you may define additional tables as required by the + | application. These tables can be used to store data that needs to be + | quickly accessed by other workers on the particular Swoole server. + | + */ + + 'tables' => [ + 'example:1000' => [ + 'name' => 'string:1000', + 'votes' => 'int', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Octane Swoole Cache Table + |-------------------------------------------------------------------------- + | + | While using Swoole, you may leverage the Octane cache, which is powered + | by a Swoole table. You may set the maximum number of rows as well as + | the number of bytes per row using the configuration options below. + | + */ + + 'cache' => [ + 'rows' => 1000, + 'bytes' => 10000, + ], + + /* + |-------------------------------------------------------------------------- + | File Watching + |-------------------------------------------------------------------------- + | + | The following list of files and directories will be watched when using + | the --watch option offered by Octane. If any of the directories and + | files are changed, Octane will automatically reload your workers. + | + */ + + 'watch' => [ + 'app', + 'bootstrap', + 'config/**/*.php', + 'database/**/*.php', + 'public/**/*.php', + 'resources/**/*.php', + 'routes', + 'composer.lock', + '.env', + ], + + /* + |-------------------------------------------------------------------------- + | Garbage Collection Threshold + |-------------------------------------------------------------------------- + | + | When executing long-lived PHP scripts such as Octane, memory can build + | up before being cleared by PHP. You can force Octane to run garbage + | collection if your application consumes this amount of megabytes. + | + */ + + 'garbage' => 50, + + /* + |-------------------------------------------------------------------------- + | Maximum Execution Time + |-------------------------------------------------------------------------- + | + | The following setting configures the maximum execution time for requests + | being handled by Octane. You may set this value to 0 to indicate that + | there isn't a specific time limit on Octane request execution time. + | + */ + + 'max_execution_time' => 30, + + /* + |-------------------------------------------------------------------------- + | Octane Server State File + |-------------------------------------------------------------------------- + | + | This value determines where Octane stores the state file used to track + | the running server's master process ID and admin endpoint, which is + | read by various Octane commands. You may tweak this if necessary. + | + */ + + 'state_file' => env('OCTANE_STATE_FILE', storage_path('logs/octane-server-state.json')), + + /* + |-------------------------------------------------------------------------- + | RoadRunner Options + |-------------------------------------------------------------------------- + | + | The following options are only used when the RoadRunner server is the + | server powering your application. You may customize the path to the + | worker binary here, which is useful for zero-downtime deployments + | where the application is served from a symlinked "current" path. + | + */ + + 'roadrunner' => [ + 'command' => env('OCTANE_ROADRUNNER_COMMAND', 'vendor/bin/roadrunner-worker'), + 'http_middleware' => env('OCTANE_ROADRUNNER_HTTP_MIDDLEWARE', 'static'), + ], + +]; diff --git a/config/sanctum.php b/config/sanctum.php index 10be889..7e254a1 100644 --- a/config/sanctum.php +++ b/config/sanctum.php @@ -43,29 +43,57 @@ | Expiration Minutes |-------------------------------------------------------------------------- | - | This value controls the number of minutes until an issued token will be - | considered expired. This will override any values set in the token's - | "expires_at" attribute, but first-party sessions are not affected. + | Off: every token Kit issues carries its own expires_at instead, from + | "lifetimes" below. A global expiration would cap every token, so an API + | key could never outlive a sign-in session. | */ - 'expiration' => env('SANCTUM_EXPIRATION', 120), + 'expiration' => null, + + /* + |-------------------------------------------------------------------------- + | Token Lifetimes + |-------------------------------------------------------------------------- + | + | Session tokens are issued by register and login. API keys are created by + | POST /v1/auth/tokens, for scripts, integrations and agents; a client picks + | an expiry up to the maximum, or gets the default. + | + */ + + 'lifetimes' => [ + 'session_minutes' => (int) env('SANCTUM_EXPIRATION', 120), + 'api_key_default_days' => (int) env('API_KEY_DEFAULT_DAYS', 90), + 'api_key_max_days' => (int) env('API_KEY_MAX_DAYS', 365), + ], /* |-------------------------------------------------------------------------- | Token Abilities |-------------------------------------------------------------------------- | - | Default abilities assigned to newly issued personal access tokens. - | Keep this list least-privilege and grant only endpoint-specific needs. + | "available" is every ability a route checks. "default" is what a session + | token from register or login gets. An API key gets the abilities its + | creator asks for, limited to ones the creating token holds itself. | */ + 'abilities' => [ + 'available' => [ + 'auth:me', + 'auth:logout', + 'auth:verification:send', + 'auth:tokens:read', + 'auth:tokens:create', + 'auth:tokens:delete', + ], 'default' => [ 'auth:me', 'auth:logout', 'auth:verification:send', 'auth:tokens:read', + 'auth:tokens:create', 'auth:tokens:delete', ], ], diff --git a/config/scribe.php b/config/scribe.php index 600d6f9..e9ba4a7 100644 --- a/config/scribe.php +++ b/config/scribe.php @@ -14,6 +14,12 @@ // Only the most common configs are shown. See the https://scribe.knuckles.wtf/laravel/reference/config for all. +// Scribe is a dev dependency. Production installs it without, and Laravel loads every config +// file, so without this every artisan command there fails on the classes below. +if ( ! class_exists(Defaults::class)) { + return []; +} + return [ // The HTML for the generated documentation. 'title' => config('app.name') . ' API Documentation', @@ -175,6 +181,7 @@ // Should extend `Knuckles\Scribe\Writing\OpenApiSpecGenerators\OpenApiGenerator`. 'generators' => [ App\Support\ProblemDetailsOpenApiGenerator::class, + App\Support\NoContentOpenApiGenerator::class, ], ], diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100755 index 0000000..fbd6dd0 --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Caches configuration, routes and events from the environment the container was started with, then +# runs the command: Octane on FrankenPHP by default, or what was passed, such as +# `php artisan queue:work` for a worker from the same image. +set -e + +php artisan optimize --no-interaction + +if [ "$#" -eq 0 ]; then + exec php artisan octane:start \ + --server=frankenphp \ + --host=0.0.0.0 \ + --port="${PORT:-8000}" \ + --admin-port=2019 \ + --workers="${OCTANE_WORKERS:-auto}" \ + --max-requests="${OCTANE_MAX_REQUESTS:-500}" +fi + +exec "$@" diff --git a/docker/healthcheck.php b/docker/healthcheck.php new file mode 100644 index 0000000..40b7bac --- /dev/null +++ b/docker/healthcheck.php @@ -0,0 +1,18 @@ +<?php + +declare(strict_types=1); + +// Asks the running server for /up with APP_URL's host, since TRUSTED_HOSTS refuses 127.0.0.1. +$port = getenv('PORT') ?: '8000'; +$host = parse_url((string) getenv('APP_URL'), PHP_URL_HOST) ?: 'localhost'; + +$context = stream_context_create(['http' => [ + 'header' => "Host: {$host}\r\nX-Forwarded-Proto: https\r\n", + 'timeout' => 2, + 'ignore_errors' => true, +]]); + +$body = @file_get_contents("http://127.0.0.1:{$port}/up", false, $context); +$status = isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $match) ? (int) $match[1] : 0; + +exit(false !== $body && 200 === $status ? 0 : 1); diff --git a/docker/php.ini b/docker/php.ini new file mode 100644 index 0000000..742d7b5 --- /dev/null +++ b/docker/php.ini @@ -0,0 +1,7 @@ +; Production PHP settings for the Octane image. +expose_php = Off +memory_limit = 256M +opcache.enable_cli = 1 +opcache.validate_timestamps = 0 +opcache.memory_consumption = 192 +opcache.max_accelerated_files = 20000 diff --git a/lang/en/api.php b/lang/en/api.php index 0ce9534..26f23dd 100644 --- a/lang/en/api.php +++ b/lang/en/api.php @@ -16,6 +16,7 @@ 'password_reset_throttled' => 'Please wait before retrying.', 'password_reset_failed' => 'Unable to reset password with the provided details.', 'token_not_found' => 'Token not found.', + 'ability_not_grantable' => 'You can only grant abilities your current token holds.', ], 'errors' => [ 'unauthenticated' => 'Unauthenticated.', diff --git a/lang/es/api.php b/lang/es/api.php index f295222..71dc221 100644 --- a/lang/es/api.php +++ b/lang/es/api.php @@ -16,6 +16,7 @@ 'password_reset_throttled' => 'Espera antes de volver a intentarlo.', 'password_reset_failed' => 'No se pudo restablecer la contrasena con los datos proporcionados.', 'token_not_found' => 'Token no encontrado.', + 'ability_not_grantable' => 'Solo puedes conceder habilidades que tiene tu token actual.', ], 'errors' => [ 'unauthenticated' => 'No autenticado.', diff --git a/public/docs/collection.json b/public/docs/collection.json index b2d770e..877cc84 100644 --- a/public/docs/collection.json +++ b/public/docs/collection.json @@ -10,7 +10,7 @@ ], "info": { "name": "Laravel API Documentation", - "_postman_id": "b4c68cd2-a1c9-4855-bafb-771176ff6d3e", + "_postman_id": "3a3b7138-0565-4302-8613-83b81be02853", "description": "", "schema": "https:\/\/schema.getpostman.com\/json\/collection\/v2.1.0\/collection.json" }, @@ -47,7 +47,7 @@ "mode": "raw", "raw": "{\"name\":\"Jane Doe\",\"email\":\"jane@example.com\",\"password\":\"password123\",\"device_name\":\"ios-app\"}" }, - "description": "Create a new account and issue a Sanctum bearer token.", + "description": "Create an account and issue its first bearer token. Use it once per new user; send an Idempotency-Key so a retried request cannot create a second account. Returns the user with the token, its type and expiry in meta, and sends a verification email.", "auth": { "type": "noauth" } @@ -56,7 +56,7 @@ { "header": [], "code": 201, - "body": "{\"data\":{\"id\":\"01m5cb6hssde51qe3kn813thmv\",\"name\":\"Justina Gaylord\",\"email\":\"lafayette.considine@example.com\",\"email_verified_at\":\"2026-10-20T09:45:06+00:00\",\"created_at\":null,\"updated_at\":null},\"meta\":{\"token\":\"1|example-token\",\"token_type\":\"Bearer\",\"expires_at\":null}}", + "body": "{\"data\":{\"id\":\"01m5cdfjnp16kbfqq3s4xsnvb5\",\"name\":\"Justina Gaylord\",\"email\":\"lafayette.considine@example.com\",\"email_verified_at\":\"2026-10-20T10:24:59+00:00\",\"created_at\":null,\"updated_at\":null},\"meta\":{\"token\":\"1|example-token\",\"token_type\":\"Bearer\",\"expires_at\":null}}", "name": "Registration succeeded." }, { @@ -91,7 +91,7 @@ "mode": "raw", "raw": "{\"email\":\"jane@example.com\",\"password\":\"password123\",\"device_name\":\"ios-app\"}" }, - "description": "Authenticate a user and issue a Sanctum bearer token.", + "description": "Exchange an email and password for a bearer token. Use it when a user signs in on a new device, naming the device in device_name. Returns the user with the token, its type and expiry in meta; wrong credentials are a 422 on the email field.", "auth": { "type": "noauth" } @@ -100,7 +100,7 @@ { "header": [], "code": 200, - "body": "{\"data\":{\"id\":\"01m5cb6ht2em5q96y8t1rffqv6\",\"name\":\"Justina Gaylord\",\"email\":\"cormier.nick@example.com\",\"email_verified_at\":\"2026-10-20T09:45:06+00:00\",\"created_at\":null,\"updated_at\":null},\"meta\":{\"token\":\"1|example-token\",\"token_type\":\"Bearer\",\"expires_at\":null}}", + "body": "{\"data\":{\"id\":\"01m5cdfjp0cmx0zgvvy8a4z5zj\",\"name\":\"Justina Gaylord\",\"email\":\"cormier.nick@example.com\",\"email_verified_at\":\"2026-10-20T10:24:59+00:00\",\"created_at\":null,\"updated_at\":null},\"meta\":{\"token\":\"1|example-token\",\"token_type\":\"Bearer\",\"expires_at\":null}}", "name": "Login succeeded." }, { @@ -132,13 +132,13 @@ } ], "body": null, - "description": "Return the authenticated user for the current bearer token." + "description": "Return the user the bearer token belongs to. Use it to check a token still works and to read the account's profile and verification state. The response carries an ETag: send it back in If-None-Match and an unchanged user returns 304 with no body." }, "response": [ { "header": [], "code": 200, - "body": "{\"data\":{\"id\":\"01m5cb6htrjmdsahn6h774frrz\",\"name\":\"Morgan Hirthe\",\"email\":\"dare.emelie@example.com\",\"email_verified_at\":\"2026-10-20T09:45:06+00:00\",\"created_at\":null,\"updated_at\":null}}", + "body": "{\"data\":{\"id\":\"01m5cdfjpm8vqdmrdwtq6fqe98\",\"name\":\"Morgan Hirthe\",\"email\":\"dare.emelie@example.com\",\"email_verified_at\":\"2026-10-20T10:24:59+00:00\",\"created_at\":null,\"updated_at\":null}}", "name": "Authenticated user profile." }, { @@ -170,7 +170,7 @@ } ], "body": null, - "description": "Revoke the current Sanctum token." + "description": "Revoke the bearer token that made this request, and only that one. Use it when a client signs out; the user's other tokens keep working. Returns 204 with no body." }, "response": [ { @@ -182,7 +182,7 @@ { "header": [], "code": 401, - "body": "{\"message\":\"Unauthenticated.\"}", + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/unauthorized\",\"title\":\"Unauthorized\",\"status\":401,\"detail\":\"Unauthenticated.\"}", "name": "Authentication failed." } ] @@ -215,7 +215,7 @@ } ], "body": null, - "description": "List personal access tokens for the authenticated user." + "description": "List the authenticated user's personal access tokens, newest first, 25 to a page. Use it to show signed-in devices or to find a token ID to revoke. Returns an array of tokens, with is_current marking the one making the request; follow the Link header's rel=\"next\" for the next page." }, "response": [ { @@ -238,6 +238,59 @@ } ] }, + { + "name": "Create API Key", + "request": { + "url": { + "host": "{{baseUrl}}", + "path": "v1\/auth\/tokens", + "query": [], + "raw": "{{baseUrl}}\/v1\/auth\/tokens" + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application\/json" + }, + { + "key": "Accept", + "value": "application\/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\"name\":\"deploy-bot\",\"abilities\":[\"auth:me\",\"auth:tokens:read\"],\"expires_at\":\"2027-01-01T00:00:00+00:00\"}" + }, + "description": "Create a long-lived personal access token with chosen abilities, for a script, integration or agent that should not sign in with a password. It can only hold abilities the token making this request holds, and expires on expires_at, or after the configured default when that is left out. Returns the token with its plain-text value in meta.token, which is shown once and cannot be read again." + }, + "response": [ + { + "header": [], + "code": 201, + "body": "{\"data\":{\"id\":\"7\",\"name\":\"deploy-bot\",\"abilities\":[\"auth:me\",\"auth:tokens:read\"],\"last_used_at\":null,\"expires_at\":\"2027-01-01T00:00:00+00:00\",\"created_at\":\"2026-10-20T12:00:00+00:00\",\"updated_at\":\"2026-10-20T12:00:00+00:00\",\"is_current\":false},\"meta\":{\"token\":\"7|example-token\",\"token_type\":\"Bearer\"}}", + "name": "API key created. meta.token is the only time its value is returned." + }, + { + "header": [], + "code": 401, + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/unauthorized\",\"title\":\"Unauthorized\",\"status\":401,\"detail\":\"Unauthenticated.\"}", + "name": "Authentication failed." + }, + { + "header": [], + "code": 403, + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/forbidden\",\"title\":\"Forbidden\",\"status\":403,\"detail\":\"Forbidden.\"}", + "name": "Token is missing the auth:tokens:create ability." + }, + { + "header": [], + "code": 422, + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/validation-failed\",\"title\":\"Validation Failed\",\"status\":422,\"detail\":\"You can only grant abilities your current token holds.\",\"errors\":{\"abilities.0\":[\"You can only grant abilities your current token holds.\"]}}", + "name": "A requested ability is not held by this token, or the expiry is invalid." + } + ] + }, { "name": "Revoke All Tokens", "request": { @@ -259,7 +312,7 @@ } ], "body": null, - "description": "Revoke all personal access tokens for the authenticated user." + "description": "Revoke every personal access token the authenticated user holds, including the one making this request. Use it to sign out everywhere after a suspected compromise. Returns 204 with no body; every later request with these tokens is a 401." }, "response": [ { @@ -271,13 +324,13 @@ { "header": [], "code": 401, - "body": "{\"message\":\"Unauthenticated.\"}", + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/unauthorized\",\"title\":\"Unauthorized\",\"status\":401,\"detail\":\"Unauthenticated.\"}", "name": "Authentication failed." }, { "header": [], "code": 403, - "body": "{\"message\":\"Forbidden.\"}", + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/forbidden\",\"title\":\"Forbidden\",\"status\":403,\"detail\":\"Forbidden.\"}", "name": "Token is missing required ability." } ] @@ -310,11 +363,8 @@ "value": "application\/json" } ], - "body": { - "mode": "raw", - "raw": "{\"token_id\":16}" - }, - "description": "Revoke one personal access token owned by the authenticated user." + "body": null, + "description": "Revoke one of the authenticated user's personal access tokens by its ID, such as a lost device's. Use List Tokens to find the ID. Returns 204 with no body; a token the user does not own, or that no longer exists, is a 404." }, "response": [ { @@ -326,19 +376,19 @@ { "header": [], "code": 401, - "body": "{\"message\":\"Unauthenticated.\"}", + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/unauthorized\",\"title\":\"Unauthorized\",\"status\":401,\"detail\":\"Unauthenticated.\"}", "name": "Authentication failed." }, { "header": [], "code": 403, - "body": "{\"message\":\"Forbidden.\"}", + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/forbidden\",\"title\":\"Forbidden\",\"status\":403,\"detail\":\"Forbidden.\"}", "name": "Token is missing required ability." }, { "header": [], "code": 404, - "body": "{\"message\":\"Token not found.\"}", + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/resource-not-found\",\"title\":\"Resource Not Found\",\"status\":404,\"detail\":\"Token not found.\"}", "name": "Token does not belong to current user or no longer exists." } ] @@ -373,7 +423,7 @@ "mode": "raw", "raw": "{\"email\":\"jane@example.com\"}" }, - "description": "Send a password reset link to the provided email if an account exists.", + "description": "Email a password reset link to an address, if an account uses it. Use it from a forgot-password form. The response is the same whether or not the account exists, so it cannot be used to discover accounts; send an Idempotency-Key so a retry does not send a second email.", "auth": { "type": "noauth" } @@ -384,6 +434,18 @@ "code": 200, "body": "{\"message\":\"If the account exists, a password reset link has been sent.\"}", "name": "Password reset request accepted." + }, + { + "header": [], + "code": 422, + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/validation-failed\",\"title\":\"Validation Failed\",\"status\":422,\"detail\":\"The email field must be a valid email address.\",\"errors\":{\"email\":[\"The email field must be a valid email address.\"]}}", + "name": "The email was missing or not an email address." + }, + { + "header": [], + "code": 429, + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/rate-limit-exceeded\",\"title\":\"Rate Limit Exceeded\",\"status\":429,\"detail\":\"Too many requests. Please try again later.\"}", + "name": "Too many reset requests for this address; retry after the Retry-After header." } ] }, @@ -411,7 +473,7 @@ "mode": "raw", "raw": "{\"token\":\"reset-token-value\",\"email\":\"jane@example.com\",\"password\":\"new-password123\",\"password_confirmation\":\"new-password123\"}" }, - "description": "Reset the user password using a valid reset token.", + "description": "Set a new password using the token from a password reset email. Use it to finish the forgot-password flow. Returns a confirmation message; an invalid or expired token is a 422 on the email field.", "auth": { "type": "noauth" } @@ -466,11 +528,8 @@ "value": "application\/json" } ], - "body": { - "mode": "raw", - "raw": "{\"token\":\"architecto\",\"email\":\"zbailey@example.net\"}" - }, - "description": "Return reset token and email payload for API clients handling email reset links.", + "body": null, + "description": "Return the token and email from a password reset link, for a client that opens the link and shows its own reset form. It does not check the token; Reset Password does. Returns the token and the email, if the link carried one.", "auth": { "type": "noauth" } @@ -481,6 +540,12 @@ "code": 200, "body": "{\"token\":\"reset-token-value\",\"email\":\"jane@example.com\"}", "name": "Reset payload data." + }, + { + "header": [], + "code": 422, + "body": "{\"type\":\"https:\\\/\\\/apiguide.dev\\\/errors\\\/validation-failed\",\"title\":\"Validation Failed\",\"status\":422,\"detail\":\"The email field must be a valid email address.\",\"errors\":{\"email\":[\"The email field must be a valid email address.\"]}}", + "name": "The email query parameter was not an email address." } ] } @@ -524,11 +589,8 @@ "value": "application\/json" } ], - "body": { - "mode": "raw", - "raw": "{\"id\":\"architecto\",\"hash\":\"ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld\"}" - }, - "description": "Verify a user email using the signed verification link parameters.", + "body": null, + "description": "Mark the user's email as verified using the signed link from the verification email. Clients do not build this URL; they follow the one in the email, which expires. Returns a confirmation message; a link that is invalid, expired or altered is a 403.", "auth": { "type": "noauth" } @@ -569,7 +631,7 @@ } ], "body": null, - "description": "Send (or resend) an email verification link to the authenticated user." + "description": "Send the authenticated user a new email verification link. Use it when the first link expired or never arrived; it is limited to six requests a minute. Returns a message saying the link was sent, or that the email is already verified." }, "response": [ { diff --git a/public/docs/index.html b/public/docs/index.html index c70dec1..c5e7f82 100644 --- a/public/docs/index.html +++ b/public/docs/index.html @@ -89,6 +89,9 @@ </li> <li class="tocify-item level-3" data-unique="authentication-GETv1-auth-tokens"> <a href="#authentication-GETv1-auth-tokens">List Tokens</a> + </li> + <li class="tocify-item level-3" data-unique="authentication-POSTv1-auth-tokens"> + <a href="#authentication-POSTv1-auth-tokens">Create API Key</a> </li> <li class="tocify-item level-3" data-unique="authentication-DELETEv1-auth-tokens"> <a href="#authentication-DELETEv1-auth-tokens">Revoke All Tokens</a> @@ -164,7 +167,7 @@ <h2 id="authentication-POSTv1-auth-register">Register</h2> <p> </p> -<p>Create a new account and issue a Sanctum bearer token.</p> +<p>Create an account and issue its first bearer token. Use it once per new user; send an Idempotency-Key so a retried request cannot create a second account. Returns the user with the token, its type and expiry in meta, and sends a verification email.</p> <span id="example-requests-POSTv1-auth-register"> <blockquote>Example request:</blockquote> @@ -217,10 +220,10 @@ <h2 id="authentication-POSTv1-auth-register">Register</h2> <code class="language-json" style="max-height: 300px;">{ "data": { - "id": "01m5cb6hssde51qe3kn813thmv", + "id": "01m5cdfjnp16kbfqq3s4xsnvb5", "name": "Justina Gaylord", "email": "lafayette.considine@example.com", - "email_verified_at": "2026-10-20T09:45:06+00:00", + "email_verified_at": "2026-10-20T10:24:59+00:00", "created_at": null, "updated_at": null }, @@ -376,7 +379,7 @@ <h2 id="authentication-POSTv1-auth-login">Login</h2> <p> </p> -<p>Authenticate a user and issue a Sanctum bearer token.</p> +<p>Exchange an email and password for a bearer token. Use it when a user signs in on a new device, naming the device in device_name. Returns the user with the token, its type and expiry in meta; wrong credentials are a 422 on the email field.</p> <span id="example-requests-POSTv1-auth-login"> <blockquote>Example request:</blockquote> @@ -427,10 +430,10 @@ <h2 id="authentication-POSTv1-auth-login">Login</h2> <code class="language-json" style="max-height: 300px;">{ "data": { - "id": "01m5cb6ht2em5q96y8t1rffqv6", + "id": "01m5cdfjp0cmx0zgvvy8a4z5zj", "name": "Justina Gaylord", "email": "cormier.nick@example.com", - "email_verified_at": "2026-10-20T09:45:06+00:00", + "email_verified_at": "2026-10-20T10:24:59+00:00", "created_at": null, "updated_at": null }, @@ -575,7 +578,7 @@ <h2 id="authentication-GETv1-auth-me">Get Current User</h2> <small class="badge badge-darkred">requires authentication</small> </p> -<p>Return the authenticated user for the current bearer token.</p> +<p>Return the user the bearer token belongs to. Use it to check a token still works and to read the account's profile and verification state. The response carries an ETag: send it back in If-None-Match and an unchanged user returns 304 with no body.</p> <span id="example-requests-GETv1-auth-me"> <blockquote>Example request:</blockquote> @@ -615,10 +618,10 @@ <h2 id="authentication-GETv1-auth-me">Get Current User</h2> <code class="language-json" style="max-height: 300px;">{ "data": { - "id": "01m5cb6htrjmdsahn6h774frrz", + "id": "01m5cdfjpm8vqdmrdwtq6fqe98", "name": "Morgan Hirthe", "email": "dare.emelie@example.com", - "email_verified_at": "2026-10-20T09:45:06+00:00", + "email_verified_at": "2026-10-20T10:24:59+00:00", "created_at": null, "updated_at": null } @@ -728,7 +731,7 @@ <h2 id="authentication-POSTv1-auth-logout">Logout</h2> <small class="badge badge-darkred">requires authentication</small> </p> -<p>Revoke the current Sanctum token.</p> +<p>Revoke the bearer token that made this request, and only that one. Use it when a client signs out; the user's other tokens keep working. Returns 204 with no body.</p> <span id="example-requests-POSTv1-auth-logout"> <blockquote>Example request:</blockquote> @@ -773,7 +776,10 @@ <h2 id="authentication-POSTv1-auth-logout">Logout</h2> <pre> <code class="language-json" style="max-height: 300px;">{ - "message": "Unauthenticated." + "type": "https://apiguide.dev/errors/unauthorized", + "title": "Unauthorized", + "status": 401, + "detail": "Unauthenticated." }</code> </pre> </span> @@ -868,7 +874,7 @@ <h2 id="authentication-GETv1-auth-tokens">List Tokens</h2> <small class="badge badge-darkred">requires authentication</small> </p> -<p>List personal access tokens for the authenticated user.</p> +<p>List the authenticated user's personal access tokens, newest first, 25 to a page. Use it to show signed-in devices or to find a token ID to revoke. Returns an array of tokens, with is_current marking the one making the request; follow the Link header's rel="next" for the next page.</p> <span id="example-requests-GETv1-auth-tokens"> <blockquote>Example request:</blockquote> @@ -1051,13 +1057,262 @@ <h4 class="fancy-heading-panel"><b>Query Parameters</b></h4> </div> </form> + <h2 id="authentication-POSTv1-auth-tokens">Create API Key</h2> + +<p> +<small class="badge badge-darkred">requires authentication</small> +</p> + +<p>Create a long-lived personal access token with chosen abilities, for a script, integration or agent that should not sign in with a password. It can only hold abilities the token making this request holds, and expires on expires_at, or after the configured default when that is left out. Returns the token with its plain-text value in meta.token, which is shown once and cannot be read again.</p> + +<span id="example-requests-POSTv1-auth-tokens"> +<blockquote>Example request:</blockquote> + + +<div class="bash-example"> + <pre><code class="language-bash">curl --request POST \ + "http://localhost/v1/auth/tokens" \ + --header "Authorization: Bearer {YOUR_BEARER_TOKEN}" \ + --header "Content-Type: application/json" \ + --header "Accept: application/json" \ + --data "{ + \"name\": \"deploy-bot\", + \"abilities\": [ + \"auth:me\", + \"auth:tokens:read\" + ], + \"expires_at\": \"2027-01-01T00:00:00+00:00\" +}" +</code></pre></div> + + +<div class="javascript-example"> + <pre><code class="language-javascript">const url = new URL( + "http://localhost/v1/auth/tokens" +); + +const headers = { + "Authorization": "Bearer {YOUR_BEARER_TOKEN}", + "Content-Type": "application/json", + "Accept": "application/json", +}; + +let body = { + "name": "deploy-bot", + "abilities": [ + "auth:me", + "auth:tokens:read" + ], + "expires_at": "2027-01-01T00:00:00+00:00" +}; + +fetch(url, { + method: "POST", + headers, + body: JSON.stringify(body), +}).then(response => response.json());</code></pre></div> + +</span> + +<span id="example-responses-POSTv1-auth-tokens"> + <blockquote> + <p>Example response (201, API key created. meta.token is the only time its value is returned.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "data": { + "id": "7", + "name": "deploy-bot", + "abilities": [ + "auth:me", + "auth:tokens:read" + ], + "last_used_at": null, + "expires_at": "2027-01-01T00:00:00+00:00", + "created_at": "2026-10-20T12:00:00+00:00", + "updated_at": "2026-10-20T12:00:00+00:00", + "is_current": false + }, + "meta": { + "token": "7|example-token", + "token_type": "Bearer" + } +}</code> + </pre> + <blockquote> + <p>Example response (401, Authentication failed.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "type": "https://apiguide.dev/errors/unauthorized", + "title": "Unauthorized", + "status": 401, + "detail": "Unauthenticated." +}</code> + </pre> + <blockquote> + <p>Example response (403, Token is missing the auth:tokens:create ability.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "type": "https://apiguide.dev/errors/forbidden", + "title": "Forbidden", + "status": 403, + "detail": "Forbidden." +}</code> + </pre> + <blockquote> + <p>Example response (422, A requested ability is not held by this token, or the expiry is invalid.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "type": "https://apiguide.dev/errors/validation-failed", + "title": "Validation Failed", + "status": 422, + "detail": "You can only grant abilities your current token holds.", + "errors": { + "abilities.0": [ + "You can only grant abilities your current token holds." + ] + } +}</code> + </pre> + </span> +<span id="execution-results-POSTv1-auth-tokens" hidden> + <blockquote>Received response<span + id="execution-response-status-POSTv1-auth-tokens"></span>: + </blockquote> + <pre class="json"><code id="execution-response-content-POSTv1-auth-tokens" + data-empty-response-text="<Empty response>" style="max-height: 400px;"></code></pre> +</span> +<span id="execution-error-POSTv1-auth-tokens" hidden> + <blockquote>Request failed with error:</blockquote> + <pre><code id="execution-error-message-POSTv1-auth-tokens"> + +Tip: Check that you're properly connected to the network. +If you're a maintainer of ths API, verify that your API is running and you've enabled CORS. +You can check the Dev Tools console for debugging information.</code></pre> +</span> +<form id="form-POSTv1-auth-tokens" data-method="POST" + data-path="v1/auth/tokens" + data-authed="1" + data-hasfiles="0" + data-isarraybody="0" + autocomplete="off" + onsubmit="event.preventDefault(); executeTryOut('POSTv1-auth-tokens', this);"> + <h3> + Request    + <button type="button" + style="background-color: #8fbcd4; padding: 5px 10px; border-radius: 5px; border-width: thin;" + id="btn-tryout-POSTv1-auth-tokens" + onclick="tryItOut('POSTv1-auth-tokens');">Try it out ⚡ + </button> + <button type="button" + style="background-color: #c97a7e; padding: 5px 10px; border-radius: 5px; border-width: thin;" + id="btn-canceltryout-POSTv1-auth-tokens" + onclick="cancelTryOut('POSTv1-auth-tokens');" hidden>Cancel 🛑 + </button>   + <button type="submit" + style="background-color: #6ac174; padding: 5px 10px; border-radius: 5px; border-width: thin;" + id="btn-executetryout-POSTv1-auth-tokens" + data-initial-text="Send Request 💥" + data-loading-text="⏱ Sending..." + hidden>Send Request 💥 + </button> + </h3> + <p> + <small class="badge badge-black">POST</small> + <b><code>v1/auth/tokens</code></b> + </p> + <h4 class="fancy-heading-panel"><b>Headers</b></h4> + <div style="padding-left: 28px; clear: unset;"> + <b style="line-height: 2;"><code>Authorization</code></b>   +  +   +   + <input type="text" style="display: none" + name="Authorization" class="auth-value" data-endpoint="POSTv1-auth-tokens" + value="Bearer {YOUR_BEARER_TOKEN}" + data-component="header"> + <br> +<p>Example: <code>Bearer {YOUR_BEARER_TOKEN}</code></p> + </div> + <div style="padding-left: 28px; clear: unset;"> + <b style="line-height: 2;"><code>Content-Type</code></b>   +  +   +   + <input type="text" style="display: none" + name="Content-Type" data-endpoint="POSTv1-auth-tokens" + value="application/json" + data-component="header"> + <br> +<p>Example: <code>application/json</code></p> + </div> + <div style="padding-left: 28px; clear: unset;"> + <b style="line-height: 2;"><code>Accept</code></b>   +  +   +   + <input type="text" style="display: none" + name="Accept" data-endpoint="POSTv1-auth-tokens" + value="application/json" + data-component="header"> + <br> +<p>Example: <code>application/json</code></p> + </div> + <h4 class="fancy-heading-panel"><b>Body Parameters</b></h4> + <div style=" padding-left: 28px; clear: unset;"> + <b style="line-height: 2;"><code>name</code></b>   +<small>string</small>  +   +   + <input type="text" style="display: none" + name="name" data-endpoint="POSTv1-auth-tokens" + value="deploy-bot" + data-component="body"> + <br> +<p>A label for the key, shown when listing tokens. Example: <code>deploy-bot</code></p> + </div> + <div style=" padding-left: 28px; clear: unset;"> + <b style="line-height: 2;"><code>abilities</code></b>   +<small>string[]</small>  +   +   + <input type="text" style="display: none" + name="abilities[0]" data-endpoint="POSTv1-auth-tokens" + data-component="body"> + <input type="text" style="display: none" + name="abilities[1]" data-endpoint="POSTv1-auth-tokens" + data-component="body"> + <br> +<p>Abilities to grant, each one held by the token making this request.</p> + </div> + <div style=" padding-left: 28px; clear: unset;"> + <b style="line-height: 2;"><code>expires_at</code></b>   +<small>string</small>  +<i>optional</i>   +   + <input type="text" style="display: none" + name="expires_at" data-endpoint="POSTv1-auth-tokens" + value="2027-01-01T00:00:00+00:00" + data-component="body"> + <br> +<p>ISO 8601 expiry, in the future and no later than the configured maximum (365 days by default). Leave it out for the default (90 days). Example: <code>2027-01-01T00:00:00+00:00</code></p> + </div> + </form> + <h2 id="authentication-DELETEv1-auth-tokens">Revoke All Tokens</h2> <p> <small class="badge badge-darkred">requires authentication</small> </p> -<p>Revoke all personal access tokens for the authenticated user.</p> +<p>Revoke every personal access token the authenticated user holds, including the one making this request. Use it to sign out everywhere after a suspected compromise. Returns 204 with no body; every later request with these tokens is a 401.</p> <span id="example-requests-DELETEv1-auth-tokens"> <blockquote>Example request:</blockquote> @@ -1102,7 +1357,10 @@ <h2 id="authentication-DELETEv1-auth-tokens">Revoke All Tokens</h2> <pre> <code class="language-json" style="max-height: 300px;">{ - "message": "Unauthenticated." + "type": "https://apiguide.dev/errors/unauthorized", + "title": "Unauthorized", + "status": 401, + "detail": "Unauthenticated." }</code> </pre> <blockquote> @@ -1111,7 +1369,10 @@ <h2 id="authentication-DELETEv1-auth-tokens">Revoke All Tokens</h2> <pre> <code class="language-json" style="max-height: 300px;">{ - "message": "Forbidden." + "type": "https://apiguide.dev/errors/forbidden", + "title": "Forbidden", + "status": 403, + "detail": "Forbidden." }</code> </pre> </span> @@ -1206,7 +1467,7 @@ <h2 id="authentication-DELETEv1-auth-tokens--token_id-">Revoke Token</h2> <small class="badge badge-darkred">requires authentication</small> </p> -<p>Revoke one personal access token owned by the authenticated user.</p> +<p>Revoke one of the authenticated user's personal access tokens by its ID, such as a lost device's. Use List Tokens to find the ID. Returns 204 with no body; a token the user does not own, or that no longer exists, is a 404.</p> <span id="example-requests-DELETEv1-auth-tokens--token_id-"> <blockquote>Example request:</blockquote> @@ -1217,11 +1478,7 @@ <h2 id="authentication-DELETEv1-auth-tokens--token_id-">Revoke Token</h2> "http://localhost/v1/auth/tokens/42" \ --header "Authorization: Bearer {YOUR_BEARER_TOKEN}" \ --header "Content-Type: application/json" \ - --header "Accept: application/json" \ - --data "{ - \"token_id\": 16 -}" -</code></pre></div> + --header "Accept: application/json"</code></pre></div> <div class="javascript-example"> @@ -1235,14 +1492,9 @@ <h2 id="authentication-DELETEv1-auth-tokens--token_id-">Revoke Token</h2> "Accept": "application/json", }; -let body = { - "token_id": 16 -}; - fetch(url, { method: "DELETE", headers, - body: JSON.stringify(body), }).then(response => response.json());</code></pre></div> </span> @@ -1260,7 +1512,10 @@ <h2 id="authentication-DELETEv1-auth-tokens--token_id-">Revoke Token</h2> <pre> <code class="language-json" style="max-height: 300px;">{ - "message": "Unauthenticated." + "type": "https://apiguide.dev/errors/unauthorized", + "title": "Unauthorized", + "status": 401, + "detail": "Unauthenticated." }</code> </pre> <blockquote> @@ -1269,7 +1524,10 @@ <h2 id="authentication-DELETEv1-auth-tokens--token_id-">Revoke Token</h2> <pre> <code class="language-json" style="max-height: 300px;">{ - "message": "Forbidden." + "type": "https://apiguide.dev/errors/forbidden", + "title": "Forbidden", + "status": 403, + "detail": "Forbidden." }</code> </pre> <blockquote> @@ -1278,7 +1536,10 @@ <h2 id="authentication-DELETEv1-auth-tokens--token_id-">Revoke Token</h2> <pre> <code class="language-json" style="max-height: 300px;">{ - "message": "Token not found." + "type": "https://apiguide.dev/errors/resource-not-found", + "title": "Resource Not Found", + "status": 404, + "detail": "Token not found." }</code> </pre> </span> @@ -1378,20 +1639,7 @@ <h4 class="fancy-heading-panel"><b>URL Parameters</b></h4> <br> <p>Personal access token id. Example: <code>42</code></p> </div> - <h4 class="fancy-heading-panel"><b>Body Parameters</b></h4> - <div style=" padding-left: 28px; clear: unset;"> - <b style="line-height: 2;"><code>token_id</code></b>   -<small>integer</small>  -   -   - <input type="number" style="display: none" - step="any" name="token_id" data-endpoint="DELETEv1-auth-tokens--token_id-" - value="16" - data-component="body"> - <br> -<p>Example: <code>16</code></p> - </div> - </form> + </form> <h2 id="authentication-password-reset">Password Reset</h2> <h2 id="authentication-POSTv1-auth-password-forgot">Request Password Reset</h2> @@ -1399,7 +1647,7 @@ <h2 id="authentication-POSTv1-auth-password-forgot">Request Password Reset</h2> <p> </p> -<p>Send a password reset link to the provided email if an account exists.</p> +<p>Email a password reset link to an address, if an account uses it. Use it from a forgot-password form. The response is the same whether or not the account exists, so it cannot be used to discover accounts; send an Idempotency-Key so a retry does not send a second email.</p> <span id="example-requests-POSTv1-auth-password-forgot"> <blockquote>Example request:</blockquote> @@ -1446,6 +1694,35 @@ <h2 id="authentication-POSTv1-auth-password-forgot">Request Password Reset</h2> <code class="language-json" style="max-height: 300px;">{ "message": "If the account exists, a password reset link has been sent." +}</code> + </pre> + <blockquote> + <p>Example response (422, The email was missing or not an email address.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "type": "https://apiguide.dev/errors/validation-failed", + "title": "Validation Failed", + "status": 422, + "detail": "The email field must be a valid email address.", + "errors": { + "email": [ + "The email field must be a valid email address." + ] + } +}</code> + </pre> + <blockquote> + <p>Example response (429, Too many reset requests for this address; retry after the Retry-After header.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "type": "https://apiguide.dev/errors/rate-limit-exceeded", + "title": "Rate Limit Exceeded", + "status": 429, + "detail": "Too many requests. Please try again later." }</code> </pre> </span> @@ -1540,7 +1817,7 @@ <h2 id="authentication-POSTv1-auth-password-reset">Reset Password</h2> <p> </p> -<p>Reset the user password using a valid reset token.</p> +<p>Set a new password using the token from a password reset email. Use it to finish the forgot-password flow. Returns a confirmation message; an invalid or expired token is a 422 on the email field.</p> <span id="example-requests-POSTv1-auth-password-reset"> <blockquote>Example request:</blockquote> @@ -1740,7 +2017,7 @@ <h2 id="authentication-GETv1-auth-password-reset--token-">Read Reset Token Paylo <p> </p> -<p>Return reset token and email payload for API clients handling email reset links.</p> +<p>Return the token and email from a password reset link, for a client that opens the link and shows its own reset form. It does not check the token; Reset Password does. Returns the token and the email, if the link carried one.</p> <span id="example-requests-GETv1-auth-password-reset--token-"> <blockquote>Example request:</blockquote> @@ -1750,12 +2027,7 @@ <h2 id="authentication-GETv1-auth-password-reset--token-">Read Reset Token Paylo <pre><code class="language-bash">curl --request GET \ --get "http://localhost/v1/auth/password/reset/reset-token-value?email=jane%40example.com" \ --header "Content-Type: application/json" \ - --header "Accept: application/json" \ - --data "{ - \"token\": \"architecto\", - \"email\": \"zbailey@example.net\" -}" -</code></pre></div> + --header "Accept: application/json"</code></pre></div> <div class="javascript-example"> @@ -1774,15 +2046,9 @@ <h2 id="authentication-GETv1-auth-password-reset--token-">Read Reset Token Paylo "Accept": "application/json", }; -let body = { - "token": "architecto", - "email": "zbailey@example.net" -}; - fetch(url, { method: "GET", headers, - body: JSON.stringify(body), }).then(response => response.json());</code></pre></div> </span> @@ -1796,6 +2062,23 @@ <h2 id="authentication-GETv1-auth-password-reset--token-">Read Reset Token Paylo <code class="language-json" style="max-height: 300px;">{ "token": "reset-token-value", "email": "jane@example.com" +}</code> + </pre> + <blockquote> + <p>Example response (422, The email query parameter was not an email address.):</p> + </blockquote> + <pre> + +<code class="language-json" style="max-height: 300px;">{ + "type": "https://apiguide.dev/errors/validation-failed", + "title": "Validation Failed", + "status": 422, + "detail": "The email field must be a valid email address.", + "errors": { + "email": [ + "The email field must be a valid email address." + ] + } }</code> </pre> </span> @@ -1896,32 +2179,7 @@ <h4 class="fancy-heading-panel"><b>Query Parameters</b></h4> <br> <p>Account email from the reset link. Example: <code>jane@example.com</code></p> </div> - <h4 class="fancy-heading-panel"><b>Body Parameters</b></h4> - <div style=" padding-left: 28px; clear: unset;"> - <b style="line-height: 2;"><code>token</code></b>   -<small>string</small>  -   -   - <input type="text" style="display: none" - name="token" data-endpoint="GETv1-auth-password-reset--token-" - value="architecto" - data-component="body"> - <br> -<p>Example: <code>architecto</code></p> - </div> - <div style=" padding-left: 28px; clear: unset;"> - <b style="line-height: 2;"><code>email</code></b>   -<small>string</small>  -<i>optional</i>   -   - <input type="text" style="display: none" - name="email" data-endpoint="GETv1-auth-password-reset--token-" - value="zbailey@example.net" - data-component="body"> - <br> -<p>Must be a valid email address. Must not be greater than 255 characters. Example: <code>zbailey@example.net</code></p> - </div> - </form> + </form> <h2 id="authentication-email-verification">Email Verification</h2> <h2 id="authentication-GETv1-auth-email-verify--id---hash-">Verify Email</h2> @@ -1929,7 +2187,7 @@ <h2 id="authentication-GETv1-auth-email-verify--id---hash-">Verify Email</h2> <p> </p> -<p>Verify a user email using the signed verification link parameters.</p> +<p>Mark the user's email as verified using the signed link from the verification email. Clients do not build this URL; they follow the one in the email, which expires. Returns a confirmation message; a link that is invalid, expired or altered is a 403.</p> <span id="example-requests-GETv1-auth-email-verify--id---hash-"> <blockquote>Example request:</blockquote> @@ -1939,12 +2197,7 @@ <h2 id="authentication-GETv1-auth-email-verify--id---hash-">Verify Email</h2> <pre><code class="language-bash">curl --request GET \ --get "http://localhost/v1/auth/email/verify/01HZX3W3T4J8Q57XNZD5BPHJ92/8c4f4370e5db9b5be6d0f4c95495f49f998fa32a" \ --header "Content-Type: application/json" \ - --header "Accept: application/json" \ - --data "{ - \"id\": \"architecto\", - \"hash\": \"ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld\" -}" -</code></pre></div> + --header "Accept: application/json"</code></pre></div> <div class="javascript-example"> @@ -1957,15 +2210,9 @@ <h2 id="authentication-GETv1-auth-email-verify--id---hash-">Verify Email</h2> "Accept": "application/json", }; -let body = { - "id": "architecto", - "hash": "ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld" -}; - fetch(url, { method: "GET", headers, - body: JSON.stringify(body), }).then(response => response.json());</code></pre></div> </span> @@ -2089,32 +2336,7 @@ <h4 class="fancy-heading-panel"><b>URL Parameters</b></h4> <br> <p>SHA-1 hash of the email from the signed verification link. Example: <code>8c4f4370e5db9b5be6d0f4c95495f49f998fa32a</code></p> </div> - <h4 class="fancy-heading-panel"><b>Body Parameters</b></h4> - <div style=" padding-left: 28px; clear: unset;"> - <b style="line-height: 2;"><code>id</code></b>   -<small>string</small>  -   -   - <input type="text" style="display: none" - name="id" data-endpoint="GETv1-auth-email-verify--id---hash-" - value="architecto" - data-component="body"> - <br> -<p>Must match an existing stored value. Example: <code>architecto</code></p> - </div> - <div style=" padding-left: 28px; clear: unset;"> - <b style="line-height: 2;"><code>hash</code></b>   -<small>string</small>  -   -   - <input type="text" style="display: none" - name="hash" data-endpoint="GETv1-auth-email-verify--id---hash-" - value="ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld" - data-component="body"> - <br> -<p>Must be 40 characters. Example: <code>ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld</code></p> - </div> - </form> + </form> <h2 id="authentication-POSTv1-auth-email-verification-notification">Send Verification Email</h2> @@ -2122,7 +2344,7 @@ <h2 id="authentication-POSTv1-auth-email-verification-notification">Send Verific <small class="badge badge-darkred">requires authentication</small> </p> -<p>Send (or resend) an email verification link to the authenticated user.</p> +<p>Send the authenticated user a new email verification link. Use it when the first link expired or never arrived; it is limited to six requests a minute. Returns a message saying the link was sent, or that the email is already verified.</p> <span id="example-requests-POSTv1-auth-email-verification-notification"> <blockquote>Example request:</blockquote> diff --git a/public/docs/openapi.yaml b/public/docs/openapi.yaml index 52384ee..143133b 100644 --- a/public/docs/openapi.yaml +++ b/public/docs/openapi.yaml @@ -24,7 +24,7 @@ paths: post: summary: Register operationId: register - description: 'Create a new account and issue a Sanctum bearer token.' + description: 'Create an account and issue its first bearer token. Use it once per new user; send an Idempotency-Key so a retried request cannot create a second account. Returns the user with the token, its type and expiry in meta, and sends a verification email.' parameters: [] responses: 201: @@ -35,10 +35,10 @@ paths: type: object example: data: - id: 01m5cb6hssde51qe3kn813thmv + id: 01m5cdfjnp16kbfqq3s4xsnvb5 name: 'Justina Gaylord' email: lafayette.considine@example.com - email_verified_at: '2026-10-20T09:45:06+00:00' + email_verified_at: '2026-10-20T10:24:59+00:00' created_at: null updated_at: null meta: @@ -51,7 +51,7 @@ paths: properties: id: type: string - example: 01m5cb6hssde51qe3kn813thmv + example: 01m5cdfjnp16kbfqq3s4xsnvb5 name: type: string example: 'Justina Gaylord' @@ -60,7 +60,7 @@ paths: example: lafayette.considine@example.com email_verified_at: type: string - example: '2026-10-20T09:45:06+00:00' + example: '2026-10-20T10:24:59+00:00' created_at: type: string example: null @@ -152,7 +152,7 @@ paths: post: summary: Login operationId: login - description: 'Authenticate a user and issue a Sanctum bearer token.' + description: 'Exchange an email and password for a bearer token. Use it when a user signs in on a new device, naming the device in device_name. Returns the user with the token, its type and expiry in meta; wrong credentials are a 422 on the email field.' parameters: [] responses: 200: @@ -163,10 +163,10 @@ paths: type: object example: data: - id: 01m5cb6ht2em5q96y8t1rffqv6 + id: 01m5cdfjp0cmx0zgvvy8a4z5zj name: 'Justina Gaylord' email: cormier.nick@example.com - email_verified_at: '2026-10-20T09:45:06+00:00' + email_verified_at: '2026-10-20T10:24:59+00:00' created_at: null updated_at: null meta: @@ -179,7 +179,7 @@ paths: properties: id: type: string - example: 01m5cb6ht2em5q96y8t1rffqv6 + example: 01m5cdfjp0cmx0zgvvy8a4z5zj name: type: string example: 'Justina Gaylord' @@ -188,7 +188,7 @@ paths: example: cormier.nick@example.com email_verified_at: type: string - example: '2026-10-20T09:45:06+00:00' + example: '2026-10-20T10:24:59+00:00' created_at: type: string example: null @@ -276,7 +276,7 @@ paths: post: summary: 'Request Password Reset' operationId: requestPasswordReset - description: 'Send a password reset link to the provided email if an account exists.' + description: 'Email a password reset link to an address, if an account uses it. Use it from a forgot-password form. The response is the same whether or not the account exists, so it cannot be used to discover accounts; send an Idempotency-Key so a retry does not send a second email.' parameters: [] responses: 200: @@ -291,6 +291,66 @@ paths: message: type: string example: 'If the account exists, a password reset link has been sent.' + 422: + description: 'The email was missing or not an email address.' + content: + application/problem+json: + schema: + type: object + example: + type: 'https://apiguide.dev/errors/validation-failed' + title: 'Validation Failed' + status: 422 + detail: 'The email field must be a valid email address.' + errors: + email: + - 'The email field must be a valid email address.' + properties: + type: + type: string + example: 'https://apiguide.dev/errors/validation-failed' + title: + type: string + example: 'Validation Failed' + status: + type: integer + example: 422 + detail: + type: string + example: 'The email field must be a valid email address.' + errors: + type: object + properties: + email: + type: array + example: + - 'The email field must be a valid email address.' + items: + type: string + 429: + description: 'Too many reset requests for this address; retry after the Retry-After header.' + content: + application/problem+json: + schema: + type: object + example: + type: 'https://apiguide.dev/errors/rate-limit-exceeded' + title: 'Rate Limit Exceeded' + status: 429 + detail: 'Too many requests. Please try again later.' + properties: + type: + type: string + example: 'https://apiguide.dev/errors/rate-limit-exceeded' + title: + type: string + example: 'Rate Limit Exceeded' + status: + type: integer + example: 429 + detail: + type: string + example: 'Too many requests. Please try again later.' tags: - Authentication requestBody: @@ -311,7 +371,7 @@ paths: post: summary: 'Reset Password' operationId: resetPassword - description: 'Reset the user password using a valid reset token.' + description: 'Set a new password using the token from a password reset email. Use it to finish the forgot-password flow. Returns a confirmation message; an invalid or expired token is a 422 on the email field.' parameters: [] responses: 200: @@ -397,7 +457,7 @@ paths: get: summary: 'Read Reset Token Payload' operationId: readResetTokenPayload - description: 'Return reset token and email payload for API clients handling email reset links.' + description: 'Return the token and email from a password reset link, for a client that opens the link and shows its own reset form. It does not check the token; Reset Password does. Returns the token and the email, if the link carried one.' parameters: - in: query @@ -426,26 +486,44 @@ paths: email: type: string example: jane@example.com + 422: + description: 'The email query parameter was not an email address.' + content: + application/problem+json: + schema: + type: object + example: + type: 'https://apiguide.dev/errors/validation-failed' + title: 'Validation Failed' + status: 422 + detail: 'The email field must be a valid email address.' + errors: + email: + - 'The email field must be a valid email address.' + properties: + type: + type: string + example: 'https://apiguide.dev/errors/validation-failed' + title: + type: string + example: 'Validation Failed' + status: + type: integer + example: 422 + detail: + type: string + example: 'The email field must be a valid email address.' + errors: + type: object + properties: + email: + type: array + example: + - 'The email field must be a valid email address.' + items: + type: string tags: - Authentication - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - token: - type: string - description: '' - example: architecto - email: - type: string - description: 'Must be a valid email address. Must not be greater than 255 characters.' - example: zbailey@example.net - nullable: true - required: - - token security: [] parameters: - @@ -460,7 +538,7 @@ paths: get: summary: 'Verify Email' operationId: verifyEmail - description: 'Verify a user email using the signed verification link parameters.' + description: "Mark the user's email as verified using the signed link from the verification email. Clients do not build this URL; they follow the one in the email, which expires. Returns a confirmation message; a link that is invalid, expired or altered is a 403." parameters: [] responses: 200: @@ -501,24 +579,6 @@ paths: example: 'Invalid verification link.' tags: - Authentication - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - id: - type: string - description: 'Must match an existing stored value.' - example: architecto - hash: - type: string - description: 'Must be 40 characters.' - example: ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld - required: - - id - - hash security: [] parameters: - @@ -541,7 +601,7 @@ paths: get: summary: 'Get Current User' operationId: getCurrentUser - description: 'Return the authenticated user for the current bearer token.' + description: "Return the user the bearer token belongs to. Use it to check a token still works and to read the account's profile and verification state. The response carries an ETag: send it back in If-None-Match and an unchanged user returns 304 with no body." parameters: [] responses: 200: @@ -552,10 +612,10 @@ paths: type: object example: data: - id: 01m5cb6htrjmdsahn6h774frrz + id: 01m5cdfjpm8vqdmrdwtq6fqe98 name: 'Morgan Hirthe' email: dare.emelie@example.com - email_verified_at: '2026-10-20T09:45:06+00:00' + email_verified_at: '2026-10-20T10:24:59+00:00' created_at: null updated_at: null properties: @@ -564,7 +624,7 @@ paths: properties: id: type: string - example: 01m5cb6htrjmdsahn6h774frrz + example: 01m5cdfjpm8vqdmrdwtq6fqe98 name: type: string example: 'Morgan Hirthe' @@ -573,7 +633,7 @@ paths: example: dare.emelie@example.com email_verified_at: type: string - example: '2026-10-20T09:45:06+00:00' + example: '2026-10-20T10:24:59+00:00' created_at: type: string example: null @@ -612,16 +672,11 @@ paths: post: summary: Logout operationId: logout - description: 'Revoke the current Sanctum token.' + description: "Revoke the bearer token that made this request, and only that one. Use it when a client signs out; the user's other tokens keep working. Returns 204 with no body." parameters: [] responses: 204: description: 'Token revoked.' - content: - application/json: - schema: - type: object - nullable: true 401: description: 'Authentication failed.' content: @@ -629,9 +684,21 @@ paths: schema: type: object example: - message: Unauthenticated. + type: 'https://apiguide.dev/errors/unauthorized' + title: Unauthorized + status: 401 + detail: Unauthenticated. properties: - message: + type: + type: string + example: 'https://apiguide.dev/errors/unauthorized' + title: + type: string + example: Unauthorized + status: + type: integer + example: 401 + detail: type: string example: Unauthenticated. tags: @@ -640,7 +707,7 @@ paths: get: summary: 'List Tokens' operationId: listTokens - description: 'List personal access tokens for the authenticated user.' + description: 'List the authenticated user''s personal access tokens, newest first, 25 to a page. Use it to show signed-in devices or to find a token ID to revoke. Returns an array of tokens, with is_current marking the one making the request; follow the Link header''s rel="next" for the next page.' parameters: - in: query @@ -753,19 +820,195 @@ paths: example: Forbidden. tags: - Authentication + post: + summary: 'Create API Key' + operationId: createAPIKey + description: 'Create a long-lived personal access token with chosen abilities, for a script, integration or agent that should not sign in with a password. It can only hold abilities the token making this request holds, and expires on expires_at, or after the configured default when that is left out. Returns the token with its plain-text value in meta.token, which is shown once and cannot be read again.' + parameters: [] + responses: + 201: + description: 'API key created. meta.token is the only time its value is returned.' + content: + application/json: + schema: + type: object + example: + data: + id: '7' + name: deploy-bot + abilities: + - 'auth:me' + - 'auth:tokens:read' + last_used_at: null + expires_at: '2027-01-01T00:00:00+00:00' + created_at: '2026-10-20T12:00:00+00:00' + updated_at: '2026-10-20T12:00:00+00:00' + is_current: false + meta: + token: 7|example-token + token_type: Bearer + properties: + data: + type: object + properties: + id: + type: string + example: '7' + name: + type: string + example: deploy-bot + abilities: + type: array + example: + - 'auth:me' + - 'auth:tokens:read' + items: + type: string + last_used_at: + type: string + example: null + nullable: true + expires_at: + type: string + example: '2027-01-01T00:00:00+00:00' + created_at: + type: string + example: '2026-10-20T12:00:00+00:00' + updated_at: + type: string + example: '2026-10-20T12:00:00+00:00' + is_current: + type: boolean + example: false + meta: + type: object + properties: + token: + type: string + example: 7|example-token + token_type: + type: string + example: Bearer + 401: + description: 'Authentication failed.' + content: + application/problem+json: + schema: + type: object + example: + type: 'https://apiguide.dev/errors/unauthorized' + title: Unauthorized + status: 401 + detail: Unauthenticated. + properties: + type: + type: string + example: 'https://apiguide.dev/errors/unauthorized' + title: + type: string + example: Unauthorized + status: + type: integer + example: 401 + detail: + type: string + example: Unauthenticated. + 403: + description: 'Token is missing the auth:tokens:create ability.' + content: + application/problem+json: + schema: + type: object + example: + type: 'https://apiguide.dev/errors/forbidden' + title: Forbidden + status: 403 + detail: Forbidden. + properties: + type: + type: string + example: 'https://apiguide.dev/errors/forbidden' + title: + type: string + example: Forbidden + status: + type: integer + example: 403 + detail: + type: string + example: Forbidden. + 422: + description: 'A requested ability is not held by this token, or the expiry is invalid.' + content: + application/problem+json: + schema: + type: object + example: + type: 'https://apiguide.dev/errors/validation-failed' + title: 'Validation Failed' + status: 422 + detail: 'You can only grant abilities your current token holds.' + errors: + abilities.0: + - 'You can only grant abilities your current token holds.' + properties: + type: + type: string + example: 'https://apiguide.dev/errors/validation-failed' + title: + type: string + example: 'Validation Failed' + status: + type: integer + example: 422 + detail: + type: string + example: 'You can only grant abilities your current token holds.' + errors: + type: object + properties: + abilities.0: + type: array + example: + - 'You can only grant abilities your current token holds.' + items: + type: string + tags: + - Authentication + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: 'A label for the key, shown when listing tokens.' + example: deploy-bot + abilities: + type: array + description: 'Abilities to grant, each one held by the token making this request.' + example: + - 'auth:me' + - 'auth:tokens:read' + items: + type: string + expires_at: + type: string + description: 'ISO 8601 expiry, in the future and no later than the configured maximum (365 days by default). Leave it out for the default (90 days).' + example: '2027-01-01T00:00:00+00:00' + required: + - name + - abilities delete: summary: 'Revoke All Tokens' operationId: revokeAllTokens - description: 'Revoke all personal access tokens for the authenticated user.' + description: 'Revoke every personal access token the authenticated user holds, including the one making this request. Use it to sign out everywhere after a suspected compromise. Returns 204 with no body; every later request with these tokens is a 401.' parameters: [] responses: 204: description: 'All tokens revoked.' - content: - application/json: - schema: - type: object - nullable: true 401: description: 'Authentication failed.' content: @@ -773,9 +1016,21 @@ paths: schema: type: object example: - message: Unauthenticated. + type: 'https://apiguide.dev/errors/unauthorized' + title: Unauthorized + status: 401 + detail: Unauthenticated. properties: - message: + type: + type: string + example: 'https://apiguide.dev/errors/unauthorized' + title: + type: string + example: Unauthorized + status: + type: integer + example: 401 + detail: type: string example: Unauthenticated. 403: @@ -785,9 +1040,21 @@ paths: schema: type: object example: - message: Forbidden. + type: 'https://apiguide.dev/errors/forbidden' + title: Forbidden + status: 403 + detail: Forbidden. properties: - message: + type: + type: string + example: 'https://apiguide.dev/errors/forbidden' + title: + type: string + example: Forbidden + status: + type: integer + example: 403 + detail: type: string example: Forbidden. tags: @@ -796,16 +1063,11 @@ paths: delete: summary: 'Revoke Token' operationId: revokeToken - description: 'Revoke one personal access token owned by the authenticated user.' + description: "Revoke one of the authenticated user's personal access tokens by its ID, such as a lost device's. Use List Tokens to find the ID. Returns 204 with no body; a token the user does not own, or that no longer exists, is a 404." parameters: [] responses: 204: description: 'Token revoked.' - content: - application/json: - schema: - type: object - nullable: true 401: description: 'Authentication failed.' content: @@ -813,9 +1075,21 @@ paths: schema: type: object example: - message: Unauthenticated. + type: 'https://apiguide.dev/errors/unauthorized' + title: Unauthorized + status: 401 + detail: Unauthenticated. properties: - message: + type: + type: string + example: 'https://apiguide.dev/errors/unauthorized' + title: + type: string + example: Unauthorized + status: + type: integer + example: 401 + detail: type: string example: Unauthenticated. 403: @@ -825,9 +1099,21 @@ paths: schema: type: object example: - message: Forbidden. + type: 'https://apiguide.dev/errors/forbidden' + title: Forbidden + status: 403 + detail: Forbidden. properties: - message: + type: + type: string + example: 'https://apiguide.dev/errors/forbidden' + title: + type: string + example: Forbidden + status: + type: integer + example: 403 + detail: type: string example: Forbidden. 404: @@ -837,26 +1123,25 @@ paths: schema: type: object example: - message: 'Token not found.' + type: 'https://apiguide.dev/errors/resource-not-found' + title: 'Resource Not Found' + status: 404 + detail: 'Token not found.' properties: - message: + type: + type: string + example: 'https://apiguide.dev/errors/resource-not-found' + title: + type: string + example: 'Resource Not Found' + status: + type: integer + example: 404 + detail: type: string example: 'Token not found.' tags: - Authentication - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - token_id: - type: integer - description: '' - example: 16 - required: - - token_id parameters: - in: path @@ -870,7 +1155,7 @@ paths: post: summary: 'Send Verification Email' operationId: sendVerificationEmail - description: 'Send (or resend) an email verification link to the authenticated user.' + description: 'Send the authenticated user a new email verification link. Use it when the first link expired or never arrived; it is limited to six requests a minute. Returns a message saying the link was sent, or that the email is already verified.' parameters: [] responses: 200: diff --git a/routes/api/v1.php b/routes/api/v1.php index ff7586c..5c24dd9 100644 --- a/routes/api/v1.php +++ b/routes/api/v1.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use App\Http\Controllers\Api\V1\Auth\CreateTokenController; use App\Http\Controllers\Api\V1\Auth\DeleteAllTokensController; use App\Http\Controllers\Api\V1\Auth\DeleteTokenController; use App\Http\Controllers\Api\V1\Auth\ForgotPasswordController; @@ -31,6 +32,8 @@ Route::get('/auth/password/reset/{token}', ShowResetPasswordTokenController::class) ->name('password.reset'); Route::get('/auth/email/verify/{id}/{hash}', VerifyEmailController::class) + ->whereUlid('id') + ->where('hash', '[0-9a-f]{40}') ->middleware(['signed', 'throttle:6,1']) ->name('verification.verify'); @@ -44,10 +47,14 @@ Route::get('/auth/tokens', ListTokensController::class) ->middleware('abilities:auth:tokens:read') ->name('v1.auth.tokens.index'); + Route::post('/auth/tokens', CreateTokenController::class) + ->middleware(['abilities:auth:tokens:create', 'idempotent']) + ->name('v1.auth.tokens.store'); Route::delete('/auth/tokens', DeleteAllTokensController::class) ->middleware('abilities:auth:tokens:delete') ->name('v1.auth.tokens.destroy-all'); Route::delete('/auth/tokens/{token_id}', DeleteTokenController::class) + ->whereNumber('token_id') ->middleware('abilities:auth:tokens:delete') ->name('v1.auth.tokens.destroy'); Route::post('/auth/email/verification-notification', SendEmailVerificationNotificationController::class) diff --git a/stubs/endpoint/controller.stub b/stubs/endpoint/controller.stub new file mode 100644 index 0000000..21ee981 --- /dev/null +++ b/stubs/endpoint/controller.stub @@ -0,0 +1,22 @@ +<?php + +declare(strict_types=1); + +namespace {{ namespace }}; + +{{ imports }} + +#[Group(name: '{{ group }}')] +#[Endpoint( + title: '{{ title }}', + description: 'TODO: Say what this endpoint does. TODO: Say when a client should call it. TODO: Say what it returns.', +)] +{{ attributes }} +final class {{ class }} +{ + public function __invoke({{ parameters }}): JsonResponse + { +{{ body }} + abort(501, 'TODO: Implement {{ title }}.'); + } +} diff --git a/stubs/endpoint/payload.stub b/stubs/endpoint/payload.stub new file mode 100644 index 0000000..8490cb8 --- /dev/null +++ b/stubs/endpoint/payload.stub @@ -0,0 +1,35 @@ +<?php + +declare(strict_types=1); + +namespace {{ namespace }}; + +use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Http\Request; + +final readonly class {{ class }} +{ + public function __construct( + // public string $name, + ) {} + + public static function fromRequest(Request $request): self + { + $data = self::validatedData($request); + + // Read with typed accessors, such as Arr::string($data, 'name'), and path parameters with + // App\Http\Payloads\RouteParameter. + return new self(); + } + + /** + * @return array<string, mixed> + */ + private static function validatedData(Request $request): array + { + /** @var array<string, mixed> $data */ + $data = $request instanceof FormRequest ? $request->validated() : $request->all(); + + return $data; + } +} diff --git a/stubs/endpoint/request.stub b/stubs/endpoint/request.stub new file mode 100644 index 0000000..75d602d --- /dev/null +++ b/stubs/endpoint/request.stub @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +namespace {{ namespace }}; + +use Illuminate\Foundation\Http\FormRequest; + +final class {{ class }} extends FormRequest +{ + public function authorize(): bool + { + return true; + } + + /** + * Body or query input only: path parameters are validated by the route's constraints. + * + * @return array<string, mixed> + */ + public function rules(): array + { + return [ + // 'name' => ['required', 'string', 'max:255'], + ]; + } +{{ queryParameters }}} diff --git a/stubs/endpoint/test.stub b/stubs/endpoint/test.stub new file mode 100644 index 0000000..921b1f9 --- /dev/null +++ b/stubs/endpoint/test.stub @@ -0,0 +1,14 @@ +<?php + +declare(strict_types=1); + +use App\Models\User; +use Illuminate\Foundation\Testing\RefreshDatabase; + +uses(RefreshDatabase::class); + +it('{{ successDescription }}', function (): void { + // Call {{ method }} {{ uri }} with a token holding {{ abilityOrNone }}, then assert the response, e.g. + // ->assertCreated()->assertJsonPath('data.id', ...). +})->todo(); +{{ guardTests }} diff --git a/tests/Feature/AuthRecoveryTest.php b/tests/Feature/AuthRecoveryTest.php index 5cb0a4d..49a1ab5 100644 --- a/tests/Feature/AuthRecoveryTest.php +++ b/tests/Feature/AuthRecoveryTest.php @@ -3,8 +3,9 @@ declare(strict_types=1); use App\Models\User; -use Illuminate\Auth\Notifications\ResetPassword; -use Illuminate\Auth\Notifications\VerifyEmail; +use App\Notifications\ResetPassword; +use App\Notifications\VerifyEmail; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; @@ -105,3 +106,25 @@ ->assertUnprocessable() ->assertJsonValidationErrors(['email']); }); + +it('queues verification and reset emails in the language of the request', function (): void { + Notification::fake(); + + $this->withHeaders(['Accept-Language' => 'es']) + ->postJson('/v1/auth/register', [ + 'name' => 'Ana', + 'email' => 'ana@example.com', + 'password' => 'password123', + 'device_name' => 'test-suite', + ]) + ->assertCreated(); + + $this->withHeaders(['Accept-Language' => 'es']) + ->postJson('/v1/auth/password/forgot', ['email' => 'ana@example.com']) + ->assertOk(); + + $user = User::query()->where('email', 'ana@example.com')->firstOrFail(); + + Notification::assertSentTo($user, VerifyEmail::class, fn(VerifyEmail $mail): bool => $mail instanceof ShouldQueue && 'es' === $mail->locale); + Notification::assertSentTo($user, ResetPassword::class, fn(ResetPassword $mail): bool => $mail instanceof ShouldQueue && 'es' === $mail->locale); +}); diff --git a/tests/Feature/AuthSecurityTest.php b/tests/Feature/AuthSecurityTest.php index 98cdde0..93dba5d 100644 --- a/tests/Feature/AuthSecurityTest.php +++ b/tests/Feature/AuthSecurityTest.php @@ -3,7 +3,7 @@ declare(strict_types=1); use App\Models\User; -use Illuminate\Auth\Notifications\ResetPassword; +use App\Notifications\ResetPassword; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\URL; diff --git a/tests/Feature/AuthTokenManagementTest.php b/tests/Feature/AuthTokenManagementTest.php index d2e26c6..7ed7183 100644 --- a/tests/Feature/AuthTokenManagementTest.php +++ b/tests/Feature/AuthTokenManagementTest.php @@ -4,6 +4,7 @@ use App\Http\Controllers\Api\V1\Auth\ListTokensController; use App\Models\User; +use App\Support\AccessTokens; use Illuminate\Foundation\Testing\RefreshDatabase; use Laravel\Sanctum\PersonalAccessToken; @@ -78,14 +79,13 @@ ->assertJsonPath('detail', __('api.auth.token_not_found')); }); -it('validates token id route parameter when revoking a single token', function (): void { +it('answers 404 for a token id that is not a number', function (): void { $user = User::factory()->create(); $requestToken = $user->createToken('request-token', ['auth:tokens:delete']); $this->withToken($requestToken->plainTextToken) ->deleteJson('/v1/auth/tokens/not-an-integer') - ->assertUnprocessable() - ->assertJsonValidationErrors(['token_id']); + ->assertProblemType('https://apiguide.dev/errors/resource-not-found', 404); }); it('forbids single token revocation when token lacks required ability', function (): void { @@ -159,3 +159,133 @@ ->getJson('/v1/auth/tokens?cursor=not-a-cursor') ->assertProblemType('https://apiguide.dev/errors/invalid-pagination-cursor', 400); }); + +it('creates an api key holding a subset of the current token abilities', function (): void { + $user = User::factory()->create(); + $session = $user->createToken('session', ['auth:me', 'auth:tokens:read', 'auth:tokens:create']); + + $response = $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', [ + 'name' => 'deploy-bot', + 'abilities' => ['auth:me'], + ]) + ->assertCreated() + ->assertJsonPath('data.name', 'deploy-bot') + ->assertJsonPath('data.abilities', ['auth:me']) + ->assertJsonPath('data.is_current', false) + ->assertJsonPath('meta.token_type', 'Bearer'); + + $key = PersonalAccessToken::findToken((string) $response->json('meta.token')); + + expect($key)->not->toBeNull(); + expect($key?->expires_at?->isSameDay(now()->addDays(90)))->toBeTrue(); + + app('auth')->forgetGuards(); + + $this->withToken((string) $response->json('meta.token'))->getJson('/v1/auth/me')->assertOk(); + + app('auth')->forgetGuards(); + + $this->withToken((string) $response->json('meta.token'))->getJson('/v1/auth/tokens')->assertProblem(403); +}); + +it('refuses to grant an ability the current token does not hold', function (): void { + $user = User::factory()->create(); + $session = $user->createToken('session', ['auth:me', 'auth:tokens:create']); + + $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', [ + 'name' => 'too-broad', + 'abilities' => ['auth:me', 'auth:tokens:delete'], + ]) + ->assertProblemType('https://apiguide.dev/errors/validation-failed', 422) + ->assertJsonPath('errors', ['abilities.1' => [__('api.auth.ability_not_grantable')]]); + + expect($user->tokens()->count())->toBe(1); +}); + +it('refuses abilities no route checks, even from a token holding every ability', function (): void { + $user = User::factory()->create(); + $session = $user->createToken('session', ['*']); + + $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', [ + 'name' => 'made-up', + 'abilities' => ['billing:refund'], + ]) + ->assertProblem(422); +}); + +it('lets an api key outlive a session token, up to the configured maximum', function (): void { + $user = User::factory()->create(); + $session = $user->createToken('session', ['auth:tokens:create', 'auth:me']); + + $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', [ + 'name' => 'year-long', + 'abilities' => ['auth:me'], + 'expires_at' => now()->addDays(365)->toAtomString(), + ]) + ->assertCreated(); + + $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', [ + 'name' => 'too-long', + 'abilities' => ['auth:me'], + 'expires_at' => now()->addDays(366)->toAtomString(), + ]) + ->assertProblem(422) + ->assertJsonValidationErrors(['expires_at']); + + $this->travel(3)->hours(); + app('auth')->forgetGuards(); + + $key = $user->tokens()->where('name', 'year-long')->firstOrFail(); + + expect($key->expires_at?->isSameDay(now()->addDays(365)->subHours(3)))->toBeTrue(); +}); + +it('keeps an api key working after session tokens have expired', function (): void { + $user = User::factory()->create(); + $session = app(AccessTokens::class)->issueSession($user, 'laptop'); + + $key = $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', ['name' => 'nightly-job', 'abilities' => ['auth:me']]) + ->assertCreated() + ->json('meta.token'); + + $this->travel(config()->integer('sanctum.lifetimes.session_minutes') + 1)->minutes(); + app('auth')->forgetGuards(); + + $this->withToken($session->plainTextToken)->getJson('/v1/auth/me')->assertUnauthorized(); + + app('auth')->forgetGuards(); + + $this->withToken((string) $key)->getJson('/v1/auth/me')->assertOk(); +}); + +it('requires the tokens create ability to make an api key', function (): void { + $user = User::factory()->create(); + $session = $user->createToken('session', ['auth:me']); + + $this->withToken($session->plainTextToken) + ->postJson('/v1/auth/tokens', ['name' => 'nope', 'abilities' => ['auth:me']]) + ->assertProblem(403); +}); + +it('does not create a second key when a create request is retried', function (): void { + $user = User::factory()->create(); + $session = $user->createToken('session', ['auth:me', 'auth:tokens:create']); + $headers = ['Idempotency-Key' => 'create-key-12345']; + $body = ['name' => 'retried', 'abilities' => ['auth:me']]; + + $first = $this->withToken($session->plainTextToken)->withHeaders($headers) + ->postJson('/v1/auth/tokens', $body) + ->assertCreated(); + + $this->withToken($session->plainTextToken)->withHeaders($headers) + ->postJson('/v1/auth/tokens', $body) + ->assertIdempotentReplay($first); + + expect($user->tokens()->where('name', 'retried')->count())->toBe(1); +}); diff --git a/tests/Feature/AuthTokenTest.php b/tests/Feature/AuthTokenTest.php index ed098ee..13e130c 100644 --- a/tests/Feature/AuthTokenTest.php +++ b/tests/Feature/AuthTokenTest.php @@ -3,7 +3,7 @@ declare(strict_types=1); use App\Models\User; -use Illuminate\Auth\Notifications\VerifyEmail; +use App\Notifications\VerifyEmail; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; use Laravel\Sanctum\PersonalAccessToken; diff --git a/tests/Feature/IdempotencyKeyTest.php b/tests/Feature/IdempotencyKeyTest.php index 6b29063..29b7ea2 100644 --- a/tests/Feature/IdempotencyKeyTest.php +++ b/tests/Feature/IdempotencyKeyTest.php @@ -3,7 +3,7 @@ declare(strict_types=1); use App\Models\User; -use Illuminate\Auth\Notifications\ResetPassword; +use App\Notifications\ResetPassword; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; use Laravel\Sanctum\PersonalAccessToken; diff --git a/tests/Feature/MakeEndpointCommandTest.php b/tests/Feature/MakeEndpointCommandTest.php new file mode 100644 index 0000000..1b741f7 --- /dev/null +++ b/tests/Feature/MakeEndpointCommandTest.php @@ -0,0 +1,123 @@ +<?php + +declare(strict_types=1); + +use Illuminate\Filesystem\Filesystem; + +/* + * The command writes into a temporary copy of the project's stubs and v1 routes, never the real + * files: the suite runs in parallel, and other tests load routes/api/v1.php. + */ +beforeEach(function (): void { + $this->files = new Filesystem(); + $this->base = sys_get_temp_dir() . '/kit-make-endpoint-' . bin2hex(random_bytes(6)); + + $this->files->copyDirectory(base_path('stubs'), "{$this->base}/stubs"); + $this->files->ensureDirectoryExists("{$this->base}/routes/api"); + $this->files->copy(base_path('routes/api/v1.php'), "{$this->base}/routes/api/v1.php"); + + $this->originalBase = base_path(); + $this->originalApp = app_path(); + app()->setBasePath($this->base); + app()->useAppPath("{$this->base}/app"); +}); + +afterEach(function (): void { + app()->setBasePath($this->originalBase); + app()->useAppPath($this->originalApp); + $this->files->deleteDirectory($this->base); +}); + +it('scaffolds the six pieces of an authenticated endpoint', function (): void { + $this->artisan('make:endpoint', [ + 'name' => 'Projects/CreateProject', + '--method' => 'POST', + '--uri' => '/projects', + ])->assertSuccessful(); + + foreach ([ + 'app/Http/Controllers/Api/V1/Projects/CreateProjectController.php', + 'app/Http/Requests/Projects/CreateProjectRequest.php', + 'app/Http/Payloads/V1/CreateProjectPayload.php', + 'tests/Feature/Projects/CreateProjectTest.php', + ] as $file) { + expect("{$this->base}/{$file}")->toBeFile(); + expect(php_strip_whitespace("{$this->base}/{$file}"))->not->toBe(''); + } + + $controller = (string) file_get_contents("{$this->base}/app/Http/Controllers/Api/V1/Projects/CreateProjectController.php"); + + expect($controller) + ->toContain('final class CreateProjectController') + ->toContain('#[Authenticated]') + ->toContain("'status' => 401") + ->toContain("'status' => 403") + ->toContain("'status' => 422") + ->toContain('CreateProjectPayload::fromRequest($request)') + ->toContain("abort(501, 'TODO: Implement Create Project.')"); + + $routes = (string) file_get_contents("{$this->base}/routes/api/v1.php"); + + expect($routes) + ->toContain('use App\Http\Controllers\Api\V1\Projects\CreateProjectController;') + ->toContain("Route::post('/projects', CreateProjectController::class)") + ->toContain("'auth:sanctum', 'throttle:auth-protected', 'abilities:projects:write', 'idempotent'") + ->toContain("->name('v1.projects.store')"); + + expect((string) file_get_contents("{$this->base}/tests/Feature/Projects/CreateProjectTest.php")) + ->toContain("it('requires the projects:write ability'") + ->toContain('->todo();'); +}); + +it('documents a GET request as query parameters and leaves path parameters to the route', function (): void { + $this->artisan('make:endpoint', [ + 'name' => 'Projects/ShowProject', + '--method' => 'GET', + '--uri' => '/projects/{project}', + '--ability' => 'projects:view', + ])->assertSuccessful(); + + expect((string) file_get_contents("{$this->base}/app/Http/Requests/Projects/ShowProjectRequest.php")) + ->toContain('public function queryParameters(): array'); + + expect((string) file_get_contents("{$this->base}/app/Http/Controllers/Api/V1/Projects/ShowProjectController.php")) + ->toContain("#[UrlParam('project'"); + + expect((string) file_get_contents("{$this->base}/routes/api/v1.php")) + ->toContain("// TODO: Constrain project") + ->toContain("'abilities:projects:view'") + ->toContain("->name('v1.projects.show')") + ->not->toContain("'abilities:projects:view', 'idempotent'"); +}); + +it('scaffolds a public endpoint without auth, and a DELETE without a Form Request', function (): void { + $this->artisan('make:endpoint', ['name' => 'Status/ShowStatus', '--method' => 'GET', '--uri' => '/status', '--guest' => true]) + ->assertSuccessful(); + $this->artisan('make:endpoint', ['name' => 'Projects/DeleteProject', '--method' => 'DELETE', '--uri' => '/projects/{project}']) + ->assertSuccessful(); + + expect((string) file_get_contents("{$this->base}/app/Http/Controllers/Api/V1/Status/ShowStatusController.php")) + ->toContain('#[Unauthenticated]') + ->not->toContain("'status' => 401"); + + expect("{$this->base}/app/Http/Requests/Projects/DeleteProjectRequest.php")->not->toBeFile(); + expect((string) file_get_contents("{$this->base}/routes/api/v1.php")) + ->toContain("Route::get('/status', ShowStatusController::class)\n ->name('v1.status.show');") + ->toContain("->name('v1.projects.destroy')"); +}); + +it('refuses to overwrite an endpoint unless forced', function (): void { + $arguments = ['name' => 'Projects/CreateProject', '--method' => 'POST', '--uri' => '/projects']; + + $this->artisan('make:endpoint', $arguments)->assertSuccessful(); + $this->artisan('make:endpoint', $arguments)->assertFailed(); + $this->artisan('make:endpoint', [...$arguments, '--force' => true])->assertSuccessful(); +}); + +it('rejects names and methods it cannot scaffold', function (string $name, string $method): void { + $this->artisan('make:endpoint', ['name' => $name, '--method' => $method, '--uri' => '/things'])->assertFailed(); +})->with([ + 'no domain' => ['CreateProject', 'POST'], + 'not studly' => ['projects/create', 'POST'], + 'unknown method' => ['Projects/CreateProject', 'TRACE'], +]); diff --git a/tests/Feature/OpenApiContractTest.php b/tests/Feature/OpenApiContractTest.php index b8cbc82..cbd3cfa 100644 --- a/tests/Feature/OpenApiContractTest.php +++ b/tests/Feature/OpenApiContractTest.php @@ -254,6 +254,12 @@ function assertOpenApiArray(array $spec, array $schema, mixed $value, string $pa expect($extraInSpec)->toBe([]); }); +it('has no unfinished documentation', function (): void { + $spec = (string) json_encode(generateOpenApiSpec()); + + expect(mb_substr_count($spec, 'TODO'))->toBe(0, 'An endpoint is still documented with a TODO from make:endpoint.'); +}); + it('keeps runtime auth responses aligned with documented openapi responses', function (): void { $spec = generateOpenApiSpec(); /** @var array<string, array<string, array<string, mixed>>> $paths */ @@ -317,6 +323,14 @@ function assertOpenApiArray(array $spec, array $schema, mixed $value, string $pa 'path' => '/v1/auth/email/verify/{id}/{hash}', 'response' => $this->getJson($verificationUrl), ], + [ + 'method' => 'POST', + 'path' => '/v1/auth/tokens', + 'response' => $this->postJson('/v1/auth/tokens', [ + 'name' => 'contract-key', + 'abilities' => ['auth:me'], + ]), + ], [ 'method' => 'POST', 'path' => '/v1/auth/password/forgot', diff --git a/vet.json b/vet.json index 31c8ca1..e4a19e2 100644 --- a/vet.json +++ b/vet.json @@ -56,10 +56,18 @@ "version": "v0.3.0", "hash": "tree-v2:170dbefcc470a823490926a602216b6f1c5ba5f258a4ba16528a199269bd610c" }, + "laminas/laminas-diactoros": { + "version": "3.9.0", + "hash": "tree-v2:a96235360b43645eb30bed80af9e8b1e4f60b80fefd1eb980e1e33f1549a7c6e" + }, "laravel/framework": { "version": "v13.35.0", "hash": "tree-v2:862428a89369e09b33dee255707d3c5d05dfffdc5bf880ce97418d0e7853d24b" }, + "laravel/octane": { + "version": "v2.22.0", + "hash": "tree-v2:67290079ce12d4269b4cdf8fc872859fad8443f71c80f889298b53e8ed9e208a" + }, "laravel/prompts": { "version": "v0.3.26", "hash": "tree-v2:5131de1988c6323c82b0ac41b1d3b256b3e5ae6d9a02edb24f6a177bd4a8f3d0" @@ -276,6 +284,10 @@ "version": "v8.1.9", "hash": "tree-v2:0088281cac46a3378736e4db93df87bd462c17b193ffa95622e72670427bd3e1" }, + "symfony/psr-http-message-bridge": { + "version": "v8.1.9", + "hash": "tree-v2:a29d81f0b30177b80606a6e88dcb64fc8dab6b536afc1c620fe9ce024be56641" + }, "symfony/routing": { "version": "v8.1.9", "hash": "tree-v2:dc0d70dd175594a8a2468f2b694b8ce0780dbd4369e7020777aac056a66c25ca" @@ -338,10 +350,6 @@ "version": "1.1.6", "hash": "tree-v2:8abdb22c79e82b9ea4884ab18dbaa595bb5315736231fa9e310b9d70a3ab0815" }, - "driftingly/rector-laravel": { - "version": "2.6.2", - "hash": "tree-v2:7ad85f8d2c4fc8ae611466f654d894413f9d066999bbede4abdccda6f230be4e" - }, "entropy/entropy": { "version": "0.4.30", "hash": "tree-v2:df059d0a216ac6093cf29ef00ca0d1316c66c716910a396e98625ebd4dd153bf" @@ -506,10 +514,6 @@ "version": "12.5.33", "hash": "tree-v2:fe7d4ec3e4840290cee07c39535422b61bb31ebd2afde15a39a78373a0cd2c64" }, - "rector/rector": { - "version": "2.7.0", - "hash": "tree-v2:e8f59d6c70f4d83c2a49a512000935fdc04f7ef278c685ae7da3cac6b36f0d91" - }, "sebastian/cli-parser": { "version": "4.2.1", "hash": "tree-v2:fc44fc3e0a4b1fd529963948acebc3a3370f7b55aa8e9969c96953477b41886e" @@ -582,10 +586,6 @@ "version": "v8.1.9", "hash": "tree-v2:ac2ebd08460160092a00a9af5531fd33f054e17c16a88425464505af0d2044d1" }, - "symplify/rule-doc-generator-contracts": { - "version": "11.2.0", - "hash": "tree-v2:143fc89ce64308c660e6f52de2df92429720106e1e43e1484dd93193772ed011" - }, "ta-tikoma/phpunit-architecture-test": { "version": "0.8.7", "hash": "tree-v2:068328d7bed81666d79d94c08e5b634b6c2f1499e8ebadf1068b4d7f19545243" @@ -606,6 +606,7 @@ "minimum-release-age": 7, "minimum-release-age-exclude": [ "juststeveking/*", + "laravel/*", "roave/security-advisories" ] }