acrylblends 0.2.0 → 0.3.0

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 (109) hide show
  1. package/dist/index.d.ts +17 -16
  2. package/dist/index.js +39 -19
  3. package/dist/index.js.map +1 -1
  4. package/package.json +1 -1
  5. package/plugins/acryl-inspect/LICENSE +21 -0
  6. package/plugins/acryl-inspect/plugin.json +11 -0
  7. package/plugins/acryl-inspect/src/index.ts +3 -0
  8. package/plugins/acryl-inspect/src/report.ts +123 -0
  9. package/plugins/acryl-inspect/src/service.ts +66 -0
  10. package/plugins/acryl-inspect/tests/report.spec.ts +64 -0
  11. package/plugins/acryl-inspect/tests/service.spec.ts +120 -0
  12. package/plugins/acryl-inspect/upstream.json +18 -0
  13. package/plugins/acryl-node-server/LICENSE +21 -0
  14. package/plugins/acryl-node-server/plugin.json +12 -0
  15. package/plugins/acryl-node-server/src/index.ts +94 -0
  16. package/plugins/acryl-node-server/tests/server.spec.ts +105 -0
  17. package/plugins/acryl-node-server/upstream.json +18 -0
  18. package/plugins/acryl-router/LICENSE +21 -0
  19. package/plugins/acryl-router/plugin.json +12 -0
  20. package/plugins/acryl-router/src/compose.ts +21 -0
  21. package/plugins/acryl-router/src/context.ts +59 -0
  22. package/plugins/acryl-router/src/helpers/index.ts +3 -0
  23. package/plugins/acryl-router/src/helpers/read-body.ts +59 -0
  24. package/plugins/acryl-router/src/helpers/sse.ts +83 -0
  25. package/plugins/acryl-router/src/helpers/validate.ts +44 -0
  26. package/plugins/acryl-router/src/http-error.ts +21 -0
  27. package/plugins/acryl-router/src/index.ts +6 -0
  28. package/plugins/acryl-router/src/middleware/body-limit.ts +25 -0
  29. package/plugins/acryl-router/src/middleware/cors.ts +46 -0
  30. package/plugins/acryl-router/src/middleware/index.ts +6 -0
  31. package/plugins/acryl-router/src/middleware/logger.ts +21 -0
  32. package/plugins/acryl-router/src/middleware/loopback-only.ts +82 -0
  33. package/plugins/acryl-router/src/middleware/request-id.ts +24 -0
  34. package/plugins/acryl-router/src/middleware/secure-headers.ts +23 -0
  35. package/plugins/acryl-router/src/pattern.ts +89 -0
  36. package/plugins/acryl-router/src/registrar.ts +90 -0
  37. package/plugins/acryl-router/src/service.ts +164 -0
  38. package/plugins/acryl-router/src/table.ts +156 -0
  39. package/plugins/acryl-router/src/types.ts +73 -0
  40. package/plugins/acryl-router/src/util.ts +23 -0
  41. package/plugins/acryl-router/tests/api.spec.ts +223 -0
  42. package/plugins/acryl-router/tests/conformance.ts +170 -0
  43. package/plugins/acryl-router/tests/helpers.spec.ts +172 -0
  44. package/plugins/acryl-router/tests/live-install.spec.ts +64 -0
  45. package/plugins/acryl-router/tests/loader.spec.ts +71 -0
  46. package/plugins/acryl-router/tests/middleware.spec.ts +183 -0
  47. package/plugins/acryl-router/tests/service.spec.ts +211 -0
  48. package/plugins/acryl-router/tests/table.spec.ts +47 -0
  49. package/plugins/acryl-router/upstream.json +20 -0
  50. package/plugins/acryl-router-http/LICENSE +21 -0
  51. package/plugins/acryl-router-http/plugin.json +11 -0
  52. package/plugins/acryl-router-http/src/bridge.ts +52 -0
  53. package/plugins/acryl-router-http/src/index.ts +63 -0
  54. package/plugins/acryl-router-http/src/serve.ts +24 -0
  55. package/plugins/acryl-router-http/tests/adapter.spec.ts +170 -0
  56. package/plugins/acryl-router-http/tests/stream.spec.ts +133 -0
  57. package/plugins/acryl-router-http/tests/surfaces.spec.ts +99 -0
  58. package/plugins/acryl-router-http/upstream.json +22 -0
  59. package/plugins/acryl-state/LICENSE +21 -0
  60. package/plugins/acryl-state/plugin.json +12 -0
  61. package/plugins/acryl-state/src/cell.ts +67 -0
  62. package/plugins/acryl-state/src/index.ts +3 -0
  63. package/plugins/acryl-state/src/react.ts +11 -0
  64. package/plugins/acryl-state/src/service.ts +101 -0
  65. package/plugins/acryl-state/tests/cell.spec.ts +71 -0
  66. package/plugins/acryl-state/tests/react.spec.ts +39 -0
  67. package/plugins/acryl-state/tests/service.spec.ts +132 -0
  68. package/plugins/acryl-state/upstream.json +20 -0
  69. package/plugins/builder/script.ts +8 -9
  70. package/plugins/extensions/index.ts +18 -1
  71. package/plugins/openai/prompt.ts +9 -5
  72. package/plugins/tasks/index.ts +14 -0
  73. package/plugins/tsconfig.json +9 -1
  74. package/templates/agent/blend.yaml +5 -7
  75. package/templates/agent/src/app.ts +8 -8
  76. package/templates/agent/src/routes.ts +32 -41
  77. package/templates/agent/template.json +3 -3
  78. package/templates/agent/test/builder.test.ts +22 -14
  79. package/templates/agent/test/model.test.ts +2 -3
  80. package/templates/{app → blank}/blend.yaml +3 -3
  81. package/templates/{app → blank}/src/app.ts +5 -5
  82. package/templates/blank/src/routes.ts +14 -0
  83. package/templates/blank/template.json +1 -0
  84. package/templates/{app → blank}/test/app.test.ts +1 -1
  85. package/templates/todo/README.md +27 -0
  86. package/templates/todo/blend.yaml +25 -0
  87. package/templates/todo/gitignore +2 -0
  88. package/templates/todo/package.json +23 -0
  89. package/templates/todo/src/app.ts +71 -0
  90. package/templates/todo/src/main.ts +19 -0
  91. package/templates/todo/src/page.ts +28 -0
  92. package/templates/todo/src/todo.ts +96 -0
  93. package/templates/todo/template.json +1 -0
  94. package/templates/todo/test/todo.test.ts +145 -0
  95. package/templates/todo/tsconfig.json +19 -0
  96. package/templates/todo/upstream.json +12 -0
  97. package/plugins/events/index.ts +0 -42
  98. package/plugins/events/plugin.json +0 -9
  99. package/plugins/http/index.ts +0 -64
  100. package/plugins/http/plugin.json +0 -10
  101. package/plugins/server/index.ts +0 -138
  102. package/plugins/server/plugin.json +0 -10
  103. package/templates/app/src/routes.ts +0 -14
  104. package/templates/app/template.json +0 -1
  105. /package/templates/{app → blank}/README.md +0 -0
  106. /package/templates/{app → blank}/gitignore +0 -0
  107. /package/templates/{app → blank}/package.json +0 -0
  108. /package/templates/{app → blank}/src/main.ts +0 -0
  109. /package/templates/{app → blank}/tsconfig.json +0 -0
