From 07e7b336a3014b4c5ae0fc766474fbbaeb993f2e Mon Sep 17 00:00:00 2001
From: Steve McDougall
Create a new account and issue a Sanctum bearer token. 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.
Authenticate a user and issue a Sanctum bearer token. 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.Register
Example request:
@@ -217,10 +217,10 @@ Register
{
"data": {
- "id": "01m5cb6hssde51qe3kn813thmv",
+ "id": "01m5cd9s04d0vrecpnz9vnq86a",
"name": "Justina Gaylord",
"email": "lafayette.considine@example.com",
- "email_verified_at": "2026-10-20T09:45:06+00:00",
+ "email_verified_at": "2026-10-20T10:21:49+00:00",
"created_at": null,
"updated_at": null
},
@@ -376,7 +376,7 @@ Login
Example request:
@@ -427,10 +427,10 @@ Login
{
"data": {
- "id": "01m5cb6ht2em5q96y8t1rffqv6",
+ "id": "01m5cd9s0csvf155wbah7yn3s0",
"name": "Justina Gaylord",
"email": "cormier.nick@example.com",
- "email_verified_at": "2026-10-20T09:45:06+00:00",
+ "email_verified_at": "2026-10-20T10:21:49+00:00",
"created_at": null,
"updated_at": null
},
@@ -575,7 +575,7 @@ Get Current User
requires authentication
Return the authenticated user for the current bearer token.
+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.
Example request:@@ -615,10 +615,10 @@
{
"data": {
- "id": "01m5cb6htrjmdsahn6h774frrz",
+ "id": "01m5cd9s12mhvc0tqhs163ps8h",
"name": "Morgan Hirthe",
"email": "dare.emelie@example.com",
- "email_verified_at": "2026-10-20T09:45:06+00:00",
+ "email_verified_at": "2026-10-20T10:21:49+00:00",
"created_at": null,
"updated_at": null
}
@@ -728,7 +728,7 @@ Logout
requires authentication
-Revoke the current Sanctum token.
+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.
Example request:
@@ -773,7 +773,10 @@ Logout
{
- "message": "Unauthenticated."
+ "type": "https://apiguide.dev/errors/unauthorized",
+ "title": "Unauthorized",
+ "status": 401,
+ "detail": "Unauthenticated."
}
@@ -868,7 +871,7 @@ List Tokens
requires authentication
-List personal access tokens for the authenticated user.
+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.
Example request:
@@ -1057,7 +1060,7 @@ Revoke All Tokens
requires authentication
-Revoke all personal access tokens for the authenticated user.
+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.
Example request:
@@ -1102,7 +1105,10 @@ Revoke All Tokens
{
- "message": "Unauthenticated."
+ "type": "https://apiguide.dev/errors/unauthorized",
+ "title": "Unauthorized",
+ "status": 401,
+ "detail": "Unauthenticated."
}
@@ -1111,7 +1117,10 @@ Revoke All Tokens
{
- "message": "Forbidden."
+ "type": "https://apiguide.dev/errors/forbidden",
+ "title": "Forbidden",
+ "status": 403,
+ "detail": "Forbidden."
}
@@ -1206,7 +1215,7 @@ Revoke Token
requires authentication
-Revoke one personal access token owned by the authenticated user.
+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.
Example request:
@@ -1217,11 +1226,7 @@ Revoke Token
"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
-}"
-
+ --header "Accept: application/json"
{
- "message": "Unauthenticated."
+ "type": "https://apiguide.dev/errors/unauthorized",
+ "title": "Unauthorized",
+ "status": 401,
+ "detail": "Unauthenticated."
}
@@ -1269,7 +1272,10 @@Revoke Token
{ - "message": "Forbidden." + "type": "https://apiguide.dev/errors/forbidden", + "title": "Forbidden", + "status": 403, + "detail": "Forbidden." }@@ -1278,7 +1284,10 @@Revoke Token
@@ -1378,20 +1387,7 @@{ - "message": "Token not found." + "type": "https://apiguide.dev/errors/resource-not-found", + "title": "Resource Not Found", + "status": 404, + "detail": "Token not found." }URL Parameters
Personal access token id. Example:
-42Body Parameters
--- +token_id-integer - - - -
-Example:
-16Password Reset
Request Password Reset
@@ -1399,7 +1395,7 @@Request Password Reset
-
Send a password reset link to the provided email if an account exists.
+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.
Example request:@@ -1446,6 +1442,35 @@Request Password Reset
{ "message": "If the account exists, a password reset link has been sent." +}+ +++Example response (422, The email was missing or not an email address.):
++ ++{ + "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." + ] + } +}+++Example response (429, Too many reset requests for this address; retry after the Retry-After header.):
++ +@@ -1540,7 +1565,7 @@{ + "type": "https://apiguide.dev/errors/rate-limit-exceeded", + "title": "Rate Limit Exceeded", + "status": 429, + "detail": "Too many requests. Please try again later." }Reset Password
-
Reset the user password using a valid reset token.
+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.
Example request:@@ -1740,7 +1765,7 @@Read Reset Token Paylo
-
Return reset token and email payload for API clients handling email reset links.
+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.
Example request:@@ -1750,12 +1775,7 @@Read Reset Token Paylo
@@ -1796,6 +1810,23 @@+ --header "Accept: application/json"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\" -}" -@@ -1774,15 +1794,9 @@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());
Read Reset Token Paylo
@@ -1896,32 +1927,7 @@{ "token": "reset-token-value", "email": "jane@example.com" +}+ +++Example response (422, The email query parameter was not an email address.):
++ +{ + "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." + ] + } }Query Parameters
Account email from the reset link. Example:
-jane@example.comBody Parameters
---token-string - - - -
-Example:
-architecto-- +
-Must be a valid email address. Must not be greater than 255 characters. Example:
-zbailey@example.netEmail Verification
Verify Email
@@ -1929,7 +1935,7 @@Verify Email
-
Verify a user email using the signed verification link parameters.
+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.
Example request:@@ -1939,12 +1945,7 @@Verify Email
+ --header "Accept: application/json"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\" -}" -@@ -1957,15 +1958,9 @@@@ -2089,32 +2084,7 @@Verify Email
"Accept": "application/json", }; -let body = { - "id": "architecto", - "hash": "ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqld" -}; - fetch(url, { method: "GET", headers, - body: JSON.stringify(body), }).then(response => response.json());URL Parameters
SHA-1 hash of the email from the signed verification link. Example:
-8c4f4370e5db9b5be6d0f4c95495f49f998fa32aBody Parameters
---id-string - - - -
-Must match an existing stored value. Example:
-architecto-- +hash-string - - - -
-Must be 40 characters. Example:
-ngzmiyvdljnikhwaykcmyuwpwlvqwrsitcpscqldSend Verification Email
@@ -2122,7 +2092,7 @@Send Verific requires authentication -
Send (or resend) an email verification link to the authenticated user.
+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.
Example request:diff --git a/public/docs/openapi.yaml b/public/docs/openapi.yaml index 52384ee..251ae68 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: 01m5cd9s04d0vrecpnz9vnq86a name: 'Justina Gaylord' email: lafayette.considine@example.com - email_verified_at: '2026-10-20T09:45:06+00:00' + email_verified_at: '2026-10-20T10:21:49+00:00' created_at: null updated_at: null meta: @@ -51,7 +51,7 @@ paths: properties: id: type: string - example: 01m5cb6hssde51qe3kn813thmv + example: 01m5cd9s04d0vrecpnz9vnq86a 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:21:49+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: 01m5cd9s0csvf155wbah7yn3s0 name: 'Justina Gaylord' email: cormier.nick@example.com - email_verified_at: '2026-10-20T09:45:06+00:00' + email_verified_at: '2026-10-20T10:21:49+00:00' created_at: null updated_at: null meta: @@ -179,7 +179,7 @@ paths: properties: id: type: string - example: 01m5cb6ht2em5q96y8t1rffqv6 + example: 01m5cd9s0csvf155wbah7yn3s0 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:21:49+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: 01m5cd9s12mhvc0tqhs163ps8h name: 'Morgan Hirthe' email: dare.emelie@example.com - email_verified_at: '2026-10-20T09:45:06+00:00' + email_verified_at: '2026-10-20T10:21:49+00:00' created_at: null updated_at: null properties: @@ -564,7 +624,7 @@ paths: properties: id: type: string - example: 01m5cb6htrjmdsahn6h774frrz + example: 01m5cd9s12mhvc0tqhs163ps8h 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:21:49+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 @@ -756,16 +823,11 @@ paths: 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 +835,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 +859,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 +882,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 +894,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 +918,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 +942,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 +974,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: From 37ef761fdd7033a71b4b5d4b5926b5b1b0183cef Mon Sep 17 00:00:00 2001 From: Steve McDougallDate: Tue, 20 Oct 2026 11:25:10 +0100 Subject: [PATCH 4/9] feat: scoped API keys with POST /v1/auth/tokens Machine clients and agents had no way to get a token without signing in with a password, which grants the session defaults. An API key now takes a name, abilities and an optional expiry: - Abilities must be held by the token creating the key, and be ones a route checks (sanctum.abilities.available), so a narrow key can never mint a broader one. The endpoint needs auth:tokens:create, which session tokens get by default. - Keys expire after 90 days by default, at most 365 (API_KEY_DEFAULT_DAYS, API_KEY_MAX_DAYS). - The request is idempotent, so a retry cannot mint a second key. sanctum.expiration was a global 120-minute cap on every token, which would have expired an API key with the session that made it. It is off; every token carries its own expires_at, and session tokens still last SANCTUM_EXPIRATION minutes. App\Support\AccessTokens issues both kinds, replacing the copies in LoginController and RegisterController. --- .env.example | 2 + .legible.yaml | 1 + .scribe/endpoints.cache/00.yaml | 105 ++++++- .scribe/endpoints/00.yaml | 105 ++++++- .../Api/V1/Auth/CreateTokenController.php | 107 +++++++ .../Api/V1/Auth/LoginController.php | 46 +-- .../Api/V1/Auth/RegisterController.php | 46 +-- app/Http/Payloads/V1/CreateTokenPayload.php | 44 +++ app/Http/Requests/Auth/CreateTokenRequest.php | 56 ++++ app/Support/AccessTokens.php | 84 ++++++ config/sanctum.php | 40 ++- lang/en/api.php | 1 + lang/es/api.php | 1 + public/docs/collection.json | 61 +++- public/docs/index.html | 264 +++++++++++++++++- public/docs/openapi.yaml | 205 +++++++++++++- routes/api/v1.php | 4 + tests/Feature/AuthTokenManagementTest.php | 131 +++++++++ tests/Feature/OpenApiContractTest.php | 8 + 19 files changed, 1195 insertions(+), 116 deletions(-) create mode 100644 app/Http/Controllers/Api/V1/Auth/CreateTokenController.php create mode 100644 app/Http/Payloads/V1/CreateTokenPayload.php create mode 100644 app/Http/Requests/Auth/CreateTokenRequest.php create mode 100644 app/Support/AccessTokens.php diff --git a/.env.example b/.env.example index 97a107b..a91f3ca 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 diff --git a/.legible.yaml b/.legible.yaml index 41965d9..be399b2 100644 --- a/.legible.yaml +++ b/.legible.yaml @@ -12,6 +12,7 @@ ignore: - 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 e52ff2e..0d2291c 100644 --- a/.scribe/endpoints.cache/00.yaml +++ b/.scribe/endpoints.cache/00.yaml @@ -80,7 +80,7 @@ endpoints: - custom: [] status: 201 - content: '{"data":{"id":"01m5cd9s04d0vrecpnz9vnq86a","name":"Justina Gaylord","email":"lafayette.considine@example.com","email_verified_at":"2026-10-20T10:21:49+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.' - @@ -159,7 +159,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cd9s0csvf155wbah7yn3s0","name":"Justina Gaylord","email":"cormier.nick@example.com","email_verified_at":"2026-10-20T10:21:49+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.' - @@ -489,7 +489,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cd9s12mhvc0tqhs163ps8h","name":"Morgan Hirthe","email":"dare.emelie@example.com","email_verified_at":"2026-10-20T10:21:49+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.' - @@ -618,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: diff --git a/.scribe/endpoints/00.yaml b/.scribe/endpoints/00.yaml index cbbf97a..d0750aa 100644 --- a/.scribe/endpoints/00.yaml +++ b/.scribe/endpoints/00.yaml @@ -78,7 +78,7 @@ endpoints: - custom: [] status: 201 - content: '{"data":{"id":"01m5cd9s04d0vrecpnz9vnq86a","name":"Justina Gaylord","email":"lafayette.considine@example.com","email_verified_at":"2026-10-20T10:21:49+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.' - @@ -157,7 +157,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cd9s0csvf155wbah7yn3s0","name":"Justina Gaylord","email":"cormier.nick@example.com","email_verified_at":"2026-10-20T10:21:49+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.' - @@ -487,7 +487,7 @@ endpoints: - custom: [] status: 200 - content: '{"data":{"id":"01m5cd9s12mhvc0tqhs163ps8h","name":"Morgan Hirthe","email":"dare.emelie@example.com","email_verified_at":"2026-10-20T10:21:49+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.' - @@ -616,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: 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/LoginController.php b/app/Http/Controllers/Api/V1/Auth/LoginController.php index 1ce8cbe..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; @@ -50,7 +51,7 @@ )] final class LoginController { - public function __invoke(LoginRequest $request): JsonResponse + public function __invoke(LoginRequest $request, AccessTokens $tokens): JsonResponse { $payload = LoginPayload::fromRequest($request); @@ -67,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, @@ -78,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/RegisterController.php b/app/Http/Controllers/Api/V1/Auth/RegisterController.php index 73e522b..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; @@ -50,7 +51,7 @@ )] final class RegisterController { - public function __invoke(RegisterRequest $request): JsonResponse + public function __invoke(RegisterRequest $request, AccessTokens $tokens): JsonResponse { $payload = RegisterPayload::fromRequest($request); @@ -62,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, @@ -73,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/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/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/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/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/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 74f9e66..877cc84 100644 --- a/public/docs/collection.json +++ b/public/docs/collection.json @@ -10,7 +10,7 @@ ], "info": { "name": "Laravel API Documentation", - "_postman_id": "b8740768-901d-452c-8967-5d439d6d2660", + "_postman_id": "3a3b7138-0565-4302-8613-83b81be02853", "description": "", "schema": "https:\/\/schema.getpostman.com\/json\/collection\/v2.1.0\/collection.json" }, @@ -56,7 +56,7 @@ { "header": [], "code": 201, - "body": "{\"data\":{\"id\":\"01m5cd9s04d0vrecpnz9vnq86a\",\"name\":\"Justina Gaylord\",\"email\":\"lafayette.considine@example.com\",\"email_verified_at\":\"2026-10-20T10:21:49+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." }, { @@ -100,7 +100,7 @@ { "header": [], "code": 200, - "body": "{\"data\":{\"id\":\"01m5cd9s0csvf155wbah7yn3s0\",\"name\":\"Justina Gaylord\",\"email\":\"cormier.nick@example.com\",\"email_verified_at\":\"2026-10-20T10:21:49+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." }, { @@ -138,7 +138,7 @@ { "header": [], "code": 200, - "body": "{\"data\":{\"id\":\"01m5cd9s12mhvc0tqhs163ps8h\",\"name\":\"Morgan Hirthe\",\"email\":\"dare.emelie@example.com\",\"email_verified_at\":\"2026-10-20T10:21:49+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." }, { @@ -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": { diff --git a/public/docs/index.html b/public/docs/index.html index d2e4f24..c5e7f82 100644 --- a/public/docs/index.html +++ b/public/docs/index.html @@ -89,6 +89,9 @@ List Tokens + ++ Create API Key Revoke All Tokens @@ -217,10 +220,10 @@ Register
{ "data": { - "id": "01m5cd9s04d0vrecpnz9vnq86a", + "id": "01m5cdfjnp16kbfqq3s4xsnvb5", "name": "Justina Gaylord", "email": "lafayette.considine@example.com", - "email_verified_at": "2026-10-20T10:21:49+00:00", + "email_verified_at": "2026-10-20T10:24:59+00:00", "created_at": null, "updated_at": null }, @@ -427,10 +430,10 @@Login
{ "data": { - "id": "01m5cd9s0csvf155wbah7yn3s0", + "id": "01m5cdfjp0cmx0zgvvy8a4z5zj", "name": "Justina Gaylord", "email": "cormier.nick@example.com", - "email_verified_at": "2026-10-20T10:21:49+00:00", + "email_verified_at": "2026-10-20T10:24:59+00:00", "created_at": null, "updated_at": null }, @@ -615,10 +618,10 @@Get Current User
{ "data": { - "id": "01m5cd9s12mhvc0tqhs163ps8h", + "id": "01m5cdfjpm8vqdmrdwtq6fqe98", "name": "Morgan Hirthe", "email": "dare.emelie@example.com", - "email_verified_at": "2026-10-20T10:21:49+00:00", + "email_verified_at": "2026-10-20T10:24:59+00:00", "created_at": null, "updated_at": null } @@ -1054,6 +1057,255 @@Query Parameters
+Create API Key
+ ++requires authentication +
+ +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.
+ + +Example request:+ + +++ + +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\" +}" +++ + + + +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());++Example response (201, API key created. meta.token is the only time its value is returned.):
++ ++{ + "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" + } +}+++Example response (401, Authentication failed.):
++ ++{ + "type": "https://apiguide.dev/errors/unauthorized", + "title": "Unauthorized", + "status": 401, + "detail": "Unauthenticated." +}+++Example response (403, Token is missing the auth:tokens:create ability.):
++ ++{ + "type": "https://apiguide.dev/errors/forbidden", + "title": "Forbidden", + "status": 403, + "detail": "Forbidden." +}+++Example response (422, A requested ability is not held by this token, or the expiry is invalid.):
++ ++ + +{ + "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." + ] + } +}+Received response: +++ + +Request failed with error:++ + ++ +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.Revoke All Tokens
diff --git a/public/docs/openapi.yaml b/public/docs/openapi.yaml index 251ae68..143133b 100644 --- a/public/docs/openapi.yaml +++ b/public/docs/openapi.yaml @@ -35,10 +35,10 @@ paths: type: object example: data: - id: 01m5cd9s04d0vrecpnz9vnq86a + id: 01m5cdfjnp16kbfqq3s4xsnvb5 name: 'Justina Gaylord' email: lafayette.considine@example.com - email_verified_at: '2026-10-20T10:21:49+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: 01m5cd9s04d0vrecpnz9vnq86a + 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-20T10:21:49+00:00' + example: '2026-10-20T10:24:59+00:00' created_at: type: string example: null @@ -163,10 +163,10 @@ paths: type: object example: data: - id: 01m5cd9s0csvf155wbah7yn3s0 + id: 01m5cdfjp0cmx0zgvvy8a4z5zj name: 'Justina Gaylord' email: cormier.nick@example.com - email_verified_at: '2026-10-20T10:21:49+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: 01m5cd9s0csvf155wbah7yn3s0 + 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-20T10:21:49+00:00' + example: '2026-10-20T10:24:59+00:00' created_at: type: string example: null @@ -612,10 +612,10 @@ paths: type: object example: data: - id: 01m5cd9s12mhvc0tqhs163ps8h + id: 01m5cdfjpm8vqdmrdwtq6fqe98 name: 'Morgan Hirthe' email: dare.emelie@example.com - email_verified_at: '2026-10-20T10:21:49+00:00' + email_verified_at: '2026-10-20T10:24:59+00:00' created_at: null updated_at: null properties: @@ -624,7 +624,7 @@ paths: properties: id: type: string - example: 01m5cd9s12mhvc0tqhs163ps8h + example: 01m5cdfjpm8vqdmrdwtq6fqe98 name: type: string example: 'Morgan Hirthe' @@ -633,7 +633,7 @@ paths: example: dare.emelie@example.com email_verified_at: type: string - example: '2026-10-20T10:21:49+00:00' + example: '2026-10-20T10:24:59+00:00' created_at: type: string example: null @@ -820,6 +820,187 @@ 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 diff --git a/routes/api/v1.php b/routes/api/v1.php index 5b916cb..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; @@ -46,6 +47,9 @@ 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'); diff --git a/tests/Feature/AuthTokenManagementTest.php b/tests/Feature/AuthTokenManagementTest.php index 11cb062..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; @@ -158,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/OpenApiContractTest.php b/tests/Feature/OpenApiContractTest.php index b8cbc82..88fd474 100644 --- a/tests/Feature/OpenApiContractTest.php +++ b/tests/Feature/OpenApiContractTest.php @@ -317,6 +317,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', From bdbb160eea1cf5fcad3f3e8875c9a6ae9453971a Mon Sep 17 00:00:00 2001 From: Steve McDougall
Date: Tue, 20 Oct 2026 11:26:08 +0100 Subject: [PATCH 5/9] feat: queue verification and password reset emails Both were sent inside the request, so a slow mail server slowed registration, resend and forgot-password. They are now queued notifications (App\Notifications), sent in the locale of the request that asked for them, since a queued job otherwise runs in the default locale. Queueing the reset email also stops forgot-password taking measurably longer when the account exists. --- app/Models/User.php | 20 ++++++++++++++++++++ app/Notifications/ResetPassword.php | 18 ++++++++++++++++++ app/Notifications/VerifyEmail.php | 17 +++++++++++++++++ tests/Feature/AuthRecoveryTest.php | 27 +++++++++++++++++++++++++-- tests/Feature/AuthSecurityTest.php | 2 +- tests/Feature/AuthTokenTest.php | 2 +- tests/Feature/IdempotencyKeyTest.php | 2 +- 7 files changed, 83 insertions(+), 5 deletions(-) create mode 100644 app/Notifications/ResetPassword.php create mode 100644 app/Notifications/VerifyEmail.php 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 @@ +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/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; From 64511c5938f48295847ebc57b7fc7bbcd06fc20e Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 11:28:54 +0100 Subject: [PATCH 6/9] ci: trust Laravel's own packages without a review Vet has no wildcard trust, so the policy has two parts. laravel/* is excluded from the 7-day release hold in vet.json. And when every package a weekly update changed is laravel/*, the bot records their trust (vet --fresh) and commits vet.json with the PR, which then needs no review. Anything else changing still waits for one. The decision compares the lock before and after the update in jq; removed packages do not count, since removing code adds nothing to trust. --- .github/workflows/dependency-updates.yml | 25 ++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) 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 From 98c759a757e971dbcbe233c41ba6af175aad1033 Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 11:34:51 +0100 Subject: [PATCH 7/9] feat: production image on Octane and FrankenPHP A Dockerfile on dunglas/frankenphp (PHP 8.5, pinned) runs Octane in worker mode on port 8000, as a non-root user, with OPcache tuned for production and a health check on /up. The same image runs a queue worker when given a command: `docker run php artisan queue:work`. The entrypoint caches config, routes and events from the runtime environment before starting. Building it found a bug in any production install: config/scribe.php references Scribe's classes, and Scribe is a dev dependency, so every artisan command failed without dev packages. The config now returns nothing when Scribe is absent. Kit holds no request state outside scoped bindings, and Octane resets locale and auth between requests (the smoke test checks Spanish then English). A CI job builds the image, boots it with production settings and requests /up and a problem through proxy headers. laravel/octane 2.22.0, laminas/laminas-diactoros 3.9.0 and symfony/psr-http-message-bridge 8.1.9 are recorded in vet.json. The latter two were reviewed for install-time hooks, network endpoints, dynamic code, shell execution and secret reads; nothing found. --- .dockerignore | 21 +++ .env.example | 2 + .github/workflows/ci-tests.yml | 39 +++++ .gitignore | 6 + Dockerfile | 44 ++++++ composer.json | 1 + composer.lock | 267 ++++++++++++++++++++++++++++++++- config/octane.php | 256 +++++++++++++++++++++++++++++++ config/scribe.php | 6 + docker/entrypoint.sh | 19 +++ docker/healthcheck.php | 18 +++ docker/php.ini | 7 + vet.json | 13 ++ 13 files changed, 698 insertions(+), 1 deletion(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 config/octane.php create mode 100755 docker/entrypoint.sh create mode 100644 docker/healthcheck.php create mode 100644 docker/php.ini 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 a91f3ca..541ad29 100644 --- a/.env.example +++ b/.env.example @@ -50,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 aff2c0e..985b7b3 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -55,3 +55,42 @@ jobs: 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/.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/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/composer.json b/composer.json index 8f187ee..9c182dd 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ "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" diff --git a/composer.lock b/composer.lock index 5b4ced0..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": "7d6df06f09e6f46c0a3614c99a11398b", + "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", 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/scribe.php b/config/scribe.php index b2f168e..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', 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 @@ + [ + '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/vet.json b/vet.json index b054268..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" @@ -594,6 +606,7 @@ "minimum-release-age": 7, "minimum-release-age-exclude": [ "juststeveking/*", + "laravel/*", "roave/security-advisories" ] } From b0ad07e7132071b38fe2575ef58a10b363928959 Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 11:42:31 +0100 Subject: [PATCH 8/9] feat: make:endpoint scaffolds an endpoint the kit way php artisan make:endpoint Projects/CreateProject --method=POST --uri=/projects writes the six pieces AGENTS.md describes: a controller with Scribe attributes and its 401, 403 and 422 problems, a Form Request (with queryParameters() on a GET, so Scribe never documents a body), a payload, a Pest test whose 401 and 403 cases pass at once and whose success case is a todo, and the route with auth, rate limit, ability, name, and idempotent on a POST. --guest, --ability and --force adjust it; missing input is prompted for. Stubs live in stubs/endpoint for projects to change, and Pint formats the output. What it cannot know stays visible: the controller answers 501, path parameters get a TODO to constrain them, and the description is three TODO sentences. A new contract test fails while the spec says TODO, and legible fails the identical descriptions, so an endpoint cannot ship half documented. It prints the steps it does not take for you, such as adding the ability to config/sanctum.php. Scribe renamed {project} to {id} when it guessed at route model binding, so the spec no longer matched the routes. Path parameters are now documented as the routes name them. --- app/Console/Commands/EndpointBlueprint.php | 56 +++ app/Console/Commands/MakeEndpointCommand.php | 405 +++++++++++++++++++ app/Providers/AppServiceProvider.php | 8 + stubs/endpoint/controller.stub | 22 + stubs/endpoint/payload.stub | 35 ++ stubs/endpoint/request.stub | 27 ++ stubs/endpoint/test.stub | 14 + tests/Feature/MakeEndpointCommandTest.php | 123 ++++++ tests/Feature/OpenApiContractTest.php | 6 + 9 files changed, 696 insertions(+) create mode 100644 app/Console/Commands/EndpointBlueprint.php create mode 100644 app/Console/Commands/MakeEndpointCommand.php create mode 100644 stubs/endpoint/controller.stub create mode 100644 stubs/endpoint/payload.stub create mode 100644 stubs/endpoint/request.stub create mode 100644 stubs/endpoint/test.stub create mode 100644 tests/Feature/MakeEndpointCommandTest.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/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 8251f21..ee6dc7d 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -10,6 +10,7 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\ServiceProvider; +use Knuckles\Scribe\Scribe; final class AppServiceProvider extends ServiceProvider { @@ -25,6 +26,13 @@ public function boot(): void { ProductionSecurityChecks::assertForEnvironment((string) app()->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/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 @@ + + */ + private static function validatedData(Request $request): array + { + /** @var array $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 @@ + + */ + 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 @@ +assertCreated()->assertJsonPath('data.id', ...). +})->todo(); +{{ guardTests }} 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 @@ +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 88fd474..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 >> $paths */ From e252912737615ccf3a75d89a99dfd519340f4be6 Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 11:43:52 +0100 Subject: [PATCH 9/9] docs: cover API keys, make:endpoint, deployment and the legible gate AGENTS.md now starts endpoints with make:endpoint, says path parameters are validated by route constraints, covers abilities and API keys, Octane-safe code and the queue worker, the laravel/* trust policy, and legible as the fourth check. The README adds the API key endpoint, the generator, deployment, the queue worker in Quick Start, and the new CI jobs and files. --- AGENTS.md | 68 ++++++++++++++++++++++++++++++++++------ README.md | 93 +++++++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 143 insertions(+), 18 deletions(-) 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/README.md b/README.md index 4222de2..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 @@ -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