@roj-ai/standalone-server 0.1.11 → 0.1.13
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/dist/files-upload-route.d.ts +36 -0
- package/dist/files-upload-route.d.ts.map +1 -0
- package/dist/files-upload-route.js +50 -0
- package/dist/files-upload-route.js.map +1 -0
- package/dist/git-instance-fs.d.ts +60 -0
- package/dist/git-instance-fs.d.ts.map +1 -0
- package/dist/git-instance-fs.js +164 -0
- package/dist/git-instance-fs.js.map +1 -0
- package/dist/instance.d.ts +6 -0
- package/dist/instance.d.ts.map +1 -1
- package/dist/instance.js +5 -0
- package/dist/instance.js.map +1 -1
- package/dist/local-registry.d.ts +109 -0
- package/dist/local-registry.d.ts.map +1 -0
- package/dist/local-registry.js +252 -0
- package/dist/local-registry.js.map +1 -0
- package/dist/main.js +7 -1
- package/dist/main.js.map +1 -1
- package/dist/platform-api.d.ts +11 -1
- package/dist/platform-api.d.ts.map +1 -1
- package/dist/platform-api.js +176 -13
- package/dist/platform-api.js.map +1 -1
- package/dist/server.d.ts +7 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +31 -1
- package/dist/server.js.map +1 -1
- package/dist/session-file-route.d.ts +24 -0
- package/dist/session-file-route.d.ts.map +1 -0
- package/dist/session-file-route.js +72 -0
- package/dist/session-file-route.js.map +1 -0
- package/dist/signed-token.d.ts +25 -0
- package/dist/signed-token.d.ts.map +1 -0
- package/dist/signed-token.js +50 -0
- package/dist/signed-token.js.map +1 -0
- package/dist/user-config-loader.d.ts.map +1 -1
- package/dist/user-config-loader.js +37 -1
- package/dist/user-config-loader.js.map +1 -1
- package/package.json +5 -5
- package/src/files-upload-route.ts +64 -0
- package/src/git-instance-fs.ts +187 -0
- package/src/instance.ts +12 -1
- package/src/local-registry.ts +334 -0
- package/src/main.ts +7 -1
- package/src/platform-api.ts +251 -13
- package/src/server.ts +47 -2
- package/src/session-file-route.ts +99 -0
- package/src/signed-token.ts +68 -0
- package/src/user-config-loader.ts +41 -2
package/src/server.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* GET /health — health check
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import type { Config, LLMMiddleware, Logger, Preset, SessionId, SessionManager } from '@roj-ai/sdk'
|
|
15
|
+
import type { Config, LLMMiddleware, LocalResource, Logger, Preset, SessionId, SessionManager } from '@roj-ai/sdk'
|
|
16
16
|
import { bootstrap, createSystemFromServices, loadConfig, validateConfig } from '@roj-ai/sdk'
|
|
17
17
|
import { createApp } from '@roj-ai/sdk/transport/http/app'
|
|
18
18
|
import { createAgentTransport, ServerAdapter } from '@roj-ai/sdk/transport/adapter'
|
|
@@ -20,9 +20,14 @@ import { createBunPlatform } from '@roj-ai/sdk/bun-platform'
|
|
|
20
20
|
import { createBunWebSocketHandlers } from '@roj-ai/transport/bun'
|
|
21
21
|
import { Hono } from 'hono'
|
|
22
22
|
import { cors } from 'hono/cors'
|
|
23
|
+
import { createFilesUploadRoute } from './files-upload-route.js'
|
|
24
|
+
import { GitInstanceFs } from './git-instance-fs.js'
|
|
23
25
|
import { createInstance, type InstanceState } from './instance.js'
|
|
26
|
+
import { LocalRegistry } from './local-registry.js'
|
|
24
27
|
import { createPlatformApi } from './platform-api.js'
|
|
25
28
|
import { proxyPreview } from './preview-proxy.js'
|
|
29
|
+
import { createSessionFileRoute } from './session-file-route.js'
|
|
30
|
+
import { generateTokenSecret } from './signed-token.js'
|
|
26
31
|
|
|
27
32
|
export interface StartStandaloneOptions {
|
|
28
33
|
presets: Preset[]
|
|
@@ -30,6 +35,12 @@ export interface StartStandaloneOptions {
|
|
|
30
35
|
instanceId?: string
|
|
31
36
|
instanceName?: string
|
|
32
37
|
llmMiddleware?: LLMMiddleware[]
|
|
38
|
+
/**
|
|
39
|
+
* Local resource registry — files (typically ZIPs) on disk addressable by slug.
|
|
40
|
+
* Injected into new sessions via `resources.inject` whenever the preset's
|
|
41
|
+
* `defaultResourceSlugs` (or input.resourceIds) match a slug here.
|
|
42
|
+
*/
|
|
43
|
+
localResources?: LocalResource[]
|
|
33
44
|
onShutdown?: () => Promise<void> | void
|
|
34
45
|
onBeforeStart?: (ctx: { config: Config; logger: Logger }) => void | Promise<void>
|
|
35
46
|
}
|
|
@@ -87,7 +98,29 @@ export async function startStandaloneServer(options: StartStandaloneOptions): Pr
|
|
|
87
98
|
sessionRuntime: sessionManager,
|
|
88
99
|
})
|
|
89
100
|
|
|
90
|
-
const
|
|
101
|
+
const tokenSecret = generateTokenSecret()
|
|
102
|
+
const publicHost = config.host === '0.0.0.0' ? 'localhost' : config.host
|
|
103
|
+
const publicBaseUrl = `http://${publicHost}:${config.port}`
|
|
104
|
+
|
|
105
|
+
const registry = new LocalRegistry(config.dataPath, logger)
|
|
106
|
+
await registry.init()
|
|
107
|
+
if (options.localResources?.length) {
|
|
108
|
+
await registry.bootstrapLocalResources(options.localResources)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const gitFs = new GitInstanceFs(config.dataPath, logger)
|
|
112
|
+
await gitFs.initInstance(instance.id)
|
|
113
|
+
|
|
114
|
+
const platformApp = createPlatformApi({
|
|
115
|
+
instance,
|
|
116
|
+
sessionManager,
|
|
117
|
+
logger,
|
|
118
|
+
presets,
|
|
119
|
+
registry,
|
|
120
|
+
gitFs,
|
|
121
|
+
tokenSecret,
|
|
122
|
+
publicBaseUrl,
|
|
123
|
+
})
|
|
91
124
|
|
|
92
125
|
const outerApp = new Hono()
|
|
93
126
|
// Reflect the request origin and allow credentials — the SPA uses
|
|
@@ -96,6 +129,11 @@ export async function startStandaloneServer(options: StartStandaloneOptions): Pr
|
|
|
96
129
|
outerApp.use('*', cors({ origin: (origin) => origin ?? '*', credentials: true }))
|
|
97
130
|
|
|
98
131
|
outerApp.get('/health', (c) => c.json({ status: 'ok', timestamp: Date.now() }))
|
|
132
|
+
|
|
133
|
+
// Multipart file upload — must be registered BEFORE the /api/v1 RPC mount
|
|
134
|
+
// so it isn't treated as JSON RPC.
|
|
135
|
+
outerApp.post('/api/v1/files/upload', createFilesUploadRoute({ registry }))
|
|
136
|
+
|
|
99
137
|
outerApp.route('/api/v1', platformApp)
|
|
100
138
|
|
|
101
139
|
// Path-based preview proxy (must come BEFORE the catch-all instance route)
|
|
@@ -105,6 +143,13 @@ export async function startStandaloneServer(options: StartStandaloneOptions): Pr
|
|
|
105
143
|
return proxyPreview(c.req.raw, prefix, sessionManager, logger)
|
|
106
144
|
})
|
|
107
145
|
|
|
146
|
+
// Token-authenticated download URL minted by `sessionFiles.createDownloadUrl`.
|
|
147
|
+
// Must come BEFORE the agent catch-all so the token gate runs.
|
|
148
|
+
outerApp.get(
|
|
149
|
+
'/api/v1/instances/:id/sessions/:sid/files/:scope{workspace|session}/*',
|
|
150
|
+
createSessionFileRoute({ tokenSecret, agentApp, logger }),
|
|
151
|
+
)
|
|
152
|
+
|
|
108
153
|
// Noop auth-exchange (platform has real cookies; standalone is open)
|
|
109
154
|
outerApp.post('/api/v1/instances/:id/exchange', (c) => c.json({ ok: true }))
|
|
110
155
|
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token-authenticated session file download route.
|
|
3
|
+
*
|
|
4
|
+
* GET /api/v1/instances/:id/sessions/:sid/files/:scope/{path}?token=...
|
|
5
|
+
*
|
|
6
|
+
* Validates the HMAC token minted by `sessionFiles.createDownloadUrl` against
|
|
7
|
+
* the URL's (instanceId, sessionId, scope, path), then proxies to the SDK's
|
|
8
|
+
* existing `/sessions/:sid/workspace/*` or `/sessions/:sid/files/*` route on
|
|
9
|
+
* the agent app — same shape as roj-platform's `session-file-route.ts`, just
|
|
10
|
+
* served in-process.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Logger } from '@roj-ai/sdk'
|
|
14
|
+
import type { Context } from 'hono'
|
|
15
|
+
import { verifyFileToken } from './signed-token.js'
|
|
16
|
+
|
|
17
|
+
// Decoupled from Hono's exact type so the SDK's hono and standalone-server's
|
|
18
|
+
// hono — which the workspace can resolve to slightly different versions —
|
|
19
|
+
// don't fight over generics. We only need fetch.
|
|
20
|
+
interface AgentAppLike {
|
|
21
|
+
fetch: (req: Request) => Response | Promise<Response>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface Deps {
|
|
25
|
+
tokenSecret: string
|
|
26
|
+
agentApp: AgentAppLike
|
|
27
|
+
logger: Logger
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const SCOPE_TO_SDK_PREFIX: Record<'workspace' | 'session', string> = {
|
|
31
|
+
workspace: 'workspace',
|
|
32
|
+
session: 'files',
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createSessionFileRoute(deps: Deps) {
|
|
36
|
+
return async (c: Context) => {
|
|
37
|
+
const instanceId = c.req.param('id')
|
|
38
|
+
const sessionId = c.req.param('sid')
|
|
39
|
+
const scope = c.req.param('scope') as 'workspace' | 'session'
|
|
40
|
+
const url = new URL(c.req.url)
|
|
41
|
+
|
|
42
|
+
const tokenStr = url.searchParams.get('token')
|
|
43
|
+
if (!tokenStr) {
|
|
44
|
+
return c.json({ error: { type: 'unauthorized', message: 'Missing token' } }, 401)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const verified = verifyFileToken(deps.tokenSecret, tokenStr)
|
|
48
|
+
if (!verified.ok) {
|
|
49
|
+
return c.json({ error: { type: 'unauthorized', message: `Invalid token (${verified.error})` } }, 401)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Recover the file path the token was signed for. Hono `*` capture is
|
|
53
|
+
// available via the URL pathname; decode each segment back to its
|
|
54
|
+
// original form so the comparison against the signed payload is exact.
|
|
55
|
+
const pathPrefix = `/api/v1/instances/${instanceId}/sessions/${sessionId}/files/${scope}/`
|
|
56
|
+
if (!url.pathname.startsWith(pathPrefix)) {
|
|
57
|
+
return c.json({ error: { type: 'invalid_request', message: 'Path mismatch' } }, 400)
|
|
58
|
+
}
|
|
59
|
+
const requestedPath = url.pathname
|
|
60
|
+
.slice(pathPrefix.length)
|
|
61
|
+
.split('/')
|
|
62
|
+
.map(seg => decodeURIComponent(seg))
|
|
63
|
+
.join('/')
|
|
64
|
+
|
|
65
|
+
const p = verified.payload
|
|
66
|
+
if (
|
|
67
|
+
p.instanceId !== instanceId ||
|
|
68
|
+
p.sessionId !== sessionId ||
|
|
69
|
+
p.scope !== scope ||
|
|
70
|
+
p.path !== requestedPath
|
|
71
|
+
) {
|
|
72
|
+
return c.json(
|
|
73
|
+
{ error: { type: 'unauthorized', message: 'Token does not match requested file' } },
|
|
74
|
+
401,
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Proxy to the SDK's underlying file route. Note the path/scope mapping:
|
|
79
|
+
// public `workspace` → SDK `/sessions/:sid/workspace/*`,
|
|
80
|
+
// public `session` → SDK `/sessions/:sid/files/*`.
|
|
81
|
+
const sdkPrefix = SCOPE_TO_SDK_PREFIX[scope]
|
|
82
|
+
const innerUrl = `${url.origin}/sessions/${sessionId}/${sdkPrefix}/${encodePathSegments(requestedPath)}`
|
|
83
|
+
try {
|
|
84
|
+
return await deps.agentApp.fetch(new Request(innerUrl, { method: 'GET' }))
|
|
85
|
+
} catch (err) {
|
|
86
|
+
deps.logger.error('Session file proxy failed', err instanceof Error ? err : new Error(String(err)), {
|
|
87
|
+
instanceId,
|
|
88
|
+
sessionId,
|
|
89
|
+
scope,
|
|
90
|
+
path: requestedPath,
|
|
91
|
+
})
|
|
92
|
+
return c.json({ error: { type: 'proxy_error', message: 'File proxy failed' } }, 502)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function encodePathSegments(path: string): string {
|
|
98
|
+
return path.split('/').map(seg => encodeURIComponent(seg)).join('/')
|
|
99
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny HMAC-signed download token used by `sessionFiles.createDownloadUrl`.
|
|
3
|
+
*
|
|
4
|
+
* The token binds (instanceId, sessionId, scope, path, expiresAt) so a leaked
|
|
5
|
+
* URL can only fetch the exact file it was minted for, and only briefly. Same
|
|
6
|
+
* shape as roj-platform's `session-file-token.ts`, just pruned for local use.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { randomBytes, createHmac, timingSafeEqual } from 'node:crypto'
|
|
10
|
+
|
|
11
|
+
export interface SignedFilePayload {
|
|
12
|
+
instanceId: string
|
|
13
|
+
sessionId: string
|
|
14
|
+
scope: 'workspace' | 'session'
|
|
15
|
+
path: string
|
|
16
|
+
expiresAt: number
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function generateTokenSecret(): string {
|
|
20
|
+
return randomBytes(32).toString('hex')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function signFileToken(secret: string, payload: SignedFilePayload): string {
|
|
24
|
+
const body = base64UrlEncode(Buffer.from(JSON.stringify(payload), 'utf8'))
|
|
25
|
+
const sig = base64UrlEncode(hmac(secret, body))
|
|
26
|
+
return `${body}.${sig}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type VerifyResult =
|
|
30
|
+
| { ok: true; payload: SignedFilePayload }
|
|
31
|
+
| { ok: false; error: 'malformed' | 'bad_signature' | 'expired' }
|
|
32
|
+
|
|
33
|
+
export function verifyFileToken(secret: string, token: string): VerifyResult {
|
|
34
|
+
const dot = token.indexOf('.')
|
|
35
|
+
if (dot < 0) return { ok: false, error: 'malformed' }
|
|
36
|
+
const body = token.slice(0, dot)
|
|
37
|
+
const sigEncoded = token.slice(dot + 1)
|
|
38
|
+
|
|
39
|
+
const expectedSig = hmac(secret, body)
|
|
40
|
+
const givenSig = base64UrlDecode(sigEncoded)
|
|
41
|
+
if (givenSig.length !== expectedSig.length || !timingSafeEqual(givenSig, expectedSig)) {
|
|
42
|
+
return { ok: false, error: 'bad_signature' }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let payload: SignedFilePayload
|
|
46
|
+
try {
|
|
47
|
+
payload = JSON.parse(base64UrlDecode(body).toString('utf8'))
|
|
48
|
+
} catch {
|
|
49
|
+
return { ok: false, error: 'malformed' }
|
|
50
|
+
}
|
|
51
|
+
if (typeof payload.expiresAt !== 'number' || payload.expiresAt < Date.now()) {
|
|
52
|
+
return { ok: false, error: 'expired' }
|
|
53
|
+
}
|
|
54
|
+
return { ok: true, payload }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function hmac(secret: string, body: string): Buffer {
|
|
58
|
+
return createHmac('sha256', secret).update(body).digest()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function base64UrlEncode(buf: Buffer): string {
|
|
62
|
+
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function base64UrlDecode(s: string): Buffer {
|
|
66
|
+
const pad = '='.repeat((4 - (s.length % 4)) % 4)
|
|
67
|
+
return Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/') + pad, 'base64')
|
|
68
|
+
}
|
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
* runtime-specific I/O) and out of `@roj-ai/sandbox-runtime` (Bun-specific).
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import type { Preset, RojConfig } from '@roj-ai/sdk'
|
|
8
|
+
import type { LocalResource, Preset, RojConfig } from '@roj-ai/sdk'
|
|
9
9
|
import { validatePreset } from '@roj-ai/sdk'
|
|
10
10
|
import { existsSync } from 'node:fs'
|
|
11
|
-
import { resolve } from 'node:path'
|
|
11
|
+
import { dirname, isAbsolute, resolve } from 'node:path'
|
|
12
12
|
|
|
13
13
|
export async function loadUserConfig(configPath: string): Promise<RojConfig> {
|
|
14
14
|
const absolutePath = resolve(process.cwd(), configPath)
|
|
@@ -63,9 +63,48 @@ export async function loadUserConfig(configPath: string): Promise<RojConfig> {
|
|
|
63
63
|
throw new Error(`Duplicate preset IDs: ${[...new Set(duplicates)].join(', ')}`)
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
const configDir = dirname(absolutePath)
|
|
67
|
+
const localResources = parseLocalResources(typedConfig.localResources, configDir, absolutePath)
|
|
68
|
+
|
|
66
69
|
return {
|
|
67
70
|
presets,
|
|
68
71
|
sandboxed: typedConfig.sandboxed as boolean | undefined,
|
|
69
72
|
snapshotter: typedConfig.snapshotter as RojConfig['snapshotter'],
|
|
73
|
+
localResources,
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function parseLocalResources(raw: unknown, configDir: string, configPath: string): LocalResource[] | undefined {
|
|
78
|
+
if (raw === undefined) return undefined
|
|
79
|
+
if (!Array.isArray(raw)) {
|
|
80
|
+
throw new Error(`'localResources' must be an array: ${configPath}`)
|
|
70
81
|
}
|
|
82
|
+
|
|
83
|
+
const seen = new Set<string>()
|
|
84
|
+
return raw.map((entry, i) => {
|
|
85
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
86
|
+
throw new Error(`localResources[${i}] must be an object: ${configPath}`)
|
|
87
|
+
}
|
|
88
|
+
const r = entry as Record<string, unknown>
|
|
89
|
+
if (typeof r.slug !== 'string' || !r.slug) {
|
|
90
|
+
throw new Error(`localResources[${i}] missing required 'slug': ${configPath}`)
|
|
91
|
+
}
|
|
92
|
+
if (typeof r.path !== 'string' || !r.path) {
|
|
93
|
+
throw new Error(`localResources[${i}] missing required 'path': ${configPath}`)
|
|
94
|
+
}
|
|
95
|
+
if (seen.has(r.slug)) {
|
|
96
|
+
throw new Error(`Duplicate localResources slug '${r.slug}': ${configPath}`)
|
|
97
|
+
}
|
|
98
|
+
seen.add(r.slug)
|
|
99
|
+
|
|
100
|
+
const resolvedPath = isAbsolute(r.path) ? r.path : resolve(configDir, r.path)
|
|
101
|
+
if (!existsSync(resolvedPath)) {
|
|
102
|
+
throw new Error(`localResources[${i}] file not found: ${resolvedPath} (config: ${configPath})`)
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
slug: r.slug,
|
|
106
|
+
path: resolvedPath,
|
|
107
|
+
name: typeof r.name === 'string' ? r.name : undefined,
|
|
108
|
+
}
|
|
109
|
+
})
|
|
71
110
|
}
|