shared-hosting-sync 0.0.0-stage → 0.1.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 (46) hide show
  1. package/.env.example +23 -0
  2. package/CHANGELOG.md +16 -0
  3. package/LICENSE +21 -0
  4. package/PHASES.md +141 -0
  5. package/PRODUCT.md +90 -0
  6. package/README.md +407 -2
  7. package/RELEASING.md +79 -0
  8. package/package.json +68 -4
  9. package/src/arguments.js +30 -0
  10. package/src/bin.js +8 -0
  11. package/src/checksum.js +18 -0
  12. package/src/cli.js +511 -0
  13. package/src/config.js +98 -0
  14. package/src/core/db.js +61 -0
  15. package/src/core/deployment.js +22 -0
  16. package/src/core/envResolver.js +98 -0
  17. package/src/core/envSchema.js +160 -0
  18. package/src/core/migrate.js +75 -0
  19. package/src/core/migrations/001_init.sql +67 -0
  20. package/src/core/migrations/002_operation_locks.sql +9 -0
  21. package/src/core/operationLock.js +54 -0
  22. package/src/core/projects.js +261 -0
  23. package/src/core/secrets.js +75 -0
  24. package/src/core/v1Migrate.js +82 -0
  25. package/src/ignore.js +148 -0
  26. package/src/metadata.js +3 -0
  27. package/src/onboarding.js +117 -0
  28. package/src/paths.js +23 -0
  29. package/src/prompt.js +54 -0
  30. package/src/server/browse.js +46 -0
  31. package/src/server/deployments.js +209 -0
  32. package/src/server/index.js +79 -0
  33. package/src/server/local.js +23 -0
  34. package/src/server/onboarding.js +198 -0
  35. package/src/server/routes.js +307 -0
  36. package/src/server/session.js +58 -0
  37. package/src/transport/ftp.js +100 -0
  38. package/src/transport/index.js +12 -0
  39. package/src/transport/reliable.js +50 -0
  40. package/src/transport/sftp.js +99 -0
  41. package/src/ui/deployments.js +129 -0
  42. package/src/ui/index.html +17 -0
  43. package/src/ui/style.css +129 -0
  44. package/src/ui/ui.js +289 -0
  45. package/src/uploader.js +160 -0
  46. package/src/watcher.js +122 -0
