@surfishs/dsh-prompt-enhance 0.1.4 → 0.1.6
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/README.en.md +11 -3
- package/README.md +19 -7
- package/docs/images/enhance-button.png +0 -0
- package/docs/images/quick-settings-en.png +0 -0
- package/docs/images/quick-settings.png +0 -0
- package/lib/client.js +9 -7
- package/lib/index.js +63 -19
- package/lib/index.js.map +3 -3
- package/package.json +1 -1
- package/src/catalog-route.ts +7 -3
- package/src/client/locales.ts +2 -2
- package/src/client/shortcut.ts +26 -10
- package/src/config.ts +1 -1
- package/src/enhance-routes.ts +12 -12
- package/src/http.ts +24 -0
- package/src/loopback.ts +36 -17
- package/src/reasoning-route.ts +7 -3
- package/src/trust.ts +62 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@surfishs/dsh-prompt-enhance",
|
|
3
3
|
"description": "Prompt enhancement for the dsh web GUI: rewrite the composer draft into a well-structured prompt through the harness LLM service, preview the before/after, then fill back, copy, or undo. Original draft is always preserved.",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.6",
|
|
5
5
|
"author": "surfishs",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"engines": {
|
package/src/catalog-route.ts
CHANGED
|
@@ -10,7 +10,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
|
10
10
|
import type { Context } from '@deepseek-ai/cordis'
|
|
11
11
|
import { LLM_MODELS_ENDPOINT, LLM_PROVIDERS_ENDPOINT, LLM_ROUTE_CHECK_ENDPOINT } from './shared/catalog'
|
|
12
12
|
import { checkRoute, listModelCatalog, listProviderCatalog } from './provider-catalog'
|
|
13
|
-
import {
|
|
13
|
+
import { trustRejection } from './trust'
|
|
14
14
|
import { writeJson } from './http'
|
|
15
15
|
|
|
16
16
|
/** Read one required query parameter, treating whitespace as absent. */
|
|
@@ -27,8 +27,12 @@ function requiredParam(url: URL, name: string): string | undefined {
|
|
|
27
27
|
* @param pathname - the already-parsed request path.
|
|
28
28
|
*/
|
|
29
29
|
export async function serveCatalog(ctx: Context, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
const rejection = trustRejection(ctx, req)
|
|
31
|
+
if (rejection !== undefined) {
|
|
32
|
+
writeJson(res, rejection, {
|
|
33
|
+
ok: false,
|
|
34
|
+
error: { code: 'internal', message: rejection === 401 ? 'unauthorized' : 'forbidden: loopback-only' },
|
|
35
|
+
})
|
|
32
36
|
return
|
|
33
37
|
}
|
|
34
38
|
if (req.method !== 'GET') {
|
package/src/client/locales.ts
CHANGED
|
@@ -171,7 +171,7 @@ export const zh = {
|
|
|
171
171
|
'settings.row.rateLimitPerMinute.label': '每分钟调用上限',
|
|
172
172
|
'settings.row.rateLimitPerMinute.hint': '每分钟增强次数上限(滑动窗口);超限时提示稍后再试。默认 10。',
|
|
173
173
|
'settings.row.shortcut.label': '快捷键',
|
|
174
|
-
'settings.row.shortcut.hint': '默认留空(禁用);填写后生效,例:ctrl+alt+shift+e(须包含 ctrl/alt/meta
|
|
174
|
+
'settings.row.shortcut.hint': '默认留空(禁用);填写后生效,例:ctrl+alt+shift+e(须包含 ctrl/alt/meta 中至少一个修饰键;F13–F24 可单独使用)。',
|
|
175
175
|
'settings.row.shortcut.placeholder': '例:ctrl+alt+shift+e',
|
|
176
176
|
'settings.strategy.replace': '替换内置策略',
|
|
177
177
|
'settings.strategy.extend': '追加在内置策略后',
|
|
@@ -363,7 +363,7 @@ export const en: Record<PromptEnhanceKey, string> = {
|
|
|
363
363
|
'settings.row.rateLimitPerMinute.label': 'Calls per minute',
|
|
364
364
|
'settings.row.rateLimitPerMinute.hint': 'Successful enhancements per minute (sliding window); past the limit the request is told to retry later. Default 10.',
|
|
365
365
|
'settings.row.shortcut.label': 'Shortcut',
|
|
366
|
-
'settings.row.shortcut.hint': 'Empty by default (disabled); set it to enable, e.g. ctrl+alt+shift+e (needs at least one of ctrl/alt/meta).',
|
|
366
|
+
'settings.row.shortcut.hint': 'Empty by default (disabled); set it to enable, e.g. ctrl+alt+shift+e (needs at least one of ctrl/alt/meta; F13–F24 may be used alone).',
|
|
367
367
|
'settings.row.shortcut.placeholder': 'e.g. ctrl+alt+shift+e',
|
|
368
368
|
'settings.strategy.replace': 'Replace the built-in strategy',
|
|
369
369
|
'settings.strategy.extend': 'Append after the built-in strategy',
|
package/src/client/shortcut.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface ShortcutCombo {
|
|
|
16
16
|
readonly alt: boolean
|
|
17
17
|
readonly shift: boolean
|
|
18
18
|
readonly meta: boolean
|
|
19
|
-
/** Final key: a single letter a-z, digit 0-9, or f1-
|
|
19
|
+
/** Final key: a single letter a-z, digit 0-9, or f1-f24. */
|
|
20
20
|
readonly key: string
|
|
21
21
|
/** Layout-independent DOM code for the key (`KeyA`, `Digit1`, `F9`). */
|
|
22
22
|
readonly code: string
|
|
@@ -36,8 +36,20 @@ const MODIFIER_ALIASES: ReadonlyMap<string, keyof Omit<ShortcutCombo, 'key' | 'c
|
|
|
36
36
|
['super', 'meta'],
|
|
37
37
|
])
|
|
38
38
|
|
|
39
|
-
/** Function
|
|
40
|
-
const
|
|
39
|
+
/** Function keys f1-f24; everything else must be one alphanumeric character. */
|
|
40
|
+
const FUNCTION_KEY_TOKEN = /^f([1-9]|1[0-9]|2[0-4])$/
|
|
41
|
+
const isKeyToken = (token: string): boolean => /^[a-z0-9]$/.test(token) || FUNCTION_KEY_TOKEN.test(token)
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Function keys that may be bound without ctrl/alt/meta: f13-f24.
|
|
45
|
+
*
|
|
46
|
+
* A bare letter or digit would swallow ordinary typing, and f1-f12 carry
|
|
47
|
+
* browser/OS defaults (refresh, fullscreen, devtools), so both still require a
|
|
48
|
+
* modifier. f13-f24 have no default action and no physical key on an ordinary
|
|
49
|
+
* keyboard — they reach the page from macro pads and remappers — so requiring a
|
|
50
|
+
* modifier there would only make the natural binding impossible.
|
|
51
|
+
*/
|
|
52
|
+
const isBareFunctionKey = (token: string): boolean => /^f(1[3-9]|2[0-4])$/.test(token)
|
|
41
53
|
|
|
42
54
|
/** The DOM `event.code` for a key token (physical, layout-independent). */
|
|
43
55
|
function codeFor(token: string): string {
|
|
@@ -53,8 +65,9 @@ type ModifierFlags = Record<'ctrl' | 'alt' | 'shift' | 'meta', boolean>
|
|
|
53
65
|
* Parse a user-configured shortcut spec. Whitespace and case are free; the
|
|
54
66
|
* key token must come last. At least one of ctrl / alt / meta is REQUIRED —
|
|
55
67
|
* a shift-only combo fires while the user is simply typing a capital
|
|
56
|
-
* letter, and a bare key would swallow that character everywhere.
|
|
57
|
-
*
|
|
68
|
+
* letter, and a bare key would swallow that character everywhere. f13-f24
|
|
69
|
+
* are the exception: they may stand alone (see {@link isBareFunctionKey}).
|
|
70
|
+
* Empty spec parses to null (shortcut disabled).
|
|
58
71
|
* @param spec - the raw settings string.
|
|
59
72
|
* @returns the normalized combo, or null when the spec is unusable.
|
|
60
73
|
*/
|
|
@@ -75,7 +88,7 @@ export function parseShortcut(spec: string | undefined): ShortcutCombo | null {
|
|
|
75
88
|
if (modifier === undefined) return null
|
|
76
89
|
modifiers[modifier] = true
|
|
77
90
|
}
|
|
78
|
-
if (!modifiers.ctrl && !modifiers.alt && !modifiers.meta) return null
|
|
91
|
+
if (!modifiers.ctrl && !modifiers.alt && !modifiers.meta && !isBareFunctionKey(last)) return null
|
|
79
92
|
return { ...modifiers, key: last, code: codeFor(last) }
|
|
80
93
|
}
|
|
81
94
|
|
|
@@ -111,7 +124,7 @@ function keyTokenOf(event: ShortcutKeyEvent): string | null {
|
|
|
111
124
|
if (letter !== undefined) return letter.toLowerCase()
|
|
112
125
|
const digit = /^Digit([0-9])$/.exec(event.code)?.[1]
|
|
113
126
|
if (digit !== undefined) return digit
|
|
114
|
-
const fn = /^F([1-9]|1[0-2])$/.exec(event.code)?.[1]
|
|
127
|
+
const fn = /^F([1-9]|1[0-9]|2[0-4])$/.exec(event.code)?.[1]
|
|
115
128
|
if (fn !== undefined) return `f${fn}`
|
|
116
129
|
const byKey = event.key.toLowerCase()
|
|
117
130
|
return isKeyToken(byKey) ? byKey : null
|
|
@@ -122,15 +135,18 @@ function keyTokenOf(event: ShortcutKeyEvent): string | null {
|
|
|
122
135
|
*
|
|
123
136
|
* Returns null — meaning "this press cannot be a shortcut" — when neither
|
|
124
137
|
* ctrl / alt / meta is held (a bare key or shift+letter would swallow ordinary
|
|
125
|
-
* typing
|
|
126
|
-
*
|
|
138
|
+
* typing; f13-f24 are the exception, see {@link isBareFunctionKey}), or when
|
|
139
|
+
* the key falls outside the a-z / 0-9 / f1-f24 whitelist the parser accepts
|
|
140
|
+
* (Space, Tab, arrows …).
|
|
127
141
|
* @param event - the recorded key press.
|
|
128
142
|
* @returns the spec string, or null.
|
|
129
143
|
*/
|
|
130
144
|
export function shortcutSpecOf(event: ShortcutKeyEvent): string | null {
|
|
131
|
-
if (!event.ctrlKey && !event.altKey && !event.metaKey) return null
|
|
132
145
|
const token = keyTokenOf(event)
|
|
133
146
|
if (token === null) return null
|
|
147
|
+
// A bare f13-f24 is allowed; every other key needs ctrl / alt / meta so
|
|
148
|
+
// ordinary typing and the browser's own function-key actions stay untouched.
|
|
149
|
+
if (!event.ctrlKey && !event.altKey && !event.metaKey && !isBareFunctionKey(token)) return null
|
|
134
150
|
const parts: string[] = []
|
|
135
151
|
if (event.ctrlKey) parts.push('ctrl')
|
|
136
152
|
if (event.altKey) parts.push('alt')
|
package/src/config.ts
CHANGED
|
@@ -170,7 +170,7 @@ export const Config = z.object({
|
|
|
170
170
|
shortcut: z
|
|
171
171
|
.string()
|
|
172
172
|
.default(DEFAULT_CONFIG.shortcut)
|
|
173
|
-
.description('触发快捷键,默认留空即禁用;如需启用,填如 ctrl+alt+e(须包含 ctrl/alt/meta 中至少一个修饰键,shift 仅可作附加,纯字母/数字或 shift
|
|
173
|
+
.description('触发快捷键,默认留空即禁用;如需启用,填如 ctrl+alt+e(须包含 ctrl/alt/meta 中至少一个修饰键,shift 仅可作附加,纯字母/数字或 shift+字母会被忽略;F13–F24 可单独使用)')
|
|
174
174
|
.volatile(),
|
|
175
175
|
maxConcurrent: z
|
|
176
176
|
.number()
|
package/src/enhance-routes.ts
CHANGED
|
@@ -16,8 +16,8 @@ import { checkInputText } from './shared/validate'
|
|
|
16
16
|
import { type Config } from './config'
|
|
17
17
|
import { toEnhanceError } from './enhancer'
|
|
18
18
|
import { runEnhance, sessionRouteOf } from './orchestrate'
|
|
19
|
-
import {
|
|
20
|
-
import { BodyTooLargeError, readBoundedJson, writeJson, endResponse } from './http'
|
|
19
|
+
import { trustRejection } from './trust'
|
|
20
|
+
import { BodyTooLargeError, UnsupportedMediaTypeError, readBoundedJson, writeJson, endResponse } from './http'
|
|
21
21
|
import { REASONING_EFFORTS_ENDPOINT } from './shared/reasoning'
|
|
22
22
|
import { serveReasoningEfforts } from './reasoning-route'
|
|
23
23
|
import { LLM_MODELS_ENDPOINT, LLM_PROVIDERS_ENDPOINT, LLM_ROUTE_CHECK_ENDPOINT } from './shared/catalog'
|
|
@@ -58,8 +58,12 @@ function attachmentCountOf(value: unknown): number | undefined {
|
|
|
58
58
|
* only the response shape differs.
|
|
59
59
|
*/
|
|
60
60
|
async function serveEnhance(ctx: Context, readConfig: () => Config, gate: AdmissionGate, pathname: string, req: IncomingMessage, res: ServerResponse, stream: boolean): Promise<void> {
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
const rejection = trustRejection(ctx, req)
|
|
62
|
+
if (rejection !== undefined) {
|
|
63
|
+
writeJson(res, rejection, {
|
|
64
|
+
ok: false,
|
|
65
|
+
error: { code: 'internal', message: rejection === 401 ? 'unauthorized' : 'forbidden: loopback-only' },
|
|
66
|
+
})
|
|
63
67
|
return
|
|
64
68
|
}
|
|
65
69
|
// One route, two exact endpoints (one-shot JSON / incremental SSE):
|
|
@@ -72,11 +76,6 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
|
|
|
72
76
|
writeJson(res, 405, { ok: false, error: { code: 'internal', message: 'only POST is allowed' } })
|
|
73
77
|
return
|
|
74
78
|
}
|
|
75
|
-
const contentType = req.headers['content-type']
|
|
76
|
-
if (contentType !== undefined && !String(contentType).toLowerCase().startsWith('application/json')) {
|
|
77
|
-
writeJson(res, 415, { ok: false, error: { code: 'rejected', message: '仅支持 application/json 请求体。' } })
|
|
78
|
-
return
|
|
79
|
-
}
|
|
80
79
|
let config: Config
|
|
81
80
|
try {
|
|
82
81
|
config = readConfig()
|
|
@@ -114,16 +113,17 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
|
|
|
114
113
|
body = await readBoundedJson(req, cap)
|
|
115
114
|
} catch (error) {
|
|
116
115
|
const tooLarge = error instanceof BodyTooLargeError
|
|
116
|
+
const badType = error instanceof UnsupportedMediaTypeError
|
|
117
117
|
// The overflow case left the body unread, so this connection can never carry
|
|
118
118
|
// another request — and measured on node v24.21.0, Node keeps it open with
|
|
119
119
|
// no FIN unless the response says otherwise. Declare it non-reusable exactly
|
|
120
120
|
// like the declared-length fast reject above: the 413 still has to travel,
|
|
121
121
|
// but the socket must not linger after it.
|
|
122
|
-
// Only the 413 closes: the 422
|
|
122
|
+
// Only the 413 closes: the 415/422 paths consumed nothing, so they stay reusable.
|
|
123
123
|
if (tooLarge) res.setHeader('connection', 'close')
|
|
124
|
-
writeJson(res, tooLarge ? 413 : 422, {
|
|
124
|
+
writeJson(res, badType ? 415 : tooLarge ? 413 : 422, {
|
|
125
125
|
ok: false,
|
|
126
|
-
error: { code: 'rejected', message: tooLarge ? '请求体超过大小上限。' : '请求体不是有效的 JSON。' },
|
|
126
|
+
error: { code: 'rejected', message: badType ? '仅支持 application/json 请求体。' : tooLarge ? '请求体超过大小上限。' : '请求体不是有效的 JSON。' },
|
|
127
127
|
})
|
|
128
128
|
return
|
|
129
129
|
}
|
package/src/http.ts
CHANGED
|
@@ -38,6 +38,24 @@ export class BodyTooLargeError extends Error {
|
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
/**
|
|
42
|
+
* The request body was not declared as JSON.
|
|
43
|
+
*
|
|
44
|
+
* A class rather than a status constant: the route maps this one to 415, and
|
|
45
|
+
* every other read/parse failure to 422. Missing `Content-Type` counts as a
|
|
46
|
+
* mismatch, not an omission — a browser form POST is exactly the request that
|
|
47
|
+
* omits the JSON type while still carrying a body.
|
|
48
|
+
*/
|
|
49
|
+
export class UnsupportedMediaTypeError extends Error {
|
|
50
|
+
/** Stable discriminant for `instanceof`-free checks across realms. */
|
|
51
|
+
readonly code = 'unsupported-media-type'
|
|
52
|
+
|
|
53
|
+
constructor() {
|
|
54
|
+
super('unsupported media type')
|
|
55
|
+
this.name = 'UnsupportedMediaTypeError'
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
41
59
|
/**
|
|
42
60
|
* Read a JSON request body, refusing anything past `maxBytes`.
|
|
43
61
|
* @param req - the incoming request.
|
|
@@ -46,6 +64,12 @@ export class BodyTooLargeError extends Error {
|
|
|
46
64
|
* @throws {@link BodyTooLargeError} past the cap, or the JSON.parse error otherwise.
|
|
47
65
|
*/
|
|
48
66
|
export async function readBoundedJson(req: IncomingMessage, maxBytes: number): Promise<unknown> {
|
|
67
|
+
// JSON only, declared or not: a request without the header is a form or a
|
|
68
|
+
// raw client, and both are shapes this route does not serve.
|
|
69
|
+
const contentType = req.headers['content-type']
|
|
70
|
+
if (typeof contentType !== 'string' || !/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json\b/i.test(contentType.trim())) {
|
|
71
|
+
throw new UnsupportedMediaTypeError()
|
|
72
|
+
}
|
|
49
73
|
const chunks: Buffer[] = []
|
|
50
74
|
let size = 0
|
|
51
75
|
for await (const chunk of req) {
|
package/src/loopback.ts
CHANGED
|
@@ -76,27 +76,46 @@ function isTrustedOrigin(origin: string, expectedPort: string | null): boolean {
|
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
/** Methods whose browser form must carry an `Origin`. */
|
|
80
|
+
const MUTATING_METHODS: ReadonlySet<string> = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
81
|
+
|
|
79
82
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
* trust model does not cover. A browser-supplied `Origin` must be a same-app
|
|
89
|
-
* local page on the very port this request was addressed to — this defeats
|
|
90
|
-
* cross-site fire-and-forget POSTs, which always carry an `Origin` that will
|
|
91
|
-
* not be trusted, and also shuts out pages served by other local servers.
|
|
83
|
+
* Structural half of the fence: the socket must be loopback, the Host header
|
|
84
|
+
* must name a loopback host, and no proxy-forwarding headers may be present.
|
|
85
|
+
*
|
|
86
|
+
* This is the half that applies even when the host's own Connection gate has
|
|
87
|
+
* already approved the request: it costs nothing and it keeps the route off a
|
|
88
|
+
* non-loopback interface. The browser-shaped checks live in
|
|
89
|
+
* {@link isTrustedRequest}, because a desktop shell's bridged fetch carries no
|
|
90
|
+
* Origin and no `Sec-Fetch-*` at all.
|
|
92
91
|
*/
|
|
93
|
-
export function
|
|
92
|
+
export function isTrustedTransport(req: IncomingMessage): boolean {
|
|
94
93
|
if (req.headers['x-forwarded-for'] !== undefined || req.headers.forwarded !== undefined) return false
|
|
95
94
|
if (!isLoopbackRequest(req)) return false
|
|
96
95
|
const host = req.headers.host
|
|
97
|
-
if (typeof host !== 'string' || host.trim() === '') return
|
|
98
|
-
|
|
96
|
+
if (typeof host !== 'string' || host.trim() === '') return false
|
|
97
|
+
return TRUSTED_HOSTNAMES.has(hostnameOf(host))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Full fence for hosts without a Connection service: the structural checks
|
|
102
|
+
* plus the browser-shaped default-deny rules.
|
|
103
|
+
*
|
|
104
|
+
* A request that declares `Sec-Fetch-Site: cross-site` is refused, and a
|
|
105
|
+
* non-GET request without an `Origin` is refused (browsers send one for every
|
|
106
|
+
* non-GET request, so its absence marks a non-browser caller that skipped the
|
|
107
|
+
* header). GET/HEAD may omit `Origin`: a browser image/script load does, and
|
|
108
|
+
* those routes are read-only.
|
|
109
|
+
*/
|
|
110
|
+
export function isTrustedRequest(req: IncomingMessage): boolean {
|
|
111
|
+
if (!isTrustedTransport(req)) return false
|
|
112
|
+
// Declared cross-site is refused even when a Host/Origin pair would pass:
|
|
113
|
+
// `Sec-Fetch-Site` is the browser's own statement about the initiator.
|
|
114
|
+
const site = req.headers['sec-fetch-site']
|
|
115
|
+
if (typeof site === 'string' && site.trim().toLowerCase() === 'cross-site') return false
|
|
116
|
+
const host = req.headers.host as string
|
|
99
117
|
const origin = req.headers.origin
|
|
100
|
-
|
|
101
|
-
return
|
|
118
|
+
const method = (req.method ?? 'GET').toUpperCase()
|
|
119
|
+
if (typeof origin !== 'string' || origin.trim() === '') return !MUTATING_METHODS.has(method)
|
|
120
|
+
return isTrustedOrigin(origin, portOf(host))
|
|
102
121
|
}
|
package/src/reasoning-route.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
|
13
13
|
import type { Context } from '@deepseek-ai/cordis'
|
|
14
14
|
import { REASONING_EFFORTS_ENDPOINT } from './shared/reasoning'
|
|
15
15
|
import { resolveReasoningCapabilities } from './reasoning-efforts'
|
|
16
|
-
import {
|
|
16
|
+
import { trustRejection } from './trust'
|
|
17
17
|
import { writeJson } from './http'
|
|
18
18
|
|
|
19
19
|
/** Read one optional query parameter, treating whitespace as absent. */
|
|
@@ -29,8 +29,12 @@ function queryParam(url: URL, name: string): string | undefined {
|
|
|
29
29
|
* @param res - the outgoing response.
|
|
30
30
|
*/
|
|
31
31
|
export async function serveReasoningEfforts(ctx: Context, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const rejection = trustRejection(ctx, req)
|
|
33
|
+
if (rejection !== undefined) {
|
|
34
|
+
writeJson(res, rejection, {
|
|
35
|
+
ok: false,
|
|
36
|
+
error: { code: 'internal', message: rejection === 401 ? 'unauthorized' : 'forbidden: loopback-only' },
|
|
37
|
+
})
|
|
34
38
|
return
|
|
35
39
|
}
|
|
36
40
|
const url = new URL(req.url ?? '/', 'http://x')
|
package/src/trust.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host trust gate shared by every route this plugin mounts.
|
|
3
|
+
*
|
|
4
|
+
* Two layers, in order:
|
|
5
|
+
*
|
|
6
|
+
* 1. `ctx.connection.requestRejection` — the host's own Host/Origin policy plus
|
|
7
|
+
* browser-session authentication, wherever the composition provides a
|
|
8
|
+
* Connection service. It is the gate the host applies to its own routes, so
|
|
9
|
+
* a plugin route that skips it is the odd one out.
|
|
10
|
+
* 2. The plugin's own loopback fence ({@link isTrustedTransport} /
|
|
11
|
+
* {@link isTrustedRequest}) — kept as the structural second gate, and as the
|
|
12
|
+
* full gate on hosts without a Connection service.
|
|
13
|
+
*
|
|
14
|
+
* Which half of the fence runs depends on whether the host gate answered:
|
|
15
|
+
*
|
|
16
|
+
* - **Host gate present and allowing** — the browser-shaped checks belong to it.
|
|
17
|
+
* A desktop shell's bridged fetch carries no `Origin` and no `Sec-Fetch-*` at
|
|
18
|
+
* all, so re-judging those headers here would reject a request the host just
|
|
19
|
+
* admitted. Only the structural half (loopback socket, loopback Host, no
|
|
20
|
+
* proxy headers) still runs.
|
|
21
|
+
* - **No Connection service** — the full fence runs, including the
|
|
22
|
+
* browser-shaped default-deny rules, because nothing else checks them.
|
|
23
|
+
* @module dsh-prompt-enhance/trust
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { IncomingMessage } from 'node:http'
|
|
27
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
28
|
+
import { isTrustedRequest, isTrustedTransport } from './loopback'
|
|
29
|
+
|
|
30
|
+
/** Statuses the host gate may answer with. */
|
|
31
|
+
export type TrustRejection = 401 | 403
|
|
32
|
+
|
|
33
|
+
/** The slice of `ctx.connection` this plugin consumes. */
|
|
34
|
+
interface ConnectionFace {
|
|
35
|
+
readonly requestRejection?: (request: { readonly headers: IncomingMessage['headers'] }) => TrustRejection | undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Warn about the fallback once per process, not once per request. */
|
|
39
|
+
let warnedFallback = false
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Decide whether one request may reach a host route.
|
|
43
|
+
* @param ctx - registrant context; `connection` is read lazily, so a host that
|
|
44
|
+
* mounts the service later is picked up without a re-apply.
|
|
45
|
+
* @param req - the incoming request.
|
|
46
|
+
* @returns 401/403 to refuse, or undefined to continue into the route.
|
|
47
|
+
*/
|
|
48
|
+
export function trustRejection(ctx: Context, req: IncomingMessage): TrustRejection | undefined {
|
|
49
|
+
const connection = ctx.get('connection' as never) as unknown as ConnectionFace | null | undefined
|
|
50
|
+
if (connection !== undefined && connection !== null && typeof connection.requestRejection === 'function') {
|
|
51
|
+
const rejection = connection.requestRejection({ headers: req.headers })
|
|
52
|
+
if (rejection !== undefined) return rejection
|
|
53
|
+
return isTrustedTransport(req) ? undefined : 403
|
|
54
|
+
}
|
|
55
|
+
if (!warnedFallback) {
|
|
56
|
+
warnedFallback = true
|
|
57
|
+
// Not console-silent: a host without Connection is a configuration the
|
|
58
|
+
// operator should be able to see in the host log, and one line is enough.
|
|
59
|
+
console.warn('[dsh-prompt-enhance] ctx.connection is unavailable; route trust falls back to the loopback fence')
|
|
60
|
+
}
|
|
61
|
+
return isTrustedRequest(req) ? undefined : 403
|
|
62
|
+
}
|