@orieljs/framework 0.1.0-alpha.14 → 0.1.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/{chunk-X4N74JDO.js → chunk-3QHTNAMZ.js} +6 -4
  2. package/dist/{chunk-X4N74JDO.js.map → chunk-3QHTNAMZ.js.map} +1 -1
  3. package/dist/{chunk-BKA5F3TH.js → chunk-6AXJB4CD.js} +5 -1
  4. package/dist/chunk-6AXJB4CD.js.map +1 -0
  5. package/dist/{chunk-UBSIBGXR.js → chunk-MG4YEWMV.js} +1351 -497
  6. package/dist/chunk-MG4YEWMV.js.map +1 -0
  7. package/dist/{chunk-4NCMY3ZS.js → chunk-YNDMTTWL.js} +121 -8
  8. package/dist/chunk-YNDMTTWL.js.map +1 -0
  9. package/dist/contracts.d.ts +112 -1
  10. package/dist/contracts.js +5 -1
  11. package/dist/{index.d-lffxurFs.d.ts → index.d-DA-Iu2a2.d.ts} +39 -2
  12. package/dist/index.d.ts +2838 -2101
  13. package/dist/index.js +1805 -647
  14. package/dist/index.js.map +1 -1
  15. package/dist/{jsx-runtime-Bc5KJzwb.d.ts → jsx-runtime-CenT41Y0.d.ts} +1 -1
  16. package/dist/jsx-runtime.d.ts +2 -2
  17. package/dist/jsx-runtime.js +3 -3
  18. package/dist/{testing-CVpo7aRl.d.ts → testing-B8J_HhF4.d.ts} +6 -2
  19. package/dist/testing.d.ts +2 -2
  20. package/dist/testing.js +3 -3
  21. package/docs/authentication.md +45 -3
  22. package/docs/authorization.md +2 -4
  23. package/docs/cache.md +29 -5
  24. package/docs/configuration.md +84 -7
  25. package/docs/console.md +41 -2
  26. package/docs/container.md +4 -0
  27. package/docs/csrf.md +2 -2
  28. package/docs/database.md +27 -2
  29. package/docs/deployment.md +42 -18
  30. package/docs/eloquent-factories.md +7 -3
  31. package/docs/eloquent-mutators.md +2 -1
  32. package/docs/eloquent-observers.md +2 -0
  33. package/docs/eloquent-relationships.md +34 -1
  34. package/docs/eloquent-resources.md +253 -0
  35. package/docs/eloquent.md +47 -0
  36. package/docs/errors.md +12 -3
  37. package/docs/events.md +3 -1
  38. package/docs/export.md +3 -3
  39. package/docs/facades.md +1 -0
  40. package/docs/helpers.md +33 -2
  41. package/docs/inertia.md +11 -1
  42. package/docs/installation.md +6 -2
  43. package/docs/laravel.md +71 -0
  44. package/docs/lifecycle.md +9 -5
  45. package/docs/live.md +88 -8
  46. package/docs/mail.md +32 -5
  47. package/docs/middleware.md +20 -12
  48. package/docs/navigation.json +12 -0
  49. package/docs/notifications.md +22 -0
  50. package/docs/pagination.md +4 -0
  51. package/docs/passwords.md +4 -6
  52. package/docs/providers.md +4 -6
  53. package/docs/queues.md +70 -2
  54. package/docs/requests.md +42 -3
  55. package/docs/responses.md +9 -5
  56. package/docs/routing.md +118 -7
  57. package/docs/scheduling.md +27 -0
  58. package/docs/session.md +2 -2
  59. package/docs/starter-kits.md +26 -7
  60. package/docs/storage.md +10 -4
  61. package/docs/testing.md +10 -2
  62. package/docs/two-factor.md +38 -4
  63. package/docs/upgrade.md +182 -0
  64. package/docs/validation.md +70 -9
  65. package/docs/views.md +1 -0
  66. package/docs/vite.md +20 -1
  67. package/package.json +43 -35
  68. package/dist/chunk-4NCMY3ZS.js.map +0 -1
  69. package/dist/chunk-BKA5F3TH.js.map +0 -1
  70. package/dist/chunk-UBSIBGXR.js.map +0 -1