package/src/paths.js ADDED
@@ -0,0 +1,23 @@
1
+ import path from 'node:path'
2
+
3
+ /** Require an explicit server destination; never infer the account root. */
4
+ export function validateRemotePath(value) {
5
+ if (typeof value !== 'string' || !value.trim()) {
6
+ throw new Error('Set DEVSYNC_REMOTE_PATH to a server folder before deploying')
7
+ }
8
+ const remote = value.replace(/\\/g, '/')
9
+ if (!remote.startsWith('/') || /[\x00-\x1f\x7f]/.test(remote) || remote.split('/').includes('..')) {
10
+ throw new Error('Remote path must be absolute and must not contain .. or control characters')
11
+ }
12
+ return path.posix.normalize(remote).replace(/\/$/, '') || '/'
13
+ }
14
+
15
+ export function relativeFile(root, file) {
16
+ const rel = path.relative(root, file)
17
+ if (!rel || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) {
18
+ throw new Error('Upload source must be a file inside the selected local folder')
19
+ }
20
+ const posix = rel.split(path.sep).join('/')
21
+ if (/[\\\x00-\x1f\x7f]/.test(posix)) throw new Error('Unsupported characters in upload path')
22
+ return posix
23
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,54 @@
1
+ import { createInterface } from 'node:readline'
2
+ import { Writable } from 'node:stream'
3
+
4
+ /** Create prompts lazily so complete configuration also works without a TTY. */
5
+ export function createPrompter(input = process.stdin, output = process.stdout) {
6
+ let rl
7
+ let muted = false
8
+ let closing
9
+ const interactive = !!input.isTTY && !!output.isTTY
10
+ const terminalOutput = new Writable({
11
+ write(chunk, encoding, callback) {
12
+ output.write(chunk, encoding, callback)
13
+ }
14
+ })
15
+ // Decide visibility when readline enqueues output. Checking inside _write
16
+ // drops an already queued prompt when the destination applies backpressure.
17
+ const enqueue = terminalOutput.write.bind(terminalOutput)
18
+ terminalOutput.write = (chunk, encoding, callback) => {
19
+ if (!muted) return enqueue(chunk, encoding, callback)
20
+ if (typeof encoding === 'function') encoding()
21
+ else callback?.()
22
+ return true
23
+ }
24
+ return {
25
+ interactive,
26
+ async ask({ key, label = key, secret = false, defaultValue }) {
27
+ if (!interactive) throw new Error(`Missing or invalid ${key}. Set it in the project .env, or run devsync setup in an interactive terminal.`)
28
+ rl ||= createInterface({ input, output: terminalOutput, terminal: true })
29
+ const suffix = defaultValue !== undefined && !secret ? ` [${defaultValue}]` : ''
30
+ try {
31
+ const value = await new Promise((resolve, reject) => {
32
+ const cancel = () => { cleanup(); reject(new Error('Setup cancelled')) }
33
+ const cleanup = () => { rl.off('close', cancel); rl.off('SIGINT', interrupt) }
34
+ const interrupt = () => { cancel(); rl.close() }
35
+ rl.once('close', cancel)
36
+ rl.once('SIGINT', interrupt)
37
+ rl.question(`${label}${suffix}: `, (answer) => { cleanup(); resolve(answer) })
38
+ muted = secret
39
+ })
40
+ return value === '' && defaultValue !== undefined ? String(defaultValue) : value
41
+ } finally {
42
+ muted = false
43
+ if (secret) terminalOutput.write('\n')
44
+ }
45
+ },
46
+ close() {
47
+ if (!closing) {
48
+ if (rl) rl.close()
49
+ closing = new Promise((resolve) => terminalOutput.end(resolve))
50
+ }
51
+ return closing
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,46 @@
1
+ // browse.js — remote directory listing for the UI's Browse button.
2
+ //
3
+ // Wraps the existing transport layer. Normalises paths to POSIX, never
4
+ // escapes the connection's root via "../", and never lets the UI reach
5
+ // outside what the user typed.
6
+
7
+ import path from 'node:path'
8
+ import { createTransport } from '../transport/index.js'
9
+
10
+ function norm(p) {
11
+ if (!p) return '/'
12
+ // Treat backslashes as separators (Windows users typing paths).
13
+ let s = p.replace(/\\/g, '/')
14
+ if (!s.startsWith('/')) s = '/' + s
15
+ // collapse ../ by tracking segments
16
+ const parts = []
17
+ for (const seg of s.split('/')) {
18
+ if (seg === '' || seg === '.') continue
19
+ if (seg === '..') { parts.pop(); continue }
20
+ parts.push(seg)
21
+ }
22
+ return '/' + parts.join('/')
23
+ }
24
+
25
+ /** List a remote directory, returning [{ name, type, path }]. */
26
+ export async function browseRemote(creds, remotePath) {
27
+ const p = norm(remotePath)
28
+ const t = await createTransport(creds, creds.transport)
29
+ try {
30
+ const entries = await t.list(p)
31
+ return entries.map((e) => ({
32
+ name: e.name,
33
+ type: e.type === 'dir' ? 'dir' : 'file',
34
+ path: joinRemote(p, e.name)
35
+ }))
36
+ } finally {
37
+ await t.close()
38
+ }
39
+ }
40
+
41
+ function joinRemote(base, name) {
42
+ const b = norm(base)
43
+ return b === '/' ? '/' + name : b + '/' + name
44
+ }
45
+
46
+ export { norm as normaliseRemotePath }
@@ -0,0 +1,209 @@
1
+ import crypto from 'node:crypto'
2
+ import { getProject, setStatus, recordSync } from '../core/projects.js'
3
+ import { resolveDeployment } from '../core/deployment.js'
4
+ import { createTransport } from '../transport/index.js'
5
+ import { buildPlan, runPlan } from '../uploader.js'
6
+ import { ProjectWatcher } from '../watcher.js'
7
+ import { acquireOperation, assertProjectIdle, projectOperation } from '../core/operationLock.js'
8
+
9
+ const fail = (message, statusCode = 400) => Object.assign(new Error(message), { statusCode })
10
+ const stamp = () => new Date().toISOString()
11
+
12
+ /** One active dashboard operation per project. Network work outlives HTTP requests. */
13
+ export class DeploymentService {
14
+ constructor({ connect = createTransport, watcherFactory = (...args) => new ProjectWatcher(...args) } = {}) {
15
+ this.connect = connect
16
+ this.watcherFactory = watcherFactory
17
+ this.records = new Map()
18
+ this.closing = false
19
+ }
20
+
21
+ isBusy(id) {
22
+ const record = this.records.get(Number(id))
23
+ return !!(record?.task || record?.watcher || record?.stopping)
24
+ }
25
+
26
+ ensureEditable(id) {
27
+ if (id && this.isBusy(id)) throw fail('Finish the current operation or stop watching before changing this project', 409)
28
+ if (id) assertProjectIdle(id)
29
+ }
30
+
31
+ activity(id) {
32
+ const project = getProject(Number(id))
33
+ if (!project) throw fail('Project not found', 404)
34
+ const record = this.records.get(project.id)
35
+ const view = record?.view || {
36
+ projectId: project.id, kind: null, state: 'idle', phase: 'idle', logs: [], plan: null,
37
+ result: null, progress: null, lastError: project.lastStatus === 'error' ? project.lastError : null
38
+ }
39
+ return structuredClone({
40
+ ...view, active: this.isBusy(project.id), externalOperation: !this.isBusy(project.id) ? projectOperation(project.id) : null,
41
+ watching: !!(record?.watcher || record?.view.kind === 'watch' && record?.task),
42
+ stopping: !!record?.stopping, lastSyncAt: project.lastSyncAt, lastUploadBytes: project.lastUploadBytes
43
+ })
44
+ }
45
+
46
+ clean(record, text) {
47
+ const password = record.context.values.DEVSYNC_PASSWORD
48
+ const value = String(text)
49
+ return (password ? value.split(password).join('[redacted]') : value).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '')
50
+ }
51
+
52
+ log(record, message, level = 'info') {
53
+ record.view.updatedAt = stamp()
54
+ record.view.logs.push({ at: stamp(), level, message: this.clean(record, message) })
55
+ if (record.view.logs.length > 100) record.view.logs.splice(0, record.view.logs.length - 100)
56
+ }
57
+
58
+ progress(record, event) {
59
+ if (!record.stopRequested) record.view.phase = event.phase === 'planning' ? 'planning' : 'uploading'
60
+ record.view.progress = {
61
+ current: event.index, total: event.total, file: this.clean(record, event.item.rel),
62
+ bytes: record.view.progress?.bytes || 0
63
+ }
64
+ record.view.updatedAt = stamp()
65
+ }
66
+
67
+ plan(record, plan) {
68
+ record.view.plan = {
69
+ considered: plan.totalFiles, uploadCount: plan.uploads.length, skippedCount: plan.skipped.length,
70
+ bytes: plan.comparedBytes,
71
+ uploads: plan.uploads.slice(0, 200).map(({ rel, remote, bytes }) => ({ rel: this.clean(record, rel), remote: this.clean(record, remote), bytes })),
72
+ skipped: plan.skipped.slice(0, 200).map(({ rel, reason, bytes }) => ({ rel: this.clean(record, rel), reason, bytes })),
73
+ excludedCount: plan.excludedCount || 0,
74
+ excluded: (plan.excluded || []).map(({ rel, reason }) => ({ rel: this.clean(record, rel), reason })),
75
+ blocked: record.context.matcher.blockedSample().map((name) => this.clean(record, name))
76
+ }
77
+ record.view.progress = { current: 0, total: plan.uploads.length, file: null, bytes: 0 }
78
+ this.log(record, `Compared ${plan.totalFiles} files: ${plan.uploads.length} to upload, ${plan.skipped.length} unchanged`)
79
+ }
80
+
81
+ fileResult(record, event) {
82
+ record.view.progress = { current: event.index + 1, total: event.total, file: this.clean(record, event.item.rel), bytes: event.bytes }
83
+ this.log(record, event.success ? `${event.dryRun ? 'Would upload' : 'Uploaded'} ${event.item.rel}` : `Failed ${event.item.rel}: ${event.error}`, event.success ? 'info' : 'error')
84
+ }
85
+
86
+ complete(record, { done, failed, bytes, dryRun }, watching = false) {
87
+ const failures = failed.slice(0, 200).map((file) => ({ rel: this.clean(record, file.rel), error: this.clean(record, file.error) }))
88
+ record.view.result = { uploaded: dryRun ? 0 : done, planned: done, failed: failures, failedCount: failed.length, bytes: dryRun ? 0 : bytes, dryRun }
89
+ record.view.lastError = failures.length ? failures.slice(0, 5).map((file) => `${file.rel}: ${file.error}`).join('; ') : null
90
+ record.view.state = failures.length ? 'error' : watching ? 'watching' : 'success'
91
+ if (!record.stopRequested) record.view.phase = watching ? 'watching' : 'complete'
92
+ setStatus(record.view.projectId, failures.length ? 'error' : watching ? 'watching' : 'idle', { error: record.view.lastError })
93
+ if (!dryRun && !failures.length) recordSync(record.view.projectId, bytes)
94
+ this.log(record, failures.length ? `${failed.length} file(s) failed; review the errors and retry` : dryRun ? `Preview complete: ${done} file(s), no uploads made` : `Completed: ${done} file(s) uploaded`, failures.length ? 'error' : 'success')
95
+ }
96
+
97
+ error(record, error) {
98
+ record.view.lastError = this.clean(record, error.message || error)
99
+ record.view.state = 'error'
100
+ record.view.phase = 'error'
101
+ setStatus(record.view.projectId, 'error', { error: record.view.lastError })
102
+ this.log(record, record.view.lastError, 'error')
103
+ }
104
+
105
+ start(id, kind, options = {}) {
106
+ if (this.closing) throw fail('The dashboard is shutting down', 503)
107
+ if (!['preview', 'deploy', 'sync', 'watch'].includes(kind)) throw fail('Unknown deployment operation')
108
+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw fail('Operation options must be an object')
109
+ if (options.dryRun !== undefined && typeof options.dryRun !== 'boolean') throw fail('dryRun must be a boolean')
110
+ if (options.mode !== undefined && !['sync', 'deploy'].includes(options.mode)) throw fail('Preview mode must be sync or deploy')
111
+ const project = getProject(Number(id))
112
+ if (!project) throw fail('Project not found', 404)
113
+ if (this.isBusy(project.id)) throw fail('This project already has an operation running. Stop watching or wait for it to finish.', 409)
114
+ const context = resolveDeployment(project, { useEnvFileEnvironment: false })
115
+ const dryRun = kind === 'preview' || context.dryRun || !!options.dryRun
116
+ const release = acquireOperation(project.id, kind, { creds: context.creds, remotePath: context.project.remotePath })
117
+ const record = {
118
+ context, release, task: null, watcher: null, transport: null, stopping: null, stopRequested: false,
119
+ view: {
120
+ projectId: project.id, operationId: crypto.randomUUID(), kind,
121
+ mode: kind === 'preview' ? options.mode || 'sync' : kind === 'deploy' ? 'deploy' : 'sync',
122
+ state: 'running', phase: 'connecting', dryRun, plan: null, result: null, progress: null,
123
+ logs: [], lastError: null, startedAt: stamp(), updatedAt: stamp(), remotePath: context.project.remotePath
124
+ }
125
+ }
126
+ this.records.set(project.id, record)
127
+ setStatus(project.id, kind === 'preview' ? 'planning' : kind === 'watch' ? 'watching' : 'syncing')
128
+ this.log(record, `Starting ${kind}${dryRun ? ' (preview only)' : ''} → ${context.project.remotePath}`)
129
+ record.task = this.execute(record).catch((error) => this.error(record, error)).finally(async () => {
130
+ if (!record.watcher && record.transport) {
131
+ try { await record.transport.close() } catch (error) { this.error(record, error) }
132
+ record.transport = null
133
+ }
134
+ record.task = null
135
+ if (!record.watcher) record.release()
136
+ })
137
+ return this.activity(project.id)
138
+ }
139
+
140
+ async execute(record) {
141
+ record.transport = await this.connect(record.context.creds, undefined, {
142
+ onRetry: ({ attempt, retries }) => this.log(record, `Connection interrupted; reconnecting (${attempt}/${retries})`, 'warning')
143
+ })
144
+ if (record.stopRequested || this.closing) return
145
+ const context = record.context
146
+ if (record.view.kind === 'watch') {
147
+ const watcher = this.watcherFactory(context.project, context.matcher, record.transport, {
148
+ dryRun: record.view.dryRun, debounceMs: context.debounceMs,
149
+ onProgress: (event) => this.progress(record, event),
150
+ onPlan: (plan) => this.plan(record, plan),
151
+ onFileResult: (event) => this.fileResult(record, event),
152
+ onEvent: (event) => {
153
+ if (event.type === 'error') this.error(record, new Error(event.message))
154
+ else if (event.type === 'retry') this.log(record, event.message, 'warning')
155
+ else if (event.type === 'change') this.log(record, event.kind === 'initial' ? 'Initial sync requested' : `${event.kind}: ${event.file}`)
156
+ },
157
+ onSettle: (result) => this.complete(record, {
158
+ done: result.planned, failed: result.failed, bytes: result.bytes, dryRun: result.dryRun
159
+ }, true)
160
+ })
161
+ record.watcher = watcher
162
+ try { watcher.start(); await watcher.ready }
163
+ catch (error) { await watcher.stop(); record.watcher = null; throw error }
164
+ if (record.stopRequested || this.closing) return
165
+ this.log(record, 'Watching started. Syncing current files, then following saves.')
166
+ watcher.queue(context.project.localPath, 'initial')
167
+ await watcher.flush()
168
+ return
169
+ }
170
+ const plan = await buildPlan(context.project, context.matcher, record.transport, {
171
+ force: record.view.mode === 'deploy', onProgress: (event) => this.progress(record, event)
172
+ })
173
+ this.plan(record, plan)
174
+ const result = await runPlan(plan, record.transport, {
175
+ dryRun: record.view.dryRun,
176
+ onProgress: (event) => this.progress(record, event), onFileResult: (event) => this.fileResult(record, event)
177
+ })
178
+ this.complete(record, { done: result.done.length, failed: result.failed, bytes: result.bytes, dryRun: record.view.dryRun })
179
+ }
180
+
181
+ stop(id) {
182
+ const record = this.records.get(Number(id))
183
+ if (!record || record.view.kind !== 'watch' || !this.isBusy(id)) throw fail('This project is not being watched', 409)
184
+ if (record.stopping) return this.activity(id)
185
+ record.stopRequested = true
186
+ record.view.state = 'stopping'
187
+ record.view.phase = 'stopping'
188
+ this.log(record, 'Stopping watching; finishing the current batch first')
189
+ record.stopping = (async () => {
190
+ if (record.watcher) await record.watcher.stop()
191
+ if (record.task) await record.task
192
+ if (record.watcher) { await record.watcher.stop(); record.watcher = null }
193
+ if (record.transport) { await record.transport.close(); record.transport = null }
194
+ record.view.state = record.view.lastError ? 'error' : 'stopped'
195
+ record.view.phase = record.view.lastError ? 'error' : 'complete'
196
+ setStatus(record.view.projectId, record.view.lastError ? 'error' : 'idle', { error: record.view.lastError })
197
+ this.log(record, 'Watching stopped', 'success')
198
+ })().catch((error) => this.error(record, error)).finally(() => { record.release(); record.stopping = null })
199
+ return this.activity(id)
200
+ }
201
+
202
+ async close() {
203
+ this.closing = true
204
+ for (const [id, record] of this.records) {
205
+ if (record.view.kind === 'watch' && this.isBusy(id)) this.stop(id)
206
+ }
207
+ await Promise.all([...this.records.values()].map((record) => record.stopping || record.task))
208
+ }
209
+ }
@@ -0,0 +1,79 @@
1
+ // Loopback dashboard and authenticated local setup API.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import http from 'node:http'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { handle } from './routes.js'
7
+ import { writeSessionToken, readSessionToken } from './session.js'
8
+ import { OnboardingService } from './onboarding.js'
9
+ import { DeploymentService } from './deployments.js'
10
+
11
+ const UI_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'ui')
12
+ const assets = new Map([
13
+ ['/', ['index.html', 'text/html']], ['/index.html', ['index.html', 'text/html']],
14
+ ['/ui.js', ['ui.js', 'application/javascript']], ['/style.css', ['style.css', 'text/css']],
15
+ ['/deployments.js', ['deployments.js', 'application/javascript']]
16
+ ])
17
+
18
+ export async function startServer({ port = 5180, host = '127.0.0.1', openBrowser = true } = {}) {
19
+ if (host !== '127.0.0.1') throw new Error('The dashboard must bind to 127.0.0.1')
20
+ if (!readSessionToken()) writeSessionToken()
21
+ const deployments = new DeploymentService()
22
+ const onboarding = new OnboardingService({ ensureEditable: (id) => deployments.ensureEditable(id) })
23
+ const server = http.createServer(async (req, res) => {
24
+ const actualPort = server.address().port
25
+ const hosts = [`127.0.0.1:${actualPort}`, `localhost:${actualPort}`]
26
+ const origins = hosts.map((value) => `http://${value}`)
27
+ if (!hosts.includes(req.headers.host) || req.headers.origin && !origins.includes(req.headers.origin) || req.headers['sec-fetch-site'] === 'cross-site') {
28
+ res.writeHead(403, { 'content-type': 'application/json' })
29
+ return res.end(JSON.stringify({ error: 'Open the dashboard using its local URL' }))
30
+ }
31
+ res.setHeader('x-content-type-options', 'nosniff')
32
+ res.setHeader('referrer-policy', 'no-referrer')
33
+ res.setHeader('cache-control', 'no-store')
34
+ res.setHeader('content-security-policy', "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
35
+ if (req.url.startsWith('/api/')) {
36
+ try { await handle(req, res, { onboarding, deployments }) }
37
+ catch {
38
+ if (!res.headersSent) {
39
+ res.writeHead(500, { 'content-type': 'application/json' })
40
+ res.end(JSON.stringify({ error: 'Could not complete that operation. Please try again.' }))
41
+ }
42
+ }
43
+ return
44
+ }
45
+ const asset = assets.get(req.url.split('?')[0])
46
+ if (!asset || req.method !== 'GET') { res.writeHead(404); return res.end('Not found') }
47
+ res.setHeader('content-type', asset[1] + '; charset=utf-8')
48
+ const stream = fs.createReadStream(path.join(UI_DIR, asset[0]))
49
+ stream.on('error', () => { if (!res.headersSent) res.writeHead(404); res.end('Not found') })
50
+ stream.pipe(res)
51
+ })
52
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve) })
53
+ const url = `http://${host}:${server.address().port}/`
54
+ let closing
55
+ const close = () => {
56
+ if (!closing) {
57
+ process.off('SIGINT', shutdown)
58
+ process.off('SIGTERM', shutdown)
59
+ closing = (async () => {
60
+ const httpClosed = new Promise((resolve) => server.close(resolve))
61
+ await deployments.close()
62
+ onboarding.clear()
63
+ await httpClosed
64
+ })()
65
+ }
66
+ return closing
67
+ }
68
+ const shutdown = async () => { await close(); process.exit(0) }
69
+ process.once('SIGINT', shutdown)
70
+ process.once('SIGTERM', shutdown)
71
+ if (openBrowser) {
72
+ try {
73
+ const { spawn } = await import('node:child_process')
74
+ const opener = process.platform === 'win32' ? `start "" "${url}"` : process.platform === 'darwin' ? `open "${url}"` : `xdg-open "${url}"`
75
+ spawn(opener, { shell: true, stdio: 'ignore', detached: true }).unref()
76
+ } catch {}
77
+ }
78
+ return { server, url, close }
79
+ }
@@ -0,0 +1,23 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import os from 'node:os'
4
+
5
+ /** Directory-only picker, independent of the folder used to launch the UI. */
6
+ export async function browseLocal(requestedPath) {
7
+ const target = requestedPath || os.homedir()
8
+ if (typeof target !== 'string' || !path.isAbsolute(target)) throw new Error('Enter an absolute local folder path')
9
+ const current = await fs.realpath(target)
10
+ if (!(await fs.stat(current)).isDirectory()) throw new Error('Select a local folder, not a file')
11
+ const entries = (await fs.readdir(current, { withFileTypes: true }))
12
+ .filter((entry) => entry.isDirectory() && !['.git', 'node_modules'].includes(entry.name))
13
+ .map((entry) => ({ name: entry.name, path: path.join(current, entry.name) }))
14
+ .sort((a, b) => a.name.localeCompare(b.name))
15
+ const roots = process.platform === 'win32'
16
+ ? (await Promise.all('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(async (letter) => {
17
+ const root = `${letter}:\\`
18
+ try { return (await fs.stat(root)).isDirectory() ? root : null } catch { return null }
19
+ }))).filter(Boolean)
20
+ : ['/']
21
+ const parent = path.dirname(current)
22
+ return { path: current, parent: parent === current ? null : parent, home: os.homedir(), roots, entries }
23
+ }
@@ -0,0 +1,198 @@
1
+ import crypto from 'node:crypto'
2
+ import { mutateProject } from '../core/operationLock.js'
3
+ import path from 'node:path'
4
+ import os from 'node:os'
5
+ import { ENV_SCHEMA, defaultsFor } from '../core/envSchema.js'
6
+ import { resolveEnv, settingError, credsFromResolved } from '../core/envResolver.js'
7
+ import { getProject, getProjectByLabel, getProjectByLocalPath, createProject, deleteProject, saveConfiguration, updateProject } from '../core/projects.js'
8
+ import { assertLocalFolder } from '../onboarding.js'
9
+ import { validateRemotePath } from '../paths.js'
10
+ import { ensureDeployignore } from '../ignore.js'
11
+ import { createTransport } from '../transport/index.js'
12
+
13
+ const connectionKeys = ['DEVSYNC_TRANSPORT', 'DEVSYNC_HOST', 'DEVSYNC_PORT', 'DEVSYNC_USERNAME', 'DEVSYNC_PASSWORD', 'DEVSYNC_PRIVATE_KEY']
14
+ const secretKeys = new Set(['DEVSYNC_PASSWORD', 'DEVSYNC_PRIVATE_KEY'])
15
+ const fail = (message, statusCode = 400) => Object.assign(new Error(message), { statusCode })
16
+
17
+ export function configurationView(resolved) {
18
+ const values = {}
19
+ const secrets = {}
20
+ const errors = {}
21
+ for (const schema of ENV_SCHEMA) {
22
+ const value = resolved.values[schema.key]
23
+ if (secretKeys.has(schema.key)) secrets[schema.key] = !!value
24
+ else values[schema.key] = value ?? ''
25
+ const error = settingError(schema.key, value, resolved.values)
26
+ if (error) errors[schema.key] = error
27
+ }
28
+ return { values, secrets, sources: { ...resolved.sources }, errors }
29
+ }
30
+
31
+ export function validateConnection(values) {
32
+ const errors = connectionKeys.map((key) => settingError(key, values[key], values)).filter(Boolean)
33
+ if (errors.length) throw fail(errors.join('; '))
34
+ }
35
+
36
+ export function safeConnectionError(error, values) {
37
+ const password = values.DEVSYNC_PASSWORD
38
+ return password ? error.message.split(password).join('[redacted]') : error.message
39
+ }
40
+
41
+ export class OnboardingService {
42
+ constructor({ connect = createTransport, now = Date.now, maxAgeMs = 30 * 60 * 1000, ensureEditable = () => {} } = {}) {
43
+ this.connect = connect
44
+ this.now = now
45
+ this.maxAgeMs = maxAgeMs
46
+ this.drafts = new Map()
47
+ this.ensureEditable = ensureEditable
48
+ }
49
+
50
+ clear() { this.drafts.clear() }
51
+
52
+ get(id) {
53
+ const draft = this.drafts.get(id)
54
+ if (!draft || draft.expires <= this.now()) {
55
+ this.drafts.delete(id)
56
+ throw fail('This setup expired. Select the local folder again.', 404)
57
+ }
58
+ draft.expires = this.now() + this.maxAgeMs
59
+ return draft
60
+ }
61
+
62
+ view(draft) {
63
+ return {
64
+ id: draft.id, localPath: draft.localPath, label: draft.label,
65
+ projectId: draft.projectId, tested: draft.tested,
66
+ ...configurationView(draft)
67
+ }
68
+ }
69
+
70
+ load({ localPath, projectId } = {}) {
71
+ for (const [id, draft] of this.drafts) if (draft.expires <= this.now()) this.drafts.delete(id)
72
+ if (this.drafts.size >= 50) throw fail('Too many open setups. Close a setup and try again.', 429)
73
+ let project = projectId ? getProject(Number(projectId)) : null
74
+ if (projectId && !project) throw fail('Project not found', 404)
75
+ const folder = assertLocalFolder(project?.localPath || localPath)
76
+ project ||= getProjectByLocalPath(folder)
77
+ this.ensureEditable(project?.id)
78
+ const resolved = resolveEnv(project?.id, { localPath: folder, useEnvFileEnvironment: false })
79
+ if (resolved.sources.DEVSYNC_TRANSPORT === 'default') {
80
+ delete resolved.values.DEVSYNC_TRANSPORT
81
+ if (resolved.sources.DEVSYNC_PORT === 'default') delete resolved.values.DEVSYNC_PORT
82
+ }
83
+ const draft = {
84
+ ...resolved, id: crypto.randomUUID(), localPath: folder, projectId: project?.id || null,
85
+ label: project?.label || path.basename(folder) || 'project', tested: false,
86
+ expires: this.now() + this.maxAgeMs, busy: false
87
+ }
88
+ this.drafts.set(draft.id, draft)
89
+ return this.view(draft)
90
+ }
91
+
92
+ update(id, entries) {
93
+ const draft = this.get(id)
94
+ if (draft.busy) throw fail('Wait for the current setup operation to finish', 409)
95
+ if (!Array.isArray(entries)) throw fail('Settings entries are required')
96
+ const values = { ...draft.values }
97
+ const sources = { ...draft.sources }
98
+ for (const entry of entries) {
99
+ if (!entry || !ENV_SCHEMA.some((schema) => schema.key === entry.key)) throw fail('Unknown setting')
100
+ if (entry.value !== null && !['string', 'number', 'boolean'].includes(typeof entry.value)) throw fail('Invalid setting value')
101
+ let value = entry.value == null ? '' : String(entry.value)
102
+ if (value.length > 16384) throw fail('Setting value is too long')
103
+ if (!secretKeys.has(entry.key)) value = value.trim()
104
+ if (entry.key === 'DEVSYNC_PRIVATE_KEY' && value) {
105
+ value = value.startsWith('~/') || value.startsWith('~\\')
106
+ ? path.join(os.homedir(), value.slice(2)) : path.resolve(draft.localPath, value)
107
+ }
108
+ if (!value) delete values[entry.key]
109
+ else values[entry.key] = value
110
+ sources[entry.key] = entry.key === 'DEVSYNC_PORT' && !value ? 'default' : 'ui'
111
+ }
112
+ if (sources.DEVSYNC_PORT === 'default') values.DEVSYNC_PORT = defaultsFor(values.DEVSYNC_TRANSPORT).DEVSYNC_PORT
113
+ if (connectionKeys.some((key) => draft.values[key] !== values[key])) draft.tested = false
114
+ draft.values = values
115
+ draft.sources = sources
116
+ return this.view(draft)
117
+ }
118
+
119
+ async inspect(draft, remotePath) {
120
+ validateConnection(draft.values)
121
+ let transport
122
+ try {
123
+ transport = await this.connect(credsFromResolved(draft.values))
124
+ const entries = await transport.list(remotePath)
125
+ return entries.filter((entry) => entry.type === 'dir' && entry.name && !['.', '..'].includes(entry.name) && !/[\\/\x00-\x1f\x7f]/.test(entry.name))
126
+ .map((entry) => ({ name: entry.name, path: path.posix.join(remotePath, entry.name) }))
127
+ .sort((a, b) => a.name.localeCompare(b.name))
128
+ } catch (error) {
129
+ throw fail(safeConnectionError(error, draft.values), 502)
130
+ } finally {
131
+ if (transport) await transport.close()
132
+ }
133
+ }
134
+
135
+ async operation(id, action) {
136
+ const draft = this.get(id)
137
+ if (draft.busy) throw fail('Wait for the current setup operation to finish', 409)
138
+ draft.busy = true
139
+ try { return await action(draft) }
140
+ finally { draft.busy = false }
141
+ }
142
+
143
+ async test(id) {
144
+ return this.operation(id, async (draft) => {
145
+ draft.tested = false
146
+ await this.inspect(draft, '/')
147
+ draft.tested = true
148
+ return this.view(draft)
149
+ })
150
+ }
151
+
152
+ async browse(id, remotePath) {
153
+ return this.operation(id, async (draft) => {
154
+ if (!draft.tested) throw fail('Test the connection before choosing a server folder', 409)
155
+ const current = validateRemotePath(remotePath)
156
+ return { path: current, parent: current === '/' ? null : path.posix.dirname(current), entries: await this.inspect(draft, current) }
157
+ })
158
+ }
159
+
160
+ async save(id, label) {
161
+ return this.operation(id, async (draft) => {
162
+ this.ensureEditable(draft.projectId)
163
+ if (typeof label !== 'string' || !label.trim() || label.trim().length > 80 || /[\x00-\x1f\x7f]/.test(label)) throw fail('Enter a project name of 1–80 characters')
164
+ label = label.trim()
165
+ const duplicate = getProjectByLabel(label)
166
+ if (duplicate && duplicate.id !== draft.projectId) throw fail('That project name is already in use', 409)
167
+ const errors = ENV_SCHEMA.map((schema) => settingError(schema.key, draft.values[schema.key], draft.values)).filter(Boolean)
168
+ if (errors.length) throw fail(errors.join('; '))
169
+ if (!draft.tested) throw fail('Test the connection before saving', 409)
170
+ const remotePath = validateRemotePath(draft.values.DEVSYNC_REMOTE_PATH)
171
+ await this.inspect(draft, remotePath)
172
+ assertLocalFolder(draft.localPath)
173
+ this.ensureEditable(draft.projectId)
174
+ ensureDeployignore(draft.localPath)
175
+ let project = draft.projectId ? getProject(draft.projectId) : null
176
+ if (draft.projectId && !project) throw fail('Project was removed. Start setup again.', 404)
177
+ const created = !project
178
+ try {
179
+ project ||= createProject({ label, localPath: draft.localPath })
180
+ mutateProject(project.id, () => {
181
+ saveConfiguration(project.id, draft.values, { sources: draft.sources })
182
+ if (project.label !== label) updateProject(project.id, { label })
183
+ })
184
+ } catch (error) {
185
+ if (created && project) deleteProject(project.id)
186
+ throw error
187
+ }
188
+ this.drafts.delete(id)
189
+ return { id: project.id, label, localPath: draft.localPath, remotePath }
190
+ })
191
+ }
192
+
193
+ remove(id) {
194
+ const draft = this.get(id)
195
+ if (draft.busy) throw fail('Wait for the current setup operation to finish', 409)
196
+ this.drafts.delete(id)
197
+ }
198
+ }