@acryldev/create-blends 1.7.1 → 1.7.3
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.
- package/{LICENSE → docs/framework/LICENSE} +3 -1
- package/docs/framework/README.md +70 -0
- package/docs/framework/agents/index.md +59 -0
- package/docs/framework/api/acryl.md +247 -0
- package/docs/framework/api/context.md +478 -0
- package/docs/framework/api/exception.md +80 -0
- package/docs/framework/api/index.md +12 -0
- package/docs/framework/api/presets.md +62 -0
- package/docs/framework/api/request.md +396 -0
- package/docs/framework/api/routing.md +303 -0
- package/docs/framework/api/summary.md +143 -0
- package/docs/framework/concepts/benchmarks.md +26 -0
- package/docs/framework/concepts/developer-experience.md +5 -0
- package/docs/framework/concepts/middleware.md +21 -0
- package/docs/framework/concepts/motivation.md +14 -0
- package/docs/framework/concepts/routers.md +63 -0
- package/docs/framework/concepts/stacks.md +235 -0
- package/docs/framework/concepts/web-standard.md +27 -0
- package/docs/framework/cordis/acryl-in-a-cordis-app.md +160 -0
- package/docs/framework/cordis/concepts.md +105 -0
- package/docs/framework/cordis/middleware.md +8 -0
- package/docs/framework/cordis/migration-from-0-3.md +111 -0
- package/docs/framework/cordis/migration-from-0-4.md +14 -0
- package/docs/framework/cordis/migration-from-dsh-webserver.md +109 -0
- package/docs/framework/cordis/migration-to-1-0.md +46 -0
- package/docs/framework/cordis/mounting.md +85 -0
- package/docs/framework/cordis/node-server.md +100 -0
- package/docs/framework/cordis/plugin-lifecycle.md +111 -0
- package/docs/framework/cordis/surfaces.md +71 -0
- package/docs/framework/cordis/transport-and-cancellation.md +57 -0
- package/docs/framework/cordis/validation.md +135 -0
- package/docs/framework/getting-started/basic.md +201 -0
- package/docs/framework/getting-started/bun.md +219 -0
- package/docs/framework/getting-started/deploy.md +133 -0
- package/docs/framework/getting-started/desktop.md +80 -0
- package/docs/framework/getting-started/nodejs.md +365 -0
- package/docs/framework/getting-started/other-runtimes.md +30 -0
- package/docs/framework/guides/best-practices.md +231 -0
- package/docs/framework/guides/bring-your-own-tool.md +218 -0
- package/docs/framework/guides/client-modules.md +210 -0
- package/docs/framework/guides/create-acrylblends.md +143 -0
- package/docs/framework/guides/data.md +314 -0
- package/docs/framework/guides/examples.md +3 -0
- package/docs/framework/guides/faq.md +19 -0
- package/docs/framework/guides/forms-and-sessions.md +235 -0
- package/docs/framework/guides/helpers.md +33 -0
- package/docs/framework/guides/jsx-dom.md +301 -0
- package/docs/framework/guides/jsx.md +487 -0
- package/docs/framework/guides/middleware.md +253 -0
- package/docs/framework/guides/production.md +80 -0
- package/docs/framework/guides/rpc.md +878 -0
- package/docs/framework/guides/testing.md +133 -0
- package/docs/framework/guides/validation.md +470 -0
- package/docs/framework/helpers/accepts.md +60 -0
- package/docs/framework/helpers/adapter.md +57 -0
- package/docs/framework/helpers/conninfo.md +77 -0
- package/docs/framework/helpers/cookie.md +232 -0
- package/docs/framework/helpers/css.md +282 -0
- package/docs/framework/helpers/dev.md +64 -0
- package/docs/framework/helpers/factory.md +180 -0
- package/docs/framework/helpers/html.md +123 -0
- package/docs/framework/helpers/jwt.md +184 -0
- package/docs/framework/helpers/proxy.md +115 -0
- package/docs/framework/helpers/route.md +143 -0
- package/docs/framework/helpers/ssg.md +390 -0
- package/docs/framework/helpers/streaming.md +224 -0
- package/docs/framework/helpers/testing.md +118 -0
- package/docs/framework/helpers/websocket.md +208 -0
- package/docs/framework/middleware/builtin/basic-auth.md +165 -0
- package/docs/framework/middleware/builtin/bearer-auth.md +138 -0
- package/docs/framework/middleware/builtin/body-limit.md +71 -0
- package/docs/framework/middleware/builtin/cache.md +99 -0
- package/docs/framework/middleware/builtin/combine.md +94 -0
- package/docs/framework/middleware/builtin/compress.md +59 -0
- package/docs/framework/middleware/builtin/context-storage.md +74 -0
- package/docs/framework/middleware/builtin/cors.md +134 -0
- package/docs/framework/middleware/builtin/csrf.md +105 -0
- package/docs/framework/middleware/builtin/etag.md +54 -0
- package/docs/framework/middleware/builtin/ip-restriction.md +69 -0
- package/docs/framework/middleware/builtin/jsx-renderer.md +283 -0
- package/docs/framework/middleware/builtin/jwk.md +192 -0
- package/docs/framework/middleware/builtin/jwt.md +145 -0
- package/docs/framework/middleware/builtin/language.md +232 -0
- package/docs/framework/middleware/builtin/logger.md +74 -0
- package/docs/framework/middleware/builtin/loopback-only.md +31 -0
- package/docs/framework/middleware/builtin/method-not-allowed.md +48 -0
- package/docs/framework/middleware/builtin/method-override.md +80 -0
- package/docs/framework/middleware/builtin/mount.md +103 -0
- package/docs/framework/middleware/builtin/pretty-json.md +53 -0
- package/docs/framework/middleware/builtin/request-id.md +87 -0
- package/docs/framework/middleware/builtin/secure-headers.md +247 -0
- package/docs/framework/middleware/builtin/timeout.md +98 -0
- package/docs/framework/middleware/builtin/timing.md +100 -0
- package/docs/framework/middleware/builtin/trailing-slash.md +74 -0
- package/docs/framework/middleware/third-party.md +4 -0
- package/docs/framework/workshop/README.md +294 -0
- package/docs/framework/workshop/facilitator.md +101 -0
- package/package.json +3 -3
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# JWK Auth Middleware
|
|
2
|
+
|
|
3
|
+
The JWK Auth Middleware authenticates requests by verifying tokens using JWK (JSON Web Key). It checks for an `Authorization` header and other configured sources, such as cookies, if specified. It validates tokens using the provided `keys`, retrieves keys from `jwks_uri` if specified, and supports token extraction from cookies if the `cookie` option is set.
|
|
4
|
+
|
|
5
|
+
## What this middleware validates
|
|
6
|
+
|
|
7
|
+
For each token, `jwk()`:
|
|
8
|
+
|
|
9
|
+
- Parses and validates the JWT header format.
|
|
10
|
+
- Requires a `kid` header and finds a matching key by `kid`.
|
|
11
|
+
- Rejects symmetric algorithms (`HS256`, `HS384`, `HS512`).
|
|
12
|
+
- Requires the header `alg` to be included in the configured `alg` allowlist.
|
|
13
|
+
- If a matched JWK has an `alg` field, requires it to match the JWT header `alg`.
|
|
14
|
+
- Verifies the token signature with the matched key.
|
|
15
|
+
- By default, validates time-based claims: `nbf`, `exp`, and `iat`.
|
|
16
|
+
|
|
17
|
+
Optional claim validation can be configured with the `verification` option:
|
|
18
|
+
|
|
19
|
+
- `iss`: validates issuer when provided.
|
|
20
|
+
- `aud`: validates audience when provided.
|
|
21
|
+
|
|
22
|
+
If you need additional token checks beyond the above (for example, custom application-level authorization rules), add them in your own middleware after `jwk()`.
|
|
23
|
+
|
|
24
|
+
> **Note.** The Authorization header sent from the client must have a specified scheme.
|
|
25
|
+
>
|
|
26
|
+
> Example: `Bearer my.token.value` or `Basic my.token.value`
|
|
27
|
+
|
|
28
|
+
## Import
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { Acryl } from '@acryldev/blends'
|
|
32
|
+
import { jwk } from '@acryldev/blends/jwk'
|
|
33
|
+
import { verifyWithJwks } from '@acryldev/blends/jwt'
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Usage
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
const app = new Acryl()
|
|
40
|
+
|
|
41
|
+
app.use(
|
|
42
|
+
'/auth/*',
|
|
43
|
+
jwk({
|
|
44
|
+
jwks_uri: `https://${backendServer}/.well-known/jwks.json`,
|
|
45
|
+
alg: ['RS256'],
|
|
46
|
+
})
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
app.get('/auth/page', (c) => {
|
|
50
|
+
return c.text('You are authorized')
|
|
51
|
+
})
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Get payload:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
const app = new Acryl()
|
|
58
|
+
|
|
59
|
+
app.use(
|
|
60
|
+
'/auth/*',
|
|
61
|
+
jwk({
|
|
62
|
+
jwks_uri: `https://${backendServer}/.well-known/jwks.json`,
|
|
63
|
+
alg: ['RS256'],
|
|
64
|
+
})
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
app.get('/auth/page', (c) => {
|
|
68
|
+
const payload = c.get('jwtPayload')
|
|
69
|
+
return c.json(payload) // eg: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
|
|
70
|
+
})
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Anonymous access:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
const app = new Acryl()
|
|
77
|
+
|
|
78
|
+
app.use(
|
|
79
|
+
'/auth/*',
|
|
80
|
+
jwk({
|
|
81
|
+
jwks_uri: (c) =>
|
|
82
|
+
`https://${c.env.authServer}/.well-known/jwks.json`,
|
|
83
|
+
alg: ['RS256'],
|
|
84
|
+
allow_anon: true,
|
|
85
|
+
})
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
app.get('/auth/page', (c) => {
|
|
89
|
+
const payload = c.get('jwtPayload')
|
|
90
|
+
return c.json(payload ?? { message: 'hello anon' })
|
|
91
|
+
})
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Using `verifyWithJwks` outside of middleware
|
|
95
|
+
|
|
96
|
+
The `verifyWithJwks` utility function can be used to verify JWT tokens outside of Acryl's middleware context, such as in SvelteKit SSR pages or other server-side environments:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const id_payload = await verifyWithJwks(
|
|
100
|
+
id_token,
|
|
101
|
+
{
|
|
102
|
+
jwks_uri: 'https://your-auth-server/.well-known/jwks.json',
|
|
103
|
+
allowedAlgorithms: ['RS256'],
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
cf: { cacheEverything: true, cacheTtl: 3600 },
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Configuring JWKS fetch request options
|
|
112
|
+
|
|
113
|
+
To configure how JWKS is retrieved from `jwks_uri`, pass fetch request options as the second argument of `jwk()`.
|
|
114
|
+
|
|
115
|
+
This argument is `RequestInit` and is used only for the JWKS fetch request.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const app = new Acryl()
|
|
119
|
+
|
|
120
|
+
app.use(
|
|
121
|
+
'/auth/*',
|
|
122
|
+
jwk(
|
|
123
|
+
{
|
|
124
|
+
jwks_uri: `https://${backendServer}/.well-known/jwks.json`,
|
|
125
|
+
alg: ['RS256'],
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
headers: {
|
|
129
|
+
Authorization: 'Bearer TOKEN',
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
)
|
|
133
|
+
)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Options
|
|
137
|
+
|
|
138
|
+
### **(required)** alg: `AsymmetricAlgorithm[]`
|
|
139
|
+
|
|
140
|
+
An array of allowed asymmetric algorithms used for token verification.
|
|
141
|
+
|
|
142
|
+
Available types are `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.
|
|
143
|
+
|
|
144
|
+
### *(optional)* keys: `AcrylJsonWebKey[] | (c: Context) => Promise<AcrylJsonWebKey[]>`
|
|
145
|
+
|
|
146
|
+
The values of your public keys, or a function that returns them. The function receives the Context object.
|
|
147
|
+
|
|
148
|
+
### *(optional)* jwks_uri: `string` | `(c: Context) => Promise<string>`
|
|
149
|
+
|
|
150
|
+
If this value is set, attempt to fetch JWKs from this URI, expecting a JSON response with `keys`, which are added to the provided `keys` option. You can also pass a callback function to dynamically determine the JWKS URI using the Context.
|
|
151
|
+
|
|
152
|
+
### *(optional)* allow_anon: `boolean`
|
|
153
|
+
|
|
154
|
+
If this value is set to `true`, requests without a valid token will be allowed to pass through the middleware. Use `c.get('jwtPayload')` to check if the request is authenticated. The default is `false`.
|
|
155
|
+
|
|
156
|
+
### *(optional)* cookie: `string`
|
|
157
|
+
|
|
158
|
+
If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.
|
|
159
|
+
|
|
160
|
+
### *(optional)* headerName: `string`
|
|
161
|
+
|
|
162
|
+
The name of the header to look for the JWT token. The default is `Authorization`.
|
|
163
|
+
|
|
164
|
+
### *(optional)* realm: `string`
|
|
165
|
+
|
|
166
|
+
The protection space described by the `realm` parameter of the `WWW-Authenticate` challenge header returned on `401` responses. The default is the request URL.
|
|
167
|
+
|
|
168
|
+
### *(optional)* verification: `VerifyOptions`
|
|
169
|
+
|
|
170
|
+
Configure claim validation behavior in addition to signature verification:
|
|
171
|
+
|
|
172
|
+
[Keep in sync with jwt.md]: #
|
|
173
|
+
|
|
174
|
+
#### *(optional)* VerifyOptions.iss: `string | RegExp`
|
|
175
|
+
|
|
176
|
+
The expected issuer used for token verification. The `iss` claim will **not** be checked if this isn't set.
|
|
177
|
+
|
|
178
|
+
#### *(optional)* VerifyOptions.aud: `string | string[] | RegExp`
|
|
179
|
+
|
|
180
|
+
The expected audience used for token verification. If this is set, the token must include an `aud` claim and at least one audience value must match.
|
|
181
|
+
|
|
182
|
+
#### *(optional)* VerifyOptions.nbf: `boolean`
|
|
183
|
+
|
|
184
|
+
The `nbf` (not before) claim will be verified if present and this is set to `true`. The default is `true`.
|
|
185
|
+
|
|
186
|
+
#### *(optional)* VerifyOptions.iat: `boolean`
|
|
187
|
+
|
|
188
|
+
The `iat` (issued at) claim will be verified if present and this is set to `true`. The default is `true`.
|
|
189
|
+
|
|
190
|
+
#### *(optional)* VerifyOptions.exp: `boolean`
|
|
191
|
+
|
|
192
|
+
The `exp` (expiration time) claim will be verified if present and this is set to `true`. The default is `true`.
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# JWT Auth Middleware
|
|
2
|
+
|
|
3
|
+
The JWT Auth Middleware provides authentication by verifying the token with JWT.
|
|
4
|
+
The middleware will check for an `Authorization` header if the `cookie` option is not set. You can customize the header name using the `headerName` option.
|
|
5
|
+
|
|
6
|
+
> **Note.** The Authorization header sent from the client must have a specified scheme.
|
|
7
|
+
>
|
|
8
|
+
> Example: `Bearer my.token.value` or `Basic my.token.value`
|
|
9
|
+
|
|
10
|
+
## Import
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { Acryl } from '@acryldev/blends'
|
|
14
|
+
import { jwt } from '@acryldev/blends/jwt'
|
|
15
|
+
import type { JwtVariables } from '@acryldev/blends/jwt'
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// Specify the variable types to infer the `c.get('jwtPayload')`:
|
|
22
|
+
type Variables = JwtVariables
|
|
23
|
+
|
|
24
|
+
const app = new Acryl<{ Variables: Variables }>()
|
|
25
|
+
|
|
26
|
+
app.use(
|
|
27
|
+
'/auth/*',
|
|
28
|
+
jwt({
|
|
29
|
+
secret: process.env.JWT_SECRET!,
|
|
30
|
+
alg: 'HS256',
|
|
31
|
+
})
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
app.get('/auth/page', (c) => {
|
|
35
|
+
return c.text('You are authorized')
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Get payload:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
const app = new Acryl()
|
|
43
|
+
|
|
44
|
+
app.use(
|
|
45
|
+
'/auth/*',
|
|
46
|
+
jwt({
|
|
47
|
+
secret: process.env.JWT_SECRET!,
|
|
48
|
+
alg: 'HS256',
|
|
49
|
+
verification: {
|
|
50
|
+
iss: 'my-trusted-issuer',
|
|
51
|
+
aud: 'my-api',
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
app.get('/auth/page', (c) => {
|
|
57
|
+
const payload = c.get('jwtPayload')
|
|
58
|
+
return c.json(payload) // eg: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022, "iss": "my-trusted-issuer" }
|
|
59
|
+
})
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**Tip.**
|
|
63
|
+
|
|
64
|
+
`jwt()` is just a middleware function. If you want to use an environment variable (eg: `c.env.JWT_SECRET`), you can use it as follows:
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
app.use('/auth/*', (c, next) => {
|
|
68
|
+
const jwtMiddleware = jwt({
|
|
69
|
+
secret: c.env.JWT_SECRET,
|
|
70
|
+
alg: 'HS256',
|
|
71
|
+
})
|
|
72
|
+
return jwtMiddleware(c, next)
|
|
73
|
+
})
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Options
|
|
77
|
+
|
|
78
|
+
### **(required)** secret: `string`
|
|
79
|
+
|
|
80
|
+
A value of your secret key.
|
|
81
|
+
|
|
82
|
+
### **(required)** alg: `string`
|
|
83
|
+
|
|
84
|
+
An algorithm type that is used for verifying.
|
|
85
|
+
|
|
86
|
+
Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.
|
|
87
|
+
|
|
88
|
+
### *(optional)* cookie: `string`
|
|
89
|
+
|
|
90
|
+
If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.
|
|
91
|
+
|
|
92
|
+
### *(optional)* headerName: `string`
|
|
93
|
+
|
|
94
|
+
The name of the header to look for the JWT token. The default is `Authorization`.
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
app.use(
|
|
98
|
+
'/auth/*',
|
|
99
|
+
jwt({
|
|
100
|
+
secret: process.env.JWT_SECRET!,
|
|
101
|
+
alg: 'HS256',
|
|
102
|
+
headerName: 'x-custom-auth-header',
|
|
103
|
+
})
|
|
104
|
+
)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### *(optional)* realm: `string`
|
|
108
|
+
|
|
109
|
+
The protection space described by the `realm` parameter of the `WWW-Authenticate` challenge header returned on `401` responses. The default is the request URL.
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
app.use(
|
|
113
|
+
'/auth/*',
|
|
114
|
+
jwt({
|
|
115
|
+
secret: process.env.JWT_SECRET!,
|
|
116
|
+
realm: 'my-protected-api',
|
|
117
|
+
})
|
|
118
|
+
)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### *(optional)* verification: `VerifyOptions`
|
|
122
|
+
|
|
123
|
+
Options controlling verification of the token.
|
|
124
|
+
|
|
125
|
+
[Keep in sync with jwk.md]: #
|
|
126
|
+
|
|
127
|
+
#### *(optional)* VerifyOptions.iss: `string | RegExp`
|
|
128
|
+
|
|
129
|
+
The expected issuer used for token verification. The `iss` claim will **not** be checked if this isn't set.
|
|
130
|
+
|
|
131
|
+
#### *(optional)* VerifyOptions.aud: `string | string[] | RegExp`
|
|
132
|
+
|
|
133
|
+
The expected audience used for token verification. If this is set, the token must include an `aud` claim and at least one audience value must match.
|
|
134
|
+
|
|
135
|
+
#### *(optional)* VerifyOptions.nbf: `boolean`
|
|
136
|
+
|
|
137
|
+
The `nbf` (not before) claim will be verified if present and this is set to `true`. The default is `true`.
|
|
138
|
+
|
|
139
|
+
#### *(optional)* VerifyOptions.iat: `boolean`
|
|
140
|
+
|
|
141
|
+
The `iat` (issued at) claim will be verified if present and this is set to `true`. The default is `true`.
|
|
142
|
+
|
|
143
|
+
#### *(optional)* VerifyOptions.exp: `boolean`
|
|
144
|
+
|
|
145
|
+
The `exp` (expiration time) claim will be verified if present and this is set to `true`. The default is `true`.
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# Language Middleware
|
|
2
|
+
|
|
3
|
+
The Language Detector middleware automatically determines a user's preferred language (locale) from various sources and makes it available via `c.get('language')`. Detection strategies include query parameters, cookies, headers, and URL path segments. Perfect for internationalization (i18n) and locale-specific content.
|
|
4
|
+
|
|
5
|
+
## Import
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Acryl } from '@acryldev/blends'
|
|
9
|
+
import { languageDetector } from '@acryldev/blends/language'
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Basic Usage
|
|
13
|
+
|
|
14
|
+
Detect language from query string, cookie, and header (default order), with fallback to English:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
const app = new Acryl()
|
|
18
|
+
|
|
19
|
+
app.use(
|
|
20
|
+
languageDetector({
|
|
21
|
+
supportedLanguages: ['en', 'ar', 'ja'], // Must include fallback
|
|
22
|
+
fallbackLanguage: 'en', // Required
|
|
23
|
+
})
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
app.get('/', (c) => {
|
|
27
|
+
const lang = c.get('language')
|
|
28
|
+
return c.text(`Hello! Your language is ${lang}`)
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Client Examples
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
# Via path
|
|
36
|
+
curl http://localhost:8787/ar/home
|
|
37
|
+
|
|
38
|
+
# Via query parameter
|
|
39
|
+
curl http://localhost:8787/?lang=ar
|
|
40
|
+
|
|
41
|
+
# Via cookie
|
|
42
|
+
curl -H 'Cookie: language=ja' http://localhost:8787/
|
|
43
|
+
|
|
44
|
+
# Via header
|
|
45
|
+
curl -H 'Accept-Language: ar,en;q=0.9' http://localhost:8787/
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Default Configuration
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
export const DEFAULT_OPTIONS: DetectorOptions = {
|
|
52
|
+
order: ['querystring', 'cookie', 'header'],
|
|
53
|
+
lookupQueryString: 'lang',
|
|
54
|
+
lookupCookie: 'language',
|
|
55
|
+
lookupFromHeaderKey: 'accept-language',
|
|
56
|
+
lookupFromPathIndex: 0,
|
|
57
|
+
caches: ['cookie'],
|
|
58
|
+
ignoreCase: true,
|
|
59
|
+
fallbackLanguage: 'en',
|
|
60
|
+
supportedLanguages: ['en'],
|
|
61
|
+
cookieOptions: {
|
|
62
|
+
sameSite: 'Strict',
|
|
63
|
+
secure: true,
|
|
64
|
+
maxAge: 365 * 24 * 60 * 60,
|
|
65
|
+
httpOnly: true,
|
|
66
|
+
},
|
|
67
|
+
debug: false,
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Key Behaviors
|
|
72
|
+
|
|
73
|
+
### Detection Workflow
|
|
74
|
+
|
|
75
|
+
1. **Order**: Checks sources in this sequence by default:
|
|
76
|
+
- Query parameter (?lang=ar)
|
|
77
|
+
- Cookie (language=ar)
|
|
78
|
+
- Accept-Language header
|
|
79
|
+
|
|
80
|
+
2. **Caching**: Stores detected language in a cookie (1 year by default)
|
|
81
|
+
|
|
82
|
+
3. **Fallback**: Uses `fallbackLanguage` if no valid detection (must be in `supportedLanguages`)
|
|
83
|
+
|
|
84
|
+
## Advanced Configuration
|
|
85
|
+
|
|
86
|
+
### Custom Detection Order
|
|
87
|
+
|
|
88
|
+
Prioritize URL path detection (e.g., /en/about):
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
app.use(
|
|
92
|
+
languageDetector({
|
|
93
|
+
order: ['path', 'cookie', 'querystring', 'header'],
|
|
94
|
+
lookupFromPathIndex: 0, // /en/profile → index 0 = 'en'
|
|
95
|
+
supportedLanguages: ['en', 'ar'],
|
|
96
|
+
fallbackLanguage: 'en',
|
|
97
|
+
})
|
|
98
|
+
)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Progressive Locale Matching
|
|
102
|
+
|
|
103
|
+
When a detected locale code like `ja-JP` is not in `supportedLanguages`, the middleware progressively truncates subtags to find a match. For example, `zh-Hant-CN` will try `zh-Hant`, then `zh`. An exact match is always preferred.
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
app.use(
|
|
107
|
+
languageDetector({
|
|
108
|
+
supportedLanguages: ['en', 'ja', 'zh-Hant'],
|
|
109
|
+
fallbackLanguage: 'en',
|
|
110
|
+
})
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
// Accept-Language: ja-JP → matches 'ja'
|
|
114
|
+
// Accept-Language: zh-Hant-CN → matches 'zh-Hant'
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Language Code Transformation
|
|
118
|
+
|
|
119
|
+
Normalize complex codes (e.g., en-US → en):
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
app.use(
|
|
123
|
+
languageDetector({
|
|
124
|
+
convertDetectedLanguage: (lang) => lang.split('-')[0],
|
|
125
|
+
supportedLanguages: ['en', 'ja'],
|
|
126
|
+
fallbackLanguage: 'en',
|
|
127
|
+
})
|
|
128
|
+
)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Cookie Configuration
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
app.use(
|
|
135
|
+
languageDetector({
|
|
136
|
+
lookupCookie: 'app_lang',
|
|
137
|
+
caches: ['cookie'],
|
|
138
|
+
cookieOptions: {
|
|
139
|
+
path: '/', // Cookie path
|
|
140
|
+
sameSite: 'Lax', // Cookie same-site policy
|
|
141
|
+
secure: true, // Only send over HTTPS
|
|
142
|
+
maxAge: 86400 * 365, // 1 year expiration
|
|
143
|
+
httpOnly: true, // Not accessible via JavaScript
|
|
144
|
+
domain: '.example.com', // Optional: specific domain
|
|
145
|
+
},
|
|
146
|
+
})
|
|
147
|
+
)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
To disable cookie caching:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
languageDetector({
|
|
154
|
+
caches: false,
|
|
155
|
+
})
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Debugging
|
|
159
|
+
|
|
160
|
+
Log detection steps:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
languageDetector({
|
|
164
|
+
debug: true, // Shows: "Detected from querystring: ar"
|
|
165
|
+
})
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Options Reference
|
|
169
|
+
|
|
170
|
+
### Basic Options
|
|
171
|
+
|
|
172
|
+
| Option | Type | Default | Required | Description |
|
|
173
|
+
| :------------------- | :--------------- | :------------------------------------ | :------- | :--------------------- |
|
|
174
|
+
| `supportedLanguages` | `string[]` | `['en']` | Yes | Allowed language codes |
|
|
175
|
+
| `fallbackLanguage` | `string` | `'en'` | Yes | Default language |
|
|
176
|
+
| `order` | `DetectorType[]` | `['querystring', 'cookie', 'header']` | No | Detection sequence |
|
|
177
|
+
| `debug` | `boolean` | `false` | No | Enable logging |
|
|
178
|
+
|
|
179
|
+
### Detection Options
|
|
180
|
+
|
|
181
|
+
| Option | Type | Default | Description |
|
|
182
|
+
| :-------------------- | :------- | :------------------ | :------------------- |
|
|
183
|
+
| `lookupQueryString` | `string` | `'lang'` | Query parameter name |
|
|
184
|
+
| `lookupCookie` | `string` | `'language'` | Cookie name |
|
|
185
|
+
| `lookupFromHeaderKey` | `string` | `'accept-language'` | Header name |
|
|
186
|
+
| `lookupFromPathIndex` | `number` | `0` | Path segment index |
|
|
187
|
+
|
|
188
|
+
### Cookie Options
|
|
189
|
+
|
|
190
|
+
| Option | Type | Default | Description |
|
|
191
|
+
| :----------------------- | :---------------------------- | :----------- | :------------------- |
|
|
192
|
+
| `caches` | `CacheType[] \| false` | `['cookie']` | Cache settings |
|
|
193
|
+
| `cookieOptions.path` | `string` | `'/'` | Cookie path |
|
|
194
|
+
| `cookieOptions.sameSite` | `'Strict' \| 'Lax' \| 'None'` | `'Strict'` | SameSite policy |
|
|
195
|
+
| `cookieOptions.secure` | `boolean` | `true` | HTTPS only |
|
|
196
|
+
| `cookieOptions.maxAge` | `number` | `31536000` | Expiration (seconds) |
|
|
197
|
+
| `cookieOptions.httpOnly` | `boolean` | `true` | JS accessibility |
|
|
198
|
+
| `cookieOptions.domain` | `string` | `undefined` | Cookie domain |
|
|
199
|
+
|
|
200
|
+
### Advanced Options
|
|
201
|
+
|
|
202
|
+
| Option | Type | Default | Description |
|
|
203
|
+
| :------------------------ | :------------------------- | :---------- | :------------------------ |
|
|
204
|
+
| `ignoreCase` | `boolean` | `true` | Case-insensitive matching |
|
|
205
|
+
| `convertDetectedLanguage` | `(lang: string) => string` | `undefined` | Language code transformer |
|
|
206
|
+
|
|
207
|
+
## Validation & Error Handling
|
|
208
|
+
|
|
209
|
+
- `fallbackLanguage` must be in `supportedLanguages` (throws error during setup)
|
|
210
|
+
- `lookupFromPathIndex` must be ≥ 0
|
|
211
|
+
- Invalid configurations throw errors during middleware initialization
|
|
212
|
+
- Failed detections silently use `fallbackLanguage`
|
|
213
|
+
|
|
214
|
+
## Common Recipes
|
|
215
|
+
|
|
216
|
+
### Path-Based Routing
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
app.get('/:lang/home', (c) => {
|
|
220
|
+
const lang = c.get('language') // 'en', 'ar', etc.
|
|
221
|
+
return c.json({ message: getLocalizedContent(lang) })
|
|
222
|
+
})
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Multiple Supported Languages
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
languageDetector({
|
|
229
|
+
supportedLanguages: ['en', 'en-GB', 'ar', 'ar-EG'],
|
|
230
|
+
convertDetectedLanguage: (lang) => lang.replace('_', '-'), // Normalize
|
|
231
|
+
})
|
|
232
|
+
```
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Logger Middleware
|
|
2
|
+
|
|
3
|
+
It's a simple logger.
|
|
4
|
+
|
|
5
|
+
## Import
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Acryl } from '@acryldev/blends'
|
|
9
|
+
import { logger } from '@acryldev/blends/logger'
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
const app = new Acryl()
|
|
16
|
+
|
|
17
|
+
app.use(logger())
|
|
18
|
+
app.get('/', (c) => c.text('Acryl!'))
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Logging Details
|
|
22
|
+
|
|
23
|
+
The Logger Middleware logs the following details for each request:
|
|
24
|
+
|
|
25
|
+
- **Incoming Request**: Logs the HTTP method, request path, and incoming request.
|
|
26
|
+
- **Outgoing Response**: Logs the HTTP method, request path, response status code, and request/response times.
|
|
27
|
+
- **Status Code Coloring**: Response status codes are color-coded for better visibility and quick identification of status categories. Different status code categories are represented by different colors.
|
|
28
|
+
- **Elapsed Time**: The time taken for the request/response cycle is logged in a human-readable format, either in milliseconds (ms) or seconds (s).
|
|
29
|
+
|
|
30
|
+
By using the Logger Middleware, you can easily monitor the flow of requests and responses in your Acryl application and quickly identify any issues or performance bottlenecks.
|
|
31
|
+
|
|
32
|
+
You can also extend the middleware further by providing your own `PrintFunc` function for tailored logging behavior.
|
|
33
|
+
|
|
34
|
+
> **Tip.**
|
|
35
|
+
> To disable _status code coloring_, you can set a `NO_COLOR` environment variable. This is a common way to disable ANSI color escape codes in logging libraries, and is described at <https://no-color.org/>.
|
|
36
|
+
|
|
37
|
+
## PrintFunc
|
|
38
|
+
|
|
39
|
+
The Logger Middleware accepts an optional `PrintFunc` function as a parameter. This function allows you to customize the logger and add additional logs.
|
|
40
|
+
|
|
41
|
+
## Options
|
|
42
|
+
|
|
43
|
+
### *(optional)* fn: `PrintFunc(str: string, ...rest: string[])`
|
|
44
|
+
|
|
45
|
+
- `str`: Passed by the logger.
|
|
46
|
+
- `...rest`: Additional string props to be printed to console.
|
|
47
|
+
|
|
48
|
+
### Example
|
|
49
|
+
|
|
50
|
+
Setting up a custom `PrintFunc` function to the Logger Middleware:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
export const customLogger = (message: string, ...rest: string[]) => {
|
|
54
|
+
console.log(message, ...rest)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
app.use(logger(customLogger))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Setting up the custom logger in a route:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
app.post('/blog', (c) => {
|
|
64
|
+
// Routing logic
|
|
65
|
+
|
|
66
|
+
customLogger('Blog saved:', `Path: ${blog.url},`, `ID: ${blog.id}`)
|
|
67
|
+
// Output
|
|
68
|
+
// <-- POST /blog
|
|
69
|
+
// Blog saved: Path: /blog/example, ID: 1
|
|
70
|
+
// --> POST /blog 201 93ms
|
|
71
|
+
|
|
72
|
+
// Return Context
|
|
73
|
+
})
|
|
74
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Loopback Only Middleware
|
|
2
|
+
|
|
3
|
+
The guard for a local app's own routes, such as a control API a desktop window calls:
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { loopbackOnly } from '@acryldev/blends/loopback-only'
|
|
7
|
+
|
|
8
|
+
app.use('/control/*', loopbackOnly())
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
A request passes only when:
|
|
12
|
+
|
|
13
|
+
- the peer is a loopback address and arrived on the real local port, both read from the transport, never from a header;
|
|
14
|
+
- the `Host` header names a loopback hostname (`127.0.0.1`, `localhost`, `[::1]`, or `hostnames`) with that port, which stops DNS
|
|
15
|
+
rebinding;
|
|
16
|
+
- for a request that changes things (not `GET`, `HEAD`, `OPTIONS`), any `Origin` is this same authority (`mutations: 'none'` turns this
|
|
17
|
+
off).
|
|
18
|
+
|
|
19
|
+
An in-process call has no socket and is refused unless `inProcess: 'allow'` says the host's own code may call it. Everything refused gets a
|
|
20
|
+
403.
|
|
21
|
+
|
|
22
|
+
A private route that no other program on the machine may call either, such as a workspace's file and terminal routes, takes
|
|
23
|
+
`callers: 'own-page'`:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
app.use('/api/workspace/*', loopbackOnly({ callers: 'own-page', hostnames: ['127.0.0.1'] }))
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Then every request must come from a page this app served: an `Origin` that is exactly this authority (with `Sec-Fetch-Site` absent or
|
|
30
|
+
`same-origin`), or, for a read, which browsers often send without `Origin`, `Sec-Fetch-Site: same-origin` and a `Referer` from this
|
|
31
|
+
authority. A script with no `Origin` is refused even for a read. `fromOwnPage(c, authority)` is the same check for middleware of your own.
|