KScript 文档
ZH

路由与 API

设置:kscript.json

kscript.json 的 http 部分包含路由及其中间件的设置。以下每项均为可选:

JSON
{
  "http": {
    "routes": ["routes.kscript", { "file": "api/v1.kscript", "prefix": "/api/v1", "api": true }],  // default: routes/web.*, routes/api.*, routes.* and api.*
    "middleware": ["log"],                      // for every route
    "groups": { "api": ["cors", "throttle"] },  // names for lists of middleware
    "views": "views",                           // where @view() looks first; never served
    "api_prefix": "/api",                       // the prefix of api.* files
    "write_files": true,                        // false: controllers and their live actions can only read files
    "cors": { "origins": ["*"], "methods": ["GET", "POST"], "headers": ["Content-Type", "Authorization"], "credentials": false },
    "auth": { "token_env": "API_TOKEN", "login": "/login", "lifetime": "2h" },  // and the KScript.Auth settings in auth.md
    "throttle": { "limit": 60, "seconds": 60, "store": "memory" },  // store: memory, file or database (shared by every server)
    "upload_limit": "8MB",                      // the most a request's uploaded files may be, in all
    "body_limit": "1MB",                        // the most a body without files (a form, JSON, text) may be
    "headers": { "X-Frame-Options": "DENY" },   // sent with every response that doesn't set its own; see below for the ones sent anyway
    "proxy": { "secret_env": "PROXY_SECRET", "header": "X-Proxy-Secret" },  // believe a reverse proxy's X-Forwarded-For
    "openapi": { "routes": "auto", "title": "People API", "version": "1.2.0", "file": "openapi.json" }  // or true / false
  }
}

每个设置也都列在kscript.json 参考中。

每个响应的标头

每个 kscript serve 发出的响应都会自动带上三个标头,因此新站点默认就是安全的:

响应头 值 作用
X-Content-Type-Options nosniff 浏览器会使用服务器为文件指定的类型,绝不会自行猜测其他类型。
Referrer-Policy strict-origin-when-cross-origin 其他网站只会获知本站的来源(origin),而不会获知访问者来自的具体页面。
X-Frame-Options SAMEORIGIN 其他网站无法在框架中显示此页面。当你的Content-Security-Policy包含frame-ancestors时会被省略,后者的含义更为准确。

headers 为 kscript serve 返回的所有内容添加响应头,包括页面、文件、路由、通行密钥以及 登录提供方。若某个响应自行设置了响应头,则保留其自身的设置;此处指定的响应头会替换上面的同名响应头。值为空则不发送该响应头:"X-Frame-Options": "" 允许任何网站将本站嵌入框架中。这里适合配置网站的其他安全响应头:

JSON
{
  "http": {
    "headers": {
      "Content-Security-Policy": "default-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self' {client_origins}",
      "X-Content-Type-Options": "nosniff",
      "Referrer-Policy": "same-origin"
    }
  }
}

{client_origins} 是登录提供方的 clients.json 中应用来源(origin)的列表,以空格分隔,这样无需重复列出每个应用,就能允许将用户送回应用的表单提交。

位于反向代理之后

在 Caddy 或 nginx 等代理后面时,每个请求都来自代理本身,因此速率限制和登录尝试次数会把所有访问者混为一谈。让代理在请求头中发送一个密钥,并指定保存该密钥的环境变量名称:

JSON
{ "http": { "proxy": { "secret_env": "PROXY_SECRET", "header": "X-Proxy-Secret" } } }

携带该密钥的请求会按其 X-Forwarded-For 中的最后一个地址计数,即代理添加的那个地址;其他请求则按其来源地址计数,这样通过其他途径到达服务器的请求就无法冒充他人。throttle 会按 /64 段统计 IPv6 访问者,因为同一台机器可以使用该段中的任意地址。