package/docs/requests.md CHANGED
@@ -400,7 +400,21 @@ with `EncryptCookies.except('appearance')` in `bootstrap/app.ts` to read it as i
400
400
  Two global middleware tidy the input of every request before your code sees it, as in Laravel: `TrimStrings` trims
401
401
  every text value, except the `password`, `password_confirmation` and `current_password` fields, and
402
402
  `ConvertEmptyStringsToNull` turns empty text into `null`. They apply to the query string and to the body, JSON
403
- included. They always run: Laravel's switches to turn them off, for every request or some, aren't in Oriel.
403
+ included.
404
+
405
+ To leave some fields as sent, or some requests, list them in `bootstrap/app.ts`. A string is a field (dotted for nested
406
+ input) and a callback leaves the whole request untouched when it returns `true`:
407
+
408
+ ```ts
409
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
410
+ middleware.trimStrings({ except: ['secret', (request) => request.is('admin/*')] })
411
+ middleware.convertEmptyStringsToNull({ except: [(request) => request.is('admin/*')] })
412
+ })
413
+ ```
414
+
415
+ `TrimStrings.skipWhen(callback)` and `ConvertEmptyStringsToNull.skipWhen(callback)` do the same for every app in the
416
+ process, until `flushState()`. To turn one off for every request, take it out of the global list:
417
+ `middleware.remove(TrimStrings)`.
404
418
 
405
419
  ## Files
406
420
 
@@ -487,7 +501,9 @@ Oriel reads a JSON, URL-encoded or multipart body into memory before your code r
487
501
  `Content-Length` header gives the size, the body isn't read at all. The limit is the same for every route.
488
502
 
489
503
  A JSON body can also nest objects and arrays only so deep: past `http.max_json_depth`, 512 levels unless you change
490
- it, the request gets a 400 ("The request body is nested too deeply.").
504
+ it, the request gets a 400 ("The request body is nested too deeply."). A form field or query key may have 64 levels
505
+ of brackets, as in PHP: `a[b][c]` has two. One with more gets a 400 ("The request input is nested too deeply."), which
506
+ no setting changes.
491
507
 
492
508
  Raise them in `config/http.ts`, where `max_body_size` is a number of bytes, and `null` turns either limit off:
493
509
 
@@ -530,4 +546,27 @@ browser asked for. The list may also be a comma-separated string, so it can come
530
546
  When you can't know your load balancers' addresses, as with many cloud providers, trust them all with `'*'`. Do it
531
547
  only when nothing can reach your app except through them: any client could then set the `X-Forwarded-*` headers.
532
548
 