@@ -0,0 +1,83 @@
1
+ import type { RouteContext } from '../types.ts'
2
+
3
+ export interface SseStream {
4
+ /** Send one event. Objects and arrays are sent as JSON; strings as they are. */
5
+ send(data: unknown, options?: { readonly event?: string, readonly id?: string }): void
6
+ /** Send a comment line (a keep-alive that clients ignore). */
7
+ comment(text: string): void
8
+ /** End the stream from the server side. */
9
+ close(): void
10
+ /** Aborted when the client goes away or the router is disposed. */
11
+ readonly signal: AbortSignal
12
+ }
13
+
14
+ const HEADERS = {
15
+ 'content-type': 'text/event-stream; charset=utf-8',
16
+ 'cache-control': 'no-store',
17
+ 'x-content-type-options': 'nosniff',
18
+ } as const
19
+
20
+ const encode = (text: string): Uint8Array => new TextEncoder().encode(text)
21
+
22
+ export interface SseOptions {
23
+ /** A comment line is sent this often so proxies and browsers keep an idle stream open. Default 15 seconds. */
24
+ readonly keepAliveMs?: number
25
+ }
26
+
27
+ const DEFAULT_KEEP_ALIVE_MS = 15_000
28
+
29
+ /**
30
+ * A server-sent-event response. `run` starts the stream; whatever cleanup function it returns runs exactly once when the stream
31
+ * ends for any reason (the client disconnects, `close()`, a plugin unload, the router being disposed). The request is held in flight with `waitUntil`
32
+ * until then, so disposal waits for the stream instead of leaking it.
33
+ */
34
+ export function streamSSE(c: RouteContext, run: (stream: SseStream) => void | (() => void), options: SseOptions = {}): Response {
35
+ let finish!: () => void
36
+ c.waitUntil(new Promise<void>(resolve => { finish = resolve }))
37
+ let controller!: ReadableStreamDefaultController<Uint8Array>
38
+ let cleanup: (() => void) | undefined
39
+ let ended = false
40
+ let keepAlive: ReturnType<typeof setInterval> | undefined
41
+
42
+ const end = (): void => {
43
+ if (ended) return
44
+ ended = true
45
+ clearInterval(keepAlive)
46
+ c.signal.removeEventListener('abort', end)
47
+ try { cleanup?.() } finally {
48
+ try { controller.close() } catch { /* already closed */ }
49
+ finish()
50
+ }
51
+ }
52
+
53
+ const body = new ReadableStream<Uint8Array>({
54
+ start: ctrl => {
55
+ controller = ctrl
56
+ const stream: SseStream = {
57
+ signal: c.signal,
58
+ send: (data, options) => {
59
+ if (ended) return
60
+ const lines: string[] = []
61
+ if (options?.id !== undefined) lines.push(`id: ${options.id}`)
62
+ if (options?.event !== undefined) lines.push(`event: ${options.event}`)
63
+ const payload = typeof data === 'string' ? data : JSON.stringify(data)
64
+ for (const line of payload.split('\n')) lines.push(`data: ${line}`)
65
+ try { controller.enqueue(encode(`${lines.join('\n')}\n\n`)) } catch { end() }
66
+ },
67
+ comment: text => {
68
+ if (ended) return
69
+ try { controller.enqueue(encode(`: ${text.replaceAll('\n', ' ')}\n\n`)) } catch { end() }
70
+ },
71
+ close: end,
72
+ }
73
+ if (c.signal.aborted) { end(); return }
74
+ c.signal.addEventListener('abort', end, { once: true })
75
+ keepAlive = setInterval(() => { stream.comment('keepalive') }, options.keepAliveMs ?? DEFAULT_KEEP_ALIVE_MS)
76
+ keepAlive.unref()
77
+ cleanup = run(stream) ?? undefined
78
+ if (ended) { try { cleanup?.() } catch { /* the stream already ended */ } }
79
+ },
80
+ cancel: end,
81
+ })
82
+ return new Response(body, { headers: HEADERS })
83
+ }
@@ -0,0 +1,44 @@
1
+ import { HttpError } from '../http-error.ts'
2
+ import type { Middleware, RouteContext } from '../types.ts'
3
+ import { readJson } from './read-body.ts'
4
+
5
+ /** The slice of the Standard Schema interface this needs; Schemastery (what Cordis uses), Zod and Valibot all implement it. */
6
+ export interface StandardSchema<T = unknown> {
7
+ readonly '~standard': {
8
+ validate(value: unknown): StandardResult<T> | Promise<StandardResult<T>>
9
+ }
10
+ }
11
+
12
+ type StandardResult<T> =
13
+ | { readonly value: T, readonly issues?: undefined }
14
+ | { readonly issues: readonly { readonly message: string, readonly path?: readonly unknown[] | undefined }[] }
15
+
16
+ export type ValidationTarget = 'json' | 'query' | 'param'
17
+
18
+ const key = (target: ValidationTarget): string => `valid:${target}`
19
+
20
+ /**
21
+ * Validate part of the request against a schema before the handler runs. A failure is a 400 with the issues; success stores the
22
+ * parsed value, which the handler reads with `valid(c, target)`. `json` reads the body within the limit; `query` is the first value of each query
23
+ * parameter; `param` is the matched path parameters.
24
+ */
25
+ export function validate<T>(target: ValidationTarget, schema: StandardSchema<T>): Middleware {
26
+ return async (c, next) => {
27
+ const input = target === 'json' ? await readJson(c) : target === 'query' ? c.query() : { ...c.param() }
28
+ const result = await schema['~standard'].validate(input)
29
+ if (result.issues !== undefined) {
30
+ throw new HttpError(400, {
31
+ response: c.json({ error: `invalid ${target}`, issues: result.issues.map(issue => ({ message: issue.message, path: (issue.path ?? []).map(part => String(typeof part === 'object' && part !== null && 'key' in part ? (part as { key: unknown }).key : part)).join('.') })) }, 400),
32
+ })
33
+ }
34
+ c.set(key(target), result.value)
35
+ return next()
36
+ }
37
+ }
38
+
39
+ /** The value `validate(target, schema)` stored. Throws if that middleware did not run on this route. */
40
+ export function valid<T>(c: RouteContext, target: ValidationTarget): T {
41
+ const value = c.get<T>(key(target))
42
+ if (value === undefined) throw new Error(`valid("${target}"): no validate("${target}", schema) ran before this handler`)
43
+ return value
44
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * An error that carries the response it should become. A handler or middleware throws it to stop a request
3
+ * with a status: `throw new HttpError(401, { message: 'Sign in first' })`. The router answers with `getResponse()`; a registered
4
+ * `onError` handler still sees every other error.
5
+ */
6
+ export class HttpError extends Error {
7
+ readonly status: number
8
+ private readonly response: Response | undefined
9
+
10
+ constructor(status: number, options: { readonly message?: string, readonly response?: Response, readonly cause?: unknown } = {}) {
11
+ super(options.message ?? `HTTP ${String(status)}`, options.cause === undefined ? undefined : { cause: options.cause })
12
+ this.name = 'HttpError'
13
+ this.status = status
14
+ this.response = options.response
15
+ }
16
+
17
+ /** The response this error stands for: the one it was given, or its message as plain text with its status. */
18
+ getResponse(): Response {
19
+ return this.response ?? new Response(this.message, { status: this.status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
20
+ }
21
+ }
@@ -0,0 +1,6 @@
1
+ export { Router, Config, apply, name, type RouterHttpService } from './service.ts'
2
+ export { RouteTable, type RouteTableOptions } from './table.ts'
3
+ export { compose } from './compose.ts'
4
+ export { HttpError } from './http-error.ts'
5
+ export type { Registrar, RouteHandlers, UseArguments } from './registrar.ts'
6
+ export type { ConnectionInfo, ErrorHandler, NotFoundHandler, ResponseBody, Handler, Method, Middleware, Next, RouteContext, RouteMethod, TrailingSlash } from './types.ts'
@@ -0,0 +1,25 @@
1
+ import type { Middleware, RouteContext } from '../types.ts'
2
+
3
+ export interface BodyLimitOptions {
4
+ readonly maxBytes: number
5
+ /** The response for a body that is too large. Defaults to a 413 with a small JSON body. */
6
+ readonly onError?: (c: RouteContext) => Response | Promise<Response>
7
+ }
8
+
9
+ /** The context key under which the limit is kept for the body-reading helpers. */
10
+ export const BODY_LIMIT_KEY = 'bodyLimit'
11
+
12
+ /**
13
+ * Refuse a request whose declared `content-length` is over the limit, and remember the limit so `readJson` and `readText` enforce it on the bytes
14
+ * they read (a chunked body declares no length). A request body is a stream: only the helpers, or a handler that counts, can stop it midway.
15
+ */
16
+ export function bodyLimit(options: BodyLimitOptions): Middleware {
17
+ return async (c, next) => {
18
+ const declared = Number(c.req.headers.get('content-length'))
19
+ if (Number.isFinite(declared) && declared > options.maxBytes) {
20
+ return options.onError === undefined ? c.json({ error: 'payload too large', maxBytes: options.maxBytes }, 413) : options.onError(c)
21
+ }
22
+ c.set(BODY_LIMIT_KEY, options.maxBytes)
23
+ return next()
24
+ }
25
+ }
@@ -0,0 +1,46 @@
1
+ import type { Middleware } from '../types.ts'
2
+ import { appendVary, setHeaders } from '../util.ts'
3
+
4
+ export interface CorsOptions {
5
+ /** `'*'`, one origin, a list, or a function that returns the origin to allow (or `undefined` to refuse). */
6
+ readonly origin?: string | readonly string[] | ((origin: string) => string | undefined)
7
+ readonly allowMethods?: readonly string[]
8
+ readonly allowHeaders?: readonly string[]
9
+ readonly exposeHeaders?: readonly string[]
10
+ readonly maxAge?: number
11
+ readonly credentials?: boolean
12
+ }
13
+
14
+ const DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']
15
+
16
+ /** Cross-origin resource sharing, with preflight answered here (a 204 that never reaches the route). */
17
+ export function cors(options: CorsOptions = {}): Middleware {
18
+ const allowed = (origin: string): string | undefined => {
19
+ const rule = options.origin ?? '*'
20
+ if (typeof rule === 'function') return rule(origin)
21
+ if (typeof rule === 'string') return rule === '*' || rule === origin ? rule : undefined
22
+ return rule.includes(origin) ? origin : undefined
23
+ }
24
+ return async (c, next) => {
25
+ const origin = c.req.headers.get('origin')
26
+ const match = origin === null ? undefined : allowed(origin)
27
+ const shared: Record<string, string> = {}
28
+ if (match !== undefined) shared['access-control-allow-origin'] = match
29
+ if (options.credentials === true && match !== undefined) shared['access-control-allow-credentials'] = 'true'
30
+ if (options.exposeHeaders !== undefined && options.exposeHeaders.length > 0) shared['access-control-expose-headers'] = options.exposeHeaders.join(',')
31
+
32
+ if (c.req.method === 'OPTIONS' && c.req.headers.has('access-control-request-method')) {
33
+ const headers = { ...shared }
34
+ if (match !== undefined) {
35
+ headers['access-control-allow-methods'] = (options.allowMethods ?? DEFAULT_METHODS).join(',')
36
+ const requested = c.req.headers.get('access-control-request-headers')
37
+ const allowHeaders = options.allowHeaders ?? (requested === null ? [] : requested.split(',').map(part => part.trim()))
38
+ if (allowHeaders.length > 0) headers['access-control-allow-headers'] = allowHeaders.join(',')
39
+ if (options.maxAge !== undefined) headers['access-control-max-age'] = String(options.maxAge)
40
+ }
41
+ return appendVary(c.body(null, 204, headers), 'Origin')
42
+ }
43
+ const response = await next()
44
+ return appendVary(setHeaders(response, shared), 'Origin')
45
+ }
46
+ }
@@ -0,0 +1,6 @@
1
+ export { bodyLimit, BODY_LIMIT_KEY, type BodyLimitOptions } from './body-limit.ts'
2
+ export { cors, type CorsOptions } from './cors.ts'
3
+ export { logger, type LogSink } from './logger.ts'
4
+ export { loopbackAuthority, loopbackOnly, sameOrigin, type LoopbackOptions } from './loopback-only.ts'
5
+ export { requestId, type RequestIdOptions } from './request-id.ts'
6
+ export { secureHeaders, type SecureHeadersOptions } from './secure-headers.ts'
@@ -0,0 +1,21 @@
1
+ import type { Middleware } from '../types.ts'
2
+
3
+ /** One line to a sink the caller owns, for example `line => ctx.logger.info(line)`. */
4
+ export type LogSink = (line: string) => void
5
+
6
+ /** Log each request on the way in and its status and time on the way out. The sink is required: a framework does not write to the console on its own. */
7
+ export function logger(sink: LogSink): Middleware {
8
+ return async (c, next) => {
9
+ const label = `${c.req.method} ${c.url.pathname}`
10
+ sink(`<-- ${label}`)
11
+ const started = performance.now()
12
+ try {
13
+ const response = await next()
14
+ sink(`--> ${label} ${String(response.status)} ${String(Math.round(performance.now() - started))}ms`)
15
+ return response
16
+ } catch (error) {
17
+ sink(`--> ${label} threw ${error instanceof Error ? error.message : String(error)} ${String(Math.round(performance.now() - started))}ms`)
18
+ throw error
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,82 @@
1
+ import { BlockList, isIP } from 'node:net'
2
+ import type { Middleware, RouteContext } from '../types.ts'
3
+
4
+ export interface LoopbackOptions {
5
+ /** Hostnames a `Host` header may name. Default: the loopback names `127.0.0.1`, `localhost` and `[::1]`. */
6
+ readonly hostnames?: readonly string[]
7
+ /**
8
+ * What a request that changes things (not GET, HEAD or OPTIONS) must show: `same-origin` (default) refuses an `Origin` header that is not this same
9
+ * authority (including `null`), which stops another web page from driving a local app. A browser always sends `Origin` on a cross-origin change, so a
10
+ * request with no `Origin` (curl, a script) is allowed: the `Host` it names is already checked to be a loopback address with this server's port, which
11
+ * is what stops DNS rebinding. `none` checks only the peer and the `Host`.
12
+ */
13
+ readonly mutations?: 'same-origin' | 'none'
14
+ /**
15
+ * A call made inside the process (the terminal UI, a test) has no socket, so no peer to check. `deny` (default) refuses it, the safe choice for a route
16
+ * that guards something; `allow` lets it through for routes whose in-process caller is the host's own code. A request that came over a socket is always
17
+ * checked in full: only a call with no connection facts at all counts as in process.
18
+ */
19
+ readonly inProcess?: 'deny' | 'allow'
20
+ }
21
+
22
+ const loopback = new BlockList()
23
+ loopback.addSubnet('127.0.0.0', 8, 'ipv4')
24
+ loopback.addSubnet('::1', 128, 'ipv6')
25
+
26
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
27
+
28
+ /**
29
+ * The authority a loopback request addressed: the `Host` header as a URL, or `undefined` when the request does not come from a loopback peer to the
30
+ * real local port, names another host, or is marked cross-site by the browser. The peer and the port come from the transport (`c.connection`), never
31
+ * from a header; an in-process call has neither and is refused.
32
+ */
33
+ export const LOOPBACK_HOSTNAMES: readonly string[] = ['127.0.0.1', 'localhost', '[::1]']
34
+
35
+ export function loopbackAuthority(c: RouteContext, hostnames: readonly string[] = LOOPBACK_HOSTNAMES): URL | undefined {
36
+ const { remoteAddress, localPort } = c.connection
37
+ const host = c.req.headers.get('host')
38
+ if (remoteAddress === undefined || localPort === undefined || host === null) return undefined
39
+ const address = (remoteAddress.replace(/^\[|\]$/gu, '').split('%', 1)[0] ?? '').replace(/^::ffff:/iu, '')
40
+ const family = isIP(address)
41
+ if (family === 0 || !loopback.check(address, family === 4 ? 'ipv4' : 'ipv6')) return undefined
42
+ let authority: URL
43
+ try {
44
+ authority = new URL(`http://${host}`)
45
+ } catch {
46
+ return undefined
47
+ }
48
+ if (
49
+ authority.protocol !== 'http:'
50
+ || Number(authority.port || '80') !== localPort
51
+ || !hostnames.includes(authority.hostname)
52
+ || c.req.headers.get('sec-fetch-site') === 'cross-site'
53
+ ) return undefined
54
+ return authority
55
+ }
56
+
57
+ /** Whether a changing request is acceptable by its `Origin`: absent (not a browser cross-origin change) or naming this same authority. `null` and any other origin are not. */
58
+ export function sameOrigin(c: RouteContext, authority: URL): boolean {
59
+ const origin = c.req.headers.get('origin')
60
+ if (origin === null) return true
61
+ try {
62
+ const parsed = new URL(origin)
63
+ return parsed.protocol === 'http:' && parsed.host === authority.host && parsed.pathname === '/'
64
+ } catch {
65
+ return false
66
+ }
67
+ }
68
+
69
+ /** Only requests from this machine to this app: loopback peer, the real port, an allowed `Host`, and for mutations a matching `Origin`. Everything else gets a 403. */
70
+ export function loopbackOnly(options: LoopbackOptions = {}): Middleware {
71
+ const mutations = options.mutations ?? 'same-origin'
72
+ const inProcess = options.inProcess ?? 'deny'
73
+ return async (c, next) => {
74
+ if (inProcess === 'allow' && c.connection.remoteAddress === undefined && c.connection.localPort === undefined) return next()
75
+ const authority = loopbackAuthority(c, options.hostnames)
76
+ if (authority === undefined) return c.json({ error: 'request authority rejected' }, 403)
77
+ if (mutations === 'same-origin' && !SAFE_METHODS.has(c.req.method) && !sameOrigin(c, authority)) {
78
+ return c.json({ error: 'a change must come from this app\'s own origin' }, 403)
79
+ }
80
+ return next()
81
+ }
82
+ }
@@ -0,0 +1,24 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { Middleware } from '../types.ts'
3
+ import { setHeaders } from '../util.ts'
4
+
5
+ export interface RequestIdOptions {
6
+ /** The header read from the request and written to the response. */
7
+ readonly header?: string
8
+ /** Makes an id when the request brought none. */
9
+ readonly generate?: () => string
10
+ }
11
+
12
+ const SAFE_ID = /^[\w\-=]{1,255}$/u
13
+
14
+ /** Give every request an id: the caller's, when it is well formed, otherwise a new one. It is `c.get('requestId')` and the response header. */
15
+ export function requestId(options: RequestIdOptions = {}): Middleware {
16
+ const header = options.header ?? 'x-request-id'
17
+ const generate = options.generate ?? randomUUID
18
+ return async (c, next) => {
19
+ const incoming = c.req.headers.get(header)
20
+ const id = incoming !== null && SAFE_ID.test(incoming) ? incoming : generate()
21
+ c.set('requestId', id)
22
+ return setHeaders(await next(), { [header]: id })
23
+ }
24
+ }
@@ -0,0 +1,23 @@
1
+ import type { Middleware } from '../types.ts'
2
+ import { setHeaders } from '../util.ts'
3
+
4
+ export interface SecureHeadersOptions {
5
+ /** Extra or replacement headers, merged over the defaults. A value of `''` removes a default. */
6
+ readonly headers?: Readonly<Record<string, string>>
7
+ }
8
+
9
+ const DEFAULTS: Record<string, string> = {
10
+ 'x-content-type-options': 'nosniff',
11
+ 'x-frame-options': 'SAMEORIGIN',
12
+ 'referrer-policy': 'no-referrer',
13
+ 'cross-origin-resource-policy': 'same-origin',
14
+ }
15
+
16
+ /** Add the standard hardening headers to every response (never overriding one the handler already set). */
17
+ export function secureHeaders(options: SecureHeadersOptions = {}): Middleware {
18
+ const wanted = Object.entries({ ...DEFAULTS, ...options.headers }).filter(([, value]) => value !== '')
19
+ return async (_c, next) => {
20
+ const response = await next()
21
+ return setHeaders(response, Object.fromEntries(wanted.filter(([name]) => !response.headers.has(name))))
22
+ }
23
+ }
@@ -0,0 +1,89 @@
1
+ import type { TrailingSlash } from './types.ts'
2
+
3
+ /** One piece of a route path. */
4
+ export type Segment =
5
+ | { readonly kind: 'static', readonly value: string }
6
+ | { readonly kind: 'param', readonly name: string }
7
+ | { readonly kind: 'wildcard' }
8
+
9
+ export interface Pattern {
10
+ /** The path as written (normalized for the trailing-slash rule). */
11
+ readonly source: string
12
+ readonly segments: readonly Segment[]
13
+ }
14
+
15
+ /** Split a pathname into segments. `/` is the empty list; under `strict` a trailing slash leaves a final empty segment. */
16
+ export function splitPath(path: string, trailingSlash: TrailingSlash): string[] {
17
+ let value = path
18
+ if (trailingSlash === 'ignore' && value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)
19
+ if (value === '/' || value === '') return []
20
+ return value.slice(1).split('/')
21
+ }
22
+
23
+ /** Compile `/a/:id/*`. A `*` is allowed only as the last segment; param names must be non-empty and unique. */
24
+ export function compilePattern(path: string, trailingSlash: TrailingSlash): Pattern {
25
+ if (!path.startsWith('/')) throw new TypeError(`router: path "${path}" must start with "/"`)
26
+ const parts = splitPath(path, trailingSlash)
27
+ const names = new Set<string>()
28
+ const segments: Segment[] = parts.map((part, index) => {
29
+ if (part === '*') {
30
+ if (index !== parts.length - 1) throw new TypeError(`router: "*" must be the last segment in "${path}"`)
31
+ return { kind: 'wildcard' }
32
+ }
33
+ if (part.startsWith(':')) {
34
+ const name = part.slice(1)
35
+ if (name === '') throw new TypeError(`router: empty parameter name in "${path}"`)
36
+ if (names.has(name)) throw new TypeError(`router: duplicate parameter ":${name}" in "${path}"`)
37
+ names.add(name)
38
+ return { kind: 'param', name }
39
+ }
40
+ return { kind: 'static', value: part }
41
+ })
42
+ return { source: path, segments }
43
+ }
44
+
45
+ /** The same path with every parameter name erased, so `/a/:id` and `/a/:name` collide as duplicates. */
46
+ export function shapeOf(pattern: Pattern): string {
47
+ return '/' + pattern.segments.map(s => s.kind === 'static' ? s.value : s.kind === 'param' ? ':' : '*').join('/')
48
+ }
49
+
50
+ function decode(value: string): string {
51
+ try { return decodeURIComponent(value) } catch { return value }
52
+ }
53
+
54
+ /** Match concrete path segments against a pattern; returns the parameters, or `undefined` when it does not match. */
55
+ export function matchPattern(pattern: Pattern, parts: readonly string[]): Record<string, string> | undefined {
56
+ const params: Record<string, string> = {}
57
+ const { segments } = pattern
58
+ for (let i = 0; i < segments.length; i++) {
59
+ const segment = segments[i]
60
+ if (segment === undefined) return undefined
61
+ if (segment.kind === 'wildcard') {
62
+ params['*'] = parts.slice(i).map(decode).join('/')
63
+ return params
64
+ }
65
+ const part = parts[i]
66
+ if (part === undefined) return undefined
67
+ if (segment.kind === 'static') {
68
+ if (segment.value !== part) return undefined
69
+ } else {
70
+ params[segment.name] = decode(part)
71
+ }
72
+ }
73
+ return parts.length === segments.length ? params : undefined
74
+ }
75
+
76
+ const SCORE = { static: 3, param: 2, wildcard: 1 } as const
77
+
78
+ /** Compare two matching patterns: the more specific one (static before param before wildcard, left to right) wins. */
79
+ export function compareSpecificity(a: Pattern, b: Pattern): number {
80
+ const length = Math.max(a.segments.length, b.segments.length)
81
+ for (let i = 0; i < length; i++) {
82
+ const left = a.segments[i]
83
+ const right = b.segments[i]
84
+ const l = left === undefined ? 0 : SCORE[left.kind]
85
+ const r = right === undefined ? 0 : SCORE[right.kind]
86
+ if (l !== r) return l - r
87
+ }
88
+ return 0
89
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The registration API every router scope shares (`get`, `use`, `group`): the router itself is one scope with an empty prefix, and
3
+ * `router.group('/api')` is another with a prefix. A scope never owns anything; every registration is released by the plugin that made it.
4
+ */
5
+
6
+ import type { Context } from '@deepseek-ai/cordis'
7
+ import { compose } from './compose.ts'
8
+ import type { Handler, Method, Middleware, RouteMethod } from './types.ts'
9
+
10
+ /** The last argument is the handler; everything before it is middleware that runs for this route only. */
11
+ export type RouteHandlers = readonly [...Middleware[], Handler]
12
+
13
+ export type UseArguments = readonly [Middleware, ...Middleware[]] | readonly [string, Middleware, ...Middleware[]]
14
+
15
+ export interface Registrar {
16
+ /** Register a route owned by the calling plugin. Returns a remover; the route also goes away when the caller unloads. */
17
+ route(method: RouteMethod, path: string, ...handlers: RouteHandlers): () => void
18
+ get(path: string, ...handlers: RouteHandlers): () => void
19
+ post(path: string, ...handlers: RouteHandlers): () => void
20
+ put(path: string, ...handlers: RouteHandlers): () => void
21
+ patch(path: string, ...handlers: RouteHandlers): () => void
22
+ delete(path: string, ...handlers: RouteHandlers): () => void
23
+ /** A route that answers every method no more specific route claims. */
24
+ all(path: string, ...handlers: RouteHandlers): () => void
25
+ /** The same handlers on several methods. Returns one remover for all of them. */
26
+ on(methods: Method | readonly Method[], path: string, ...handlers: RouteHandlers): () => void
27
+ /** Middleware for a path and everything below it (default: everything in this scope), in registration order. */
28
+ use(...args: UseArguments): () => void
29
+ /** A scope whose paths all start with `prefix`; optional middleware runs for everything under it. */
30
+ group(prefix: string, ...middleware: Middleware[]): Registrar
31
+ }
32
+
33
+ /** What a scope needs from the router: put one route or one middleware into the table, owned by `owner`. */
34
+ export interface Primitives {
35
+ add(owner: Context, method: RouteMethod, path: string, handler: Handler): () => void
36
+ use(owner: Context, path: string, middleware: Middleware): () => void
37
+ }
38
+
39
+ const PREFIX = /^\/(?:[^/*:\s]+(?:\/[^/*:\s]+)*)?$/
40
+
41
+ /** Join a scope prefix and a path: `('/api', '/x')` is `/api/x`, `('/api', '/')` is `/api`, and an empty prefix leaves the path alone. */
42
+ export function joinPath(prefix: string, path: string): string {
43
+ if (prefix === '') return path
44
+ if (path === '/' || path === '') return prefix
45
+ if (!path.startsWith('/')) throw new TypeError(`router: path "${path}" must start with "/"`)
46
+ return `${prefix}${path}`
47
+ }
48
+
49
+ function validatePrefix(prefix: string): void {
50
+ if (prefix !== '' && !PREFIX.test(prefix)) throw new TypeError(`router: group prefix "${prefix}" must be a plain path like "/api" (no wildcard, no parameter, no trailing slash)`)
51
+ }
52
+
53
+ function single(handlers: RouteHandlers): Handler {
54
+ const last = handlers.at(-1)
55
+ if (last === undefined) throw new TypeError('router: a route needs a handler')
56
+ const middleware = handlers.slice(0, -1) as Middleware[]
57
+ return middleware.length === 0 ? last as Handler : compose(middleware, last as Handler)
58
+ }
59
+
60
+ export function createRegistrar(owner: Context, prefix: string, primitives: Primitives): Registrar {
61
+ validatePrefix(prefix)
62
+ const route = (method: RouteMethod, path: string, ...handlers: RouteHandlers): (() => void) =>
63
+ primitives.add(owner, method, joinPath(prefix, path), single(handlers))
64
+ const registrar: Registrar = {
65
+ route,
66
+ get: (path, ...h) => route('GET', path, ...h),
67
+ post: (path, ...h) => route('POST', path, ...h),
68
+ put: (path, ...h) => route('PUT', path, ...h),
69
+ patch: (path, ...h) => route('PATCH', path, ...h),
70
+ delete: (path, ...h) => route('DELETE', path, ...h),
71
+ all: (path, ...h) => route('*', path, ...h),
72
+ on: (methods, path, ...h) => {
73
+ const removers = (Array.isArray(methods) ? methods as readonly Method[] : [methods as Method]).map(method => route(method, path, ...h))
74
+ return () => { for (const remove of removers) remove() }
75
+ },
76
+ use: (...args) => {
77
+ const [first, ...rest] = args as readonly [string | Middleware, ...Middleware[]]
78
+ const path = typeof first === 'string' ? first : '/'
79
+ const middleware = typeof first === 'string' ? rest : [first, ...rest]
80
+ const removers = middleware.map(mw => primitives.use(owner, joinPath(prefix, path), mw))
81
+ return () => { for (const remove of removers) remove() }
82
+ },
83
+ group: (nested, ...middleware) => {
84
+ const scope = createRegistrar(owner, joinPath(prefix, nested), primitives)
85
+ if (middleware.length > 0) scope.use(...(middleware as [Middleware, ...Middleware[]]))
86
+ return scope
87
+ },
88
+ }
89
+ return registrar
90
+ }