533
- Laravel's trusted hosts (`trustHosts()`) aren't in Oriel: let your web server or load balancer refuse unknown hosts.
549
+ ## Configuring trusted hosts
550
+
551
+ Your app answers a request whatever its `Host` header says, so links it builds from the request, such as a password
552
+ reset link, could point to another site. To answer only your own hosts, turn on `TrustHosts` in `bootstrap/app.ts`, as
553
+ in Laravel:
554
+
555
+ ```ts
556
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
557
+ middleware.trustHosts()
558
+ })
559
+ ```
560
+
561
+ It then answers only `APP_URL`'s host and its subdomains; another host gets a 404, "Bad hostname provided.". List
562
+ more hosts, or patterns, with `at`, and leave `APP_URL`'s out with `subdomains: false`:
563
+
564
+ ```ts
565
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
566
+ middleware.trustHosts({ at: ['shop.example.com', /^preview-\d+\.example\.net$/], subdomains: false })
567
+ })
568
+ ```
569
+
570
+ A host name in `at` matches as a whole, in any case, and `at` may be a function that returns the list. The host checked
571
+ is the one from `X-Forwarded-Host` when a [trusted proxy](#configuring-trusted-proxies) sends it. It checks nothing in
572
+ the `local` environment or while your tests run.
package/docs/responses.md CHANGED
@@ -56,9 +56,11 @@ Route.get('/', () => view('welcome', { name: 'Taylor' }))
56
56
 
57
57
  [Views](views.md) covers writing them.
58
58
 
59
- > [!WARNING]
60
- > Return a view, not a TSX element. A route that returns `<Welcome />` sends the element's description as JSON. To
61
- > send TSX that isn't a view file, render it first: `response(await View.renderToString(<Welcome />))`.
59
+ A route may return a TSX element too: it's sent rendered, as a view is, and an `<html>` root gets its doctype:
60
+
61
+ ```tsx
62
+ Route.get('/hello', () => <h1>Hello</h1>)
63
+ ```
62
64
 
63
65
  ### Attaching headers to responses
64
66
 
@@ -107,7 +109,8 @@ export class AddFrameOptions implements Middleware {
107
109
  }
108
110
  ```
109
111
 
110
- Oriel has no `cache.headers` middleware: set `Cache-Control` as any other header.
112
+ Set `Cache-Control` as any other header, or let the `cache.headers` middleware set it for a route, as
113
+ `cache.headers:public;max_age=3600;etag` ([the middleware aliases](middleware.md#middleware-aliases) list its options).
111
114
 
112
115
  ### Attaching cookies to responses
113
116
 
@@ -351,7 +354,8 @@ const created = response().json({ name: 'Abigail' }, 201)
351
354
  ```
352
355
 
353
356
  The data goes through `JSON.stringify()`, so models and collections become JSON as they do when a route returns
354
- them, and dates become ISO strings. Laravel's JSONP `withCallback()` isn't in Oriel.
357
+ them, and dates become ISO strings. Laravel's JSONP `withCallback()` isn't in Oriel. To choose a model's keys for an
358
+ API, return an [API resource](eloquent-resources.md) instead.
355
359
 
356
360
  ### Empty responses
357
361
 
package/docs/routing.md CHANGED
@@ -494,6 +494,39 @@ if (request().routeIs('admin.*')) {
494
494
  }
495
495
  ```
496
496
 
497
+ #### Signed URLs
498
+
499
+ A signed URL carries a signature in its query string, made with your app key, so your app can tell that nobody changed
500
+ it: a link to unsubscribe from a list, or to confirm something, sent by email to someone who isn't signed in.
501
+ `url().signedRoute()` signs a named route's URL, and `temporarySignedRoute()` one that expires, at a `Date` or a number
502
+ of seconds from now:
503
+
504
+ ```ts
505
+ import { Route, url } from '@orieljs/framework'
506
+
507
+ Route.get('/unsubscribe/{user}', () => 'Unsubscribed').middleware('signed').name('unsubscribe')
508
+
509
+ const link = url().signedRoute('unsubscribe', { user: 1 })
510
+
511
+ const forAnHour = url().temporarySignedRoute('unsubscribe', 3600, { user: 1 })
512
+ ```
513
+
514
+ The `signed` middleware answers a request whose signature is missing, wrong or expired with a 403, so the route only
515
+ runs for a URL your app signed. To check one yourself, for a response of your own:
516
+
517
+ ```ts
518
+ import { abort, request, Route, url } from '@orieljs/framework'
519
+
520
+ Route.get('/unsubscribe/{user}', () => {
521
+ if (!url().hasValidSignature(request())) abort(401)
522
+ return 'Unsubscribed'
523
+ }).name('unsubscribe')
524
+ ```
525
+
526
+ A URL signed with `false` as the last argument signs only its path, so it works behind any host; check it with
527
+ `signed:relative`. A signature made with your previous app key (`APP_PREVIOUS_KEYS`) still checks out after you rotate
528
+ the key.
529
+
497
530
  ## Route groups
498
531
 
499
532
  A group shares middleware, a controller, a URI prefix or a name prefix between its routes. Groups can be nested: a
@@ -674,10 +707,62 @@ a 404.
674
707
 
675
708
  ## Rate limiting
676
709
 
710
+ ### Defining rate limiters
711
+
712
+ A named rate limiter says how often a request may reach the routes that use it. Define one with `RateLimiter.for()`,
713
+ in a service provider's `boot()`, as in Laravel. Its function gets the request and returns a `Limit`:
714
+
715
+ ```ts title="app/Providers/AppServiceProvider.ts"
716
+ import { Limit, RateLimiter, ServiceProvider } from '@orieljs/framework'
717
+ import type { User } from '../Models/User'
718
+
719
+ export class AppServiceProvider extends ServiceProvider {
720
+ override boot(): void {
721
+ RateLimiter.for('api', async (request) => {
722
+ const user = await request.user<User>()
723
+
724
+ return Limit.perMinute(60).by(user?.id ?? request.ip())
725
+ })
726
+ }
727
+ }
728
+ ```
729
+
730
+ `Limit.perSecond()`, `perMinute()`, `perHour()` and `perDay()` take the number of requests, and a number of seconds,
731
+ minutes, hours or days for the window (1 unless you give it); `Limit.perMinutes(5, 100)` allows 100 every five
732
+ minutes. `by()` names what is counted, such as the user or the IP address. A limit without `by()` is one count for
733
+ every client. `Limit.none()` doesn't limit at all, for a user who shouldn't be:
734
+
735
+ ```ts
736
+ declare const isVip: (request: unknown) => Promise<boolean>
737
+ // ---cut---
738
+ RateLimiter.for('uploads', async (request) =>
739
+ (await isVip(request)) ? Limit.none() : Limit.perMinute(100).by(request.ip()),
740
+ )
741
+ ```
742
+
743
+ The function may return several limits, each counted on its own: past any of them, the request is refused.
744
+
745
+ ```ts
746
+ RateLimiter.for('login', (request) => [Limit.perMinute(500), Limit.perMinute(3).by(String(request.input('email')))])
747
+ ```
748
+
749
+ Oriel defines no limiter of its own, not even `api`: `throttle:<name>` with a name nothing defined is an error,
750
+ "Rate limiter [api] is not defined.".
751
+
677
752
  ### Attaching rate limiters to routes
678
753
 
679
- The `throttle` middleware limits how often a client may call a route. Its parameters are the number of requests and
680
- the window in minutes:
754
+ Attach a named limiter with `throttle:<name>`:
755
+
756
+ ```ts
757
+ declare const handler: () => string
758
+ // ---cut---
759
+ Route.middleware('throttle:uploads').group(() => {
760
+ Route.post('/audio', handler)
761
+ Route.post('/video', handler)
762
+ })
763
+ ```
764
+
765
+ Or give `throttle` its numbers, the number of requests and the window in minutes:
681
766
 
682
767
  ```ts
683
768
  declare const handler: () => string
@@ -693,11 +778,9 @@ cache's default store, or in the store that a `limiter` key in `config/cache.ts`
693
778
  `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers. Past the limit, the route answers 429 ("Too Many Attempts.")
694
779
  with `Retry-After`, the seconds to wait, and `X-RateLimit-Reset`, the Unix time the window ends.
695
780
 
696
- Every route behind `throttle` adds to the same count for a client, whatever its numbers. To count a group of routes
697
- on its own, give `throttle` a third parameter, a prefix for its key: `throttle:10,1,uploads`.
698
-
699
- > [!WARNING]
700
- > Laravel's named rate limiters (`RateLimiter::for()`) aren't in Oriel: give `throttle` its numbers directly.
781
+ Every route behind `throttle` with numbers adds to the same count for a client, whatever its numbers. To count a
782
+ group of routes on its own, give `throttle` a third parameter, a prefix for its key: `throttle:10,1,uploads`. A named
783
+ limiter's counts are its own: two limiters never share one, even with the same `by()`.
701
784
 
702
785
  ## Form method spoofing
703
786
 
@@ -736,3 +819,31 @@ const parameters = request().route() // every parameter, by name
736
819
 
737
820
  `Route.has('login')` tells you whether a route of that name exists, as a new app's welcome page does to show its login
738
821
  link.
822
+
823
+ ## Cross-origin resource sharing (CORS)
824
+
825
+ Oriel answers CORS `OPTIONS` requests with the values you configure, as Laravel does. The `HandleCors` middleware,
826
+ in the global list, answers a browser's preflight request at once, and adds the CORS headers to every other response
827
+ on the paths it covers, errors included.
828
+
829
+ By default it covers `api/*`: any origin may call your API routes, with any method and header, but without cookies or
830
+ other credentials. To change that, publish the configuration with `node oriel install:api`, which writes
831
+ `config/cors.ts` (or create the file yourself):
832
+
833
+ ```ts title="config/cors.ts"
834
+ export default {
835
+ paths: ['api/*'],
836
+ allowed_methods: ['*'],
837
+ allowed_origins: ['https://app.example.com', '*.example.org'],
838
+ allowed_origins_patterns: [],
839
+ allowed_headers: ['*'],
840
+ exposed_headers: [],
841
+ max_age: 0,
842
+ supports_credentials: false,
843
+ }
844
+ ```
845
+
846
+ `paths` are patterns as `request().is()` takes them. A `*` in an origin is a wildcard, and
847
+ `allowed_origins_patterns` takes regular expressions. With `supports_credentials`, the response names the caller's
848
+ origin instead of `*` and allows credentials, so list your origins. `paths: []`, or
849
+ `middleware.remove(HandleCors)` in `bootstrap/app.ts`, turns it off.
@@ -252,6 +252,8 @@ node oriel schedule:work
252
252
  ```
253
253
 
254
254
  When one minute's run fails, as when the cache can't be read, it reports the error and goes on with the next minute.
255
+ Ctrl-C, or a `SIGTERM` from a deploy, stops it: no task starts after that, and the tasks still running give up their
256
+ `withoutOverlapping()` locks, so their next run isn't blocked.
255
257
  [Deployment](deployment.md#task-scheduling) shows both ways in production.
256
258
 
257
259
  ## Task hooks
@@ -278,3 +280,28 @@ Schedule.command('emails:send')
278
280
 
279
281
  `then()` is another name for `after()`. A task skipped by a constraint, an overlap or another server runs none of
280
282
  its hooks.
283
+
284
+ ## Events
285
+
286
+ The scheduler dispatches Laravel's [events](events.md) as it runs each due task, in `schedule:run`, `schedule:work`
287
+ and the Vercel cron alike. Each has the scheduled `task`:
288
+
289
+ - `ScheduledTaskStarting` before the task runs, once its constraints have passed and its locks are taken;
290
+ - `ScheduledTaskFinished` once it has run, with its `runtime` in seconds, to two decimals;
291
+ - `ScheduledTaskFailed` when it fails, with the `exception`. A task that throws dispatches only this one; a command
292
+ that exits non-zero, or a closure that returns `false`, dispatches `ScheduledTaskFinished` first, as in Laravel;
293
+ - `ScheduledTaskSkipped` when a `when()` or `skip()` constraint holds a due task back.
294
+
295
+ A task held back by `withoutOverlapping()` or `onOneServer()` dispatches none of them.
296
+
297
+ ```ts title="app/Providers/AppServiceProvider.ts"
298
+ import { Event, Log, ScheduledTaskFailed, ServiceProvider } from '@orieljs/framework'
299
+
300
+ export class AppServiceProvider extends ServiceProvider {
301
+ override boot(): void {
302
+ Event.listen(ScheduledTaskFailed, (event: ScheduledTaskFailed) => {
303
+ void Log.error(`${event.task.getSummaryForDisplay()} failed`, { error: String(event.exception) })
304
+ })
305
+ }
306
+ }
307
+ ```
package/docs/session.md CHANGED
@@ -103,8 +103,8 @@ time that session is written.
103
103
 
104
104
  The `redis` driver talks to the Redis server of `config/database.ts`: `connection` names an entry of
105
105
  `database.redis` (`default` unless you set `SESSION_CONNECTION`). Its keys start with `oriel_session:` and expire after
106
- `lifetime`. Oriel's Redis client, `ioredis`, comes with the framework, and the connection is closed when your app shuts
107
- down.
106
+ `lifetime`. The driver needs Oriel's Redis client, `ioredis`, which you install yourself (`npm install ioredis`), and
107
+ the connection is closed when your app shuts down.
108
108
 
109
109
  ## Interacting with the session
110
110
 
@@ -129,7 +129,7 @@ The Live kit's pages are components in `app/Live`, and its other markup is in `r
129
129
  | `resources/js/app.ts` | Starts Live in the browser, with the Light / Dark / System switch, the menus, and the dashboard's Copy buttons and tick |
130
130
 
131
131
  A Live page's route names its component: `Route.get('login', Login)`. Every update the browser sends runs the page
132
- route's `auth`, `verified`, `guest` and `can` middleware again, so a signed-out tab can't run an action. TypeScript's
132
+ route's `auth`, `verified`, `guest`, `can` and `password.confirm` middleware again, so a signed-out tab can't run an action. TypeScript's
133
133
  `private` doesn't hide a method from the browser: name it with `#` or a leading `_`, or mark it `@Locked`.
134
134
  [Live](live.md) explains components.
135
135
 
@@ -236,16 +236,33 @@ welcome page in `routes/web.ts`:
236
236
  | `/settings` | `GET` | | A redirect to `/settings/profile` |
237
237
  | `/settings/profile` | `GET`, `PATCH`, `DELETE` | `profile.edit`, `profile.update`, `profile.destroy` | The profile page, updating the name and email, and deleting the account |
238
238
  | `/settings/password` | `GET`, `PUT` | `password.edit`, `password.update` | The password page, and changing the password |
239
+ | `/settings/two-factor` | `GET`, `POST`, `DELETE` | `two-factor.show`, `two-factor.enable`, `two-factor.disable` | The two-factor page, setting up an app, and turning it off |
240
+ | `/settings/two-factor/confirm` | `POST` | `two-factor.confirm` | Confirming the app with its first code |
241
+ | `/settings/two-factor/recovery-codes` | `POST` | `two-factor.regenerate-recovery-codes` | New recovery codes |
239
242
  | `/settings/appearance` | `GET` | `appearance.edit` | The appearance page |
243
+ | `/confirm-password` | `GET`, `POST` | `password.confirm`, `password.confirm.store` | The password confirmation page, and confirming |
244
+ | `/two-factor-challenge` | `GET`, `POST` | `two-factor.login`, `two-factor.login.store` | The code asked for at login, and sending it |
240
245
 
241
246
  Where a URI has two methods and one name, the name is the `GET` route's. The guest pages are behind the `guest`
242
- middleware, and the rest behind `auth`. In the Live kit, a page's route is a `GET` route to its component, and the
247
+ middleware, and the rest behind `auth`; the two-factor settings also behind `password.confirm`, and the challenge
248
+ behind `guest` and `two-factor.challenge`. In the Live kit, a page's route is a `GET` route to its component, and the
243
249
  forms are the component's actions: the `POST`, `PATCH`, `PUT` and `DELETE` routes, and `logout` and
244
250
  `verification.send`, aren't there. `node oriel route:list` shows them all.
245
251
 
246
- > [!NOTE]
247
- > Laravel's starter kits also have two-factor authentication and a password confirmation page. Oriel's kits have
248
- > neither.
252
+ ### Two-factor authentication
253
+
254
+ Settings → Two-factor asks for the password first, then not again for `auth.password_timeout` seconds (three hours).
255
+ There a user sets up an authenticator app: the page shows a QR code and the setup key, and the app's first code turns
256
+ two-factor on. The page then shows eight recovery codes, once, with a link to download them; it can make new ones, and
257
+ turn two-factor off. From then on, logging in asks for a code from the app, or a recovery code, each of which works
258
+ once.
259
+
260
+ The setup key and the codes stay off the browser's history: the Inertia kits encrypt the page's history state and
261
+ clear it when the user logs out, and the Live kit drops them from the page as it is left.
262
+
263
+ The kits set `two_factor: { enabled: true, methods: ['app'] }` in `config/auth.ts`, so it is each user's choice: a
264
+ user who hasn't set up an app signs in with the password alone. [Two-factor login](two-factor.md) covers the settings,
265
+ and email codes, which the kits don't offer.
249
266
 
250
267
  ### Email verification
251
268
 
@@ -288,11 +305,13 @@ The kits limit the routes an attacker would try many times:
288
305
  | Signing in | 5 failed attempts per email address and IP address, then locked for a minute |
289
306
  | The verification link, and sending it again | 6 requests a minute (`throttle:6,1`) |
290
307
  | Changing the password | 6 requests a minute (`throttle:6,1`) |
308
+ | Confirming the password | 6 requests a minute (`throttle:6,1`) |
309
+ | A two-factor code at login | 5 a minute for each account (the `two-factor` limiter in `routes/auth.ts`), and 5 wrong codes end the login |
291
310
  | Sending a reset link | One link per email address a minute (`passwords.users.throttle` in `config/auth.ts`) |
292
311
 
293
312
  The login limit is in `LoginRequest`, in `app/Http/Requests/Auth` (in the Live kit, in the `Login` component): change
294
- the `5` in `tooManyAttempts()` to allow more. In the Live kit, sending the verification mail again and changing the
295
- password are component actions, which have no limit of their own.
313
+ the `5` in `tooManyAttempts()` to allow more. In the Live kit, the forms are component actions, which take no route
314
+ middleware: `throttle()`, in `app/Support/throttle.ts`, gives them the same limits.
296
315
 
297
316
  ### Customizing user creation
298
317
 
package/docs/storage.md CHANGED
@@ -20,7 +20,8 @@ import { Storage } from '@orieljs/framework'
20
20
  await Storage.disk('local').put('example.txt', 'Contents')
21
21
  ```
22
22
 
23
- A path that climbs out of the root with `../` throws.
23
+ A path that climbs out of the root with `../` throws. A new app's `local` disk has `serve: true`, so its files can be
24
+ shared through [temporary URLs](#temporary-urls), as in Laravel 11.
24
25
 
25
26
  ### The public disk
26
27
 
@@ -127,15 +128,20 @@ set), with the bucket as a subdomain, or in the path when `usePathStyleEndpoint`
127
128
 
128
129
  ### Temporary URLs
129
130
 
130
- On an S3 disk, `temporaryUrl()` gives a signed URL that works until the date you give:
131
+ `temporaryUrl()` gives a signed URL that works until the date you give, on an S3 disk and on a `local` disk with
132
+ `serve: true`:
131
133
 
132
134
  ```ts
133
135
  import { Storage } from '@orieljs/framework'
134
136
 
135
- const url = await Storage.disk('s3').temporaryUrl('report.pdf', new Date(Date.now() + 5 * 60_000))
137
+ const url = await Storage.disk('local').temporaryUrl('invoices/1042.pdf', new Date(Date.now() + 5 * 60_000))
136
138
  ```
137
139
 
138
- A `local` disk can't sign URLs, and throws.
140
+ A served `local` disk has a route, `storage.<disk>`, at its `url`'s path, else at `/storage`: the link above is
141
+ `<APP_URL>/storage/invoices/1042.pdf?expires=…&signature=…`, signed over its path and query with your `APP_KEY`. The
142
+ route sends the file inline, uncached and sandboxed, so nothing in it runs. A link that's altered or has expired gets
143
+ a 403, or a 404 in production, and a path with no file gets a 404. On a served disk whose `visibility` is `public`,
144
+ every file is sent, with or without a signature. A `local` disk without `serve: true` throws.
139
145
 
140
146
  ### File metadata
141
147
 
package/docs/testing.md CHANGED
@@ -123,8 +123,16 @@ node oriel test tests/Feature/User.test.ts
123
123
  node oriel test --filter="the application returns"
124
124
  ```
125
125
 
126
- Anything after `--` goes to Vitest as it is, such as `node oriel test -- --coverage` for a coverage report (with
127
- `@vitest/coverage-v8` installed).
126
+ Options `oriel test` doesn't know go to Vitest as they are, in their place, such as `--coverage` for a coverage report
127
+ (with `@vitest/coverage-v8` installed) or `-t` for a name pattern:
128
+
129
+ ```sh
130
+ node oriel test --coverage
131
+
132
+ node oriel test tests/Unit --reporter=dot
133
+ ```
134
+
135
+ So does anything after `--`, for an option `oriel` takes itself: `node oriel test -- --help` shows Vitest's help.
128
136
 
129
137
  ### Running tests in parallel
130
138
 
@@ -16,7 +16,10 @@ Each user has a method:
16
16
  - **Authenticator app**: the user scans a QR code with an app such as Google Authenticator or 1Password and confirms
17
17
  it with one code; from then on, the app's code is asked for.
18
18
 
19
- The starter kits don't have two-factor pages yet: you add the routes and pages your app needs, as below.
19
+ The browser [starter kits](starter-kits.md#two-factor-authentication) have it: Settings → Two-factor, behind a
20
+ password confirmation, sets up an authenticator app and shows its recovery codes, and logging in then asks for the
21
+ app's code. They set `methods: ['app']`, so a user who hasn't set up an app signs in with the password alone. The API
22
+ kit and the skeleton don't have it: add the routes and pages your app needs, as below.
20
23
 
21
24
  ## Turning it on
22
25
 
@@ -57,8 +60,9 @@ A user is asked only by a method open to them: email, or an app they have set up
57
60
  hasn't set up an app has no method open, so their password alone signs them in, as in Fortify, where two-factor is each
58
61
  user's choice. Keep `'email'` in `methods` to ask every user for a second factor.
59
62
 
60
- The secret and the recovery codes are encrypted with your app key; emailed codes are kept hashed, in the cache, so the
61
- cache must be shared by your servers (`database` or `redis`, as on Vercel).
63
+ The secret and the recovery codes are encrypted with your app key; emailed codes are kept hashed, in the cache, and so
64
+ is the count of wrong codes, so the cache must be shared by your servers (`database` or `redis`, as on Vercel). With
65
+ `file` or `array` on several servers, each one would count on its own.
62
66
 
63
67
  ## Signing in
64
68
 
@@ -103,7 +107,7 @@ Route.middleware('two-factor.challenge').group(() => {
103
107
  return redirect().intended('dashboard')
104
108
  }
105
109
  return back().withErrors({ code: 'That code is not right.' })
106
- })
110
+ }).middleware('throttle:5,1')
107
111
 
108
112
  Route.post('/two-factor-challenge/email', async () => {
109
113
  await TwoFactor.useMethod('email')
@@ -165,6 +169,10 @@ Route.middleware('auth').group(() => {
165
169
  on a working app throws `TwoFactorAppAlreadyEnabledError`, since a new secret would silently stop the old app's codes: call
166
170
  `disableApp(user)` first. Before the app is confirmed, calling `enableApp()` again just replaces the secret.
167
171
 
172
+ `TwoFactor.appSetup(user)` gives the same secret, URL and QR code again while the app waits for its code, so the page
173
+ can show them after a reload or a wrong code without a new secret. It is `undefined` before `enableApp()` and once the
174
+ app is confirmed.
175
+
168
176
  In a test, `totpCode(secret, Date.now())` from `@orieljs/framework` gives the code the app would show.
169
177
 
170
178
  ## Recovery codes
@@ -185,6 +193,32 @@ import type { User } from '../Models/User'
185
193
  TwoFactor.requireWhen((user) => (user as User).getAttribute('is_admin') === true)
186
194
  ```
187
195
 
196
+ ## Adding two-factor to an app made before alpha.16
197
+
198
+ An app made from a starter kit owns its copy of the kit's code, so upgrading Oriel adds no pages, and nobody is asked
199
+ for a code. To add what a new kit app has:
200
+
201
+ 1. Add the columns: `node oriel two-factor:install`, then `node oriel migrate`.
202
+ 2. Turn it on for the authenticator app only: `two_factor: { enabled: true, methods: ['app'] }` in `config/auth.ts`.
203
+ Not email: `TwoFactor`'s default method is email, which every user has from the start, so with it every user would
204
+ be asked for a mailed code at their next login.
205
+ 3. Hide the secret and the codes: `User`'s `hidden` gains `two_factor_secret` and `two_factor_recovery_codes`, and its
206
+ `casts` `two_factor_confirmed_at: 'datetime'`. Run `node oriel model:types` again.
207
+ 4. Ask for the code at login: `TwoFactor.attempt()` instead of `Auth.attempt()`, as in [Signing in](#signing-in). In
208
+ an Inertia kit that is `LoginRequest.authenticate()`, and `AuthenticatedSessionController.store()` redirects a
209
+ `'challenge'` to `two-factor.login`; in the Live kit, the `Login` component's `login()` does both. At a
210
+ `'challenge'`, put the email in the session as `login.email`: the `two-factor` rate limiter counts codes by it,
211
+ and by the IP address without it.
212
+ 5. Copy the rest from a new alpha.16 app of the same stack (`npm create @orieljs@latest`):
213
+ - **Inertia kits:** `ConfirmablePasswordController` and `TwoFactorChallengeController` (in
214
+ `app/Http/Controllers/Auth`), `Settings/TwoFactorController`, their routes in `routes/auth.ts` (with the
215
+ `two-factor` rate limiter) and `routes/settings.ts`, the pages `Auth/ConfirmPassword`, `Auth/TwoFactorChallenge`
216
+ and `Settings/TwoFactor`, and the Two-factor tab in `SettingsLayout` and the sidebar.
217
+ - **Live kit:** the `ConfirmPassword`, `TwoFactorChallenge` and `Settings/TwoFactor` components, `app/Support/throttle.ts`,
218
+ their routes, the tab in `components/settings/layout.tsx` and the sidebar, and the Copy button's lines in
219
+ `resources/js/app.ts`.
220
+ - **Both:** the two-factor styles at the end of `resources/css/app.css`, `tests/TwoFactor.ts` and the two-factor tests.
221
+
188
222
  ## Events
189
223
 
190
224
  `TwoFactorChallenged` (the code was asked for), `TwoFactorFailed` (a wrong code), `TwoFactorAuthenticated` (the user is