Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

feat: add support for npm distribution and server management CLI

johaven4a5f8215d1ca
diff --git a/backend/src/configuration/config.loader.ts b/backend/src/configuration/config.loader.ts
index afec0f4e..a514a706 100644
--- a/backend/src/configuration/config.loader.ts
+++ b/backend/src/configuration/config.loader.ts
@@ -31,7 +31,7 @@ export function configLoader(): any {
throw new Error(`Missing configuration: "${ENVIRONMENT_FILE_NAME}" not found, or no variables beginning with "${ENVIRONMENT_PREFIX}" are set.`)
}
- if (!config.logger.stdout) {
+ if (config.logger.stdout === false) {
// ensure log directory exists
const logFilePath = config.logger.filePath || DEFAULT_LOG_FILE_PATH
const dirLogPath = path.dirname(logFilePath)
@@ -44,10 +44,19 @@ export function configLoader(): any {
return config
}
+function buildPathsUp(basePath: string, fileName: string, levels = 4): string[] {
+ // Generates candidate file paths, optionally walking up from __dirname to a given depth.
+ return Array.from({ length: levels + 1 }, (_, i) => path.resolve(basePath, ...Array(i).fill('..'), fileName))
+}
+
function loadEnvFile(envPath: string, envFileName: string, throwIfMissing = false): any {
- for (const ePath of [path.join(__dirname, `../../../${envPath}`), `./${envPath}`, envFileName]) {
- if (fs.existsSync(ePath) && fs.lstatSync(ePath).isFile()) {
- return yaml.load(fs.readFileSync(ePath, 'utf8'))
+ const candidates = [envPath, envFileName, ...buildPathsUp(__dirname, envPath), ...buildPathsUp(__dirname, envFileName)]
+ for (const envFilePath of candidates) {
+ if (fs.existsSync(envFilePath) && fs.lstatSync(envFilePath).isFile()) {
+ if (envFileName === ENVIRONMENT_FILE_NAME) {
+ console.log(`Load configuration → ${envFilePath}`)
+ }
+ return yaml.load(fs.readFileSync(envFilePath, 'utf8'))
}
}
if (throwIfMissing) {
diff --git a/backend/src/infrastructure/database/constants.ts b/backend/src/infrastructure/database/constants.ts
index 7663ca2b..26b74aca 100644
--- a/backend/src/infrastructure/database/constants.ts
+++ b/backend/src/infrastructure/database/constants.ts
@@ -9,5 +9,5 @@ import { IS_DEV_ENV } from '../../configuration/config.constants'
export const DB_CHARSET = 'utf8mb4'
export const DB_TOKEN_PROVIDER = 'DB'
-export const SCHEMA_PATH = path.join(__dirname, `./schema${IS_DEV_ENV ? '.ts' : '.js'}`)
-export const MIGRATIONS_PATH = './migrations'
+export const SCHEMA_PATH = path.join(__dirname, `schema${IS_DEV_ENV ? '.ts' : '.js'}`)
+export const MIGRATIONS_PATH = path.join(__dirname, '../../../migrations')
diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yaml
index 02de7d1a..50c4a7f3 100755
--- a/environment/environment.dist.yaml
+++ b/environment/environment.dist.yaml
@@ -17,7 +17,7 @@ logger:
stdout: true
# colorize output
colorize: true
- # file path where logs are written when stdout is false
+ # path to the log file used when stdout is set to false
filePath: /var/log/sync-in/server.log
mysql:
url: mysql://user:MySQLRootPassword@localhost:3306/database
diff --git a/package.json b/package.json
index 961e03ab..84fdb0e3 100755
--- a/package.json
+++ b/package.json
@@ -17,6 +17,7 @@
},
"license": "AGPL-3.0-or-later",
"private": true,
+ "os": ["!win32"],
"engineStrict": true,
"engines": {
"node": ">=22.15.0"
diff --git a/scripts/build/release.mjs b/scripts/build/release.mjs
index 1308b7dc..351cf628 100644
--- a/scripts/build/release.mjs
+++ b/scripts/build/release.mjs
@@ -1,23 +1,14 @@
#!/usr/bin/env node
-/*
- * Copyright (C) 2012-2025 Johan Legrand <[email protected]>
- * This file is part of Sync-in | The open source file sync and share solution
- * See the LICENSE file for licensing details
- */
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
-import { exec } from 'child_process'
+import { exec, execSync } from 'child_process'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const rootDir = path.resolve(__dirname, '../..')
const pathRelative = (curPath) => path.relative(rootDir, curPath)
-/* Packages JSON */
-const rootPKGPath = path.join(rootDir, 'package.json')
-const backendPKGPath = path.join(rootDir, 'backend', 'package.json')
-
/* Release */
const releaseDir = path.join(rootDir, 'release')
const releaseConf = {
@@ -34,7 +25,7 @@ const releaseConf = {
}
}
-// Check server build
+/* Check server build */
if (!fs.existsSync(releaseConf.server.src)) {
console.error(`❌ ${pathRelative(releaseConf.server.src)} directory does not exist. Have you run the build ?`)
process.exit(1)
@@ -46,7 +37,7 @@ for (const subDir of ['server', 'static']) {
}
}
-// Clean Up Release Directory
+/* Clean up release directory */
if (fs.existsSync(releaseDir)) {
try {
await fs.promises.rm(releaseDir, { recursive: true, force: true })
@@ -57,7 +48,7 @@ if (fs.existsSync(releaseDir)) {
}
}
-// Create Release Directory
+/* Create release directory */
try {
await fs.promises.mkdir(releaseDir, { recursive: true })
console.log(`✅ dir created: ${pathRelative(releaseDir)}`)
@@ -66,29 +57,49 @@ try {
process.exit(1)
}
-const [rootPkgRaw, backendPkgRaw] = await Promise.all([fs.promises.readFile(rootPKGPath, 'utf8'), fs.promises.readFile(backendPKGPath, 'utf8')])
-const rootPkg = JSON.parse(rootPkgRaw)
-const backendPkg = JSON.parse(backendPkgRaw)
+/* Create package.json */
+const rootPKGPath = path.join(rootDir, 'package.json')
+const rootPkg = JSON.parse(await fs.promises.readFile(rootPKGPath, 'utf8'))
+
+function extractDependencies() {
+ try {
+ const raw = execSync(`cd ${rootDir} && npm -w backend list --depth=0 --omit=dev --include=optional --json`, { encoding: 'utf8' })
+ const json = JSON.parse(raw)
+ const dependencies = Object.fromEntries(
+ Object.entries(json.dependencies[Object.keys(json.dependencies)[0]].dependencies).map((p) => [p[0], p[1].version])
+ )
+ const nbDeps = Object.keys(dependencies).length
+ if (nbDeps <= 3) {
+ throw new Error(`The number of dependencies seems incorrect : ${nbDeps}`)
+ }
+ console.error(`✅ extracted dependencies : ${nbDeps}`)
+ return dependencies
+ } catch (e) {
+ console.error(`❌ extract dependencies : ${e}`)
+ process.exit(1)
+ }
+}
const releasePKG = {
- name: rootPkg.name,
+ name: '@sync-in/server',
version: rootPkg.version,
description: rootPkg.description,
author: rootPkg.author,
- license: rootPkg.license,
homepage: rootPkg.homepage,
repository: rootPkg.repository,
bugs: rootPkg.bugs,
- os: ['!win32'],
+ license: rootPkg.license,
+ os: rootPkg.os,
+ engineStrict: rootPkg.engineStrict,
+ engines: rootPkg.engines,
keywords: rootPkg.keywords,
- bin: {
- 'sync-in-server': 'server/main.js'
+ publishConfig: {
+ access: 'public',
},
- scripts: {
- init_env: 'cp environment/environment.dist.min.yaml environment.yaml'
+ bin: {
+ 'sync-in-server': 'sync-in-server.js'
},
- dependencies: backendPkg.dependencies,
- optionalDependencies: backendPkg.optionalDependencies
+ dependencies: extractDependencies()
}
/* Move dist -> release/sync-in-server */
@@ -104,7 +115,7 @@ try {
const extraFiles = ['CHANGELOG.md', 'README.md', 'LICENSE']
for (const f of extraFiles) {
try {
- await fs.promises.copyFile(path.join(rootDir, f), path.join(releaseConf.server.dst, f))
+ await fs.promises.copyFile(path.join(rootDir, f), path.join(releaseConf.server.dst, path.basename(f)))
console.log(`✅ ${pathRelative(path.join(releaseConf.server.dst, f))} copied`)
} catch (e) {
console.error(`❌ ${pathRelative(path.join(releaseConf.server.dst, f))} not copied - ${e}`)
@@ -112,6 +123,28 @@ for (const f of extraFiles) {
}
}
+/* CLI: sync-in-server.js */
+const srcCLI = 'scripts/npm-sync-in-server.js'
+const dstCLIName = 'sync-in-server.js'
+try {
+ await fs.promises.copyFile(path.join(rootDir, srcCLI), path.join(releaseConf.server.dst, dstCLIName))
+ console.log(`✅ ${pathRelative(path.join(releaseConf.server.dst, dstCLIName))} copied`)
+} catch (e) {
+ console.error(`❌ ${pathRelative(path.join(releaseConf.server.dst, dstCLIName))} not copied - ${e}`)
+ process.exit(1)
+}
+
+/* Migrations directory */
+const migrationsDirName = 'migrations'
+const migrationsDirectory = path.join(rootDir, 'backend', migrationsDirName)
+try {
+ await fs.promises.cp(migrationsDirectory, path.join(releaseConf.server.dst, migrationsDirName), { recursive: true })
+ console.log(`✅ ${pathRelative(path.join(releaseConf.server.dst, migrationsDirName))} copied`)
+} catch (e) {
+ console.error(`❌ ${pathRelative(path.join(releaseConf.server.dst, migrationsDirName))} not copied - ${e}`)
+ process.exit(1)
+}
+
/* Environment files */
const environmentDir = 'environment'
const environmentFiles = ['environment.dist.min.yaml', 'environment.dist.yaml']
@@ -151,11 +184,8 @@ try {
process.exit(1)
}
-
try {
await Promise.all([
- exec(`cd ${releaseDir} && zip -r ${releaseConf.server.name}.zip ${releaseConf.server.name}`),
- exec(`cd ${releaseDir} && tar -czf ${releaseConf.server.name}.tar.gz ${releaseConf.server.name}`),
exec(`cd ${releaseDir} && zip -r ${releaseConf.docker.name}.zip ${releaseConf.docker.name}`),
exec(`cd ${releaseDir} && tar -czf ${releaseConf.docker.name}.tar.gz ${releaseConf.docker.name}`)
])
@@ -163,4 +193,4 @@ try {
} catch (e) {
console.error(`❌ release archives was not created : ${e}`)
process.exit(1)
-}
\ No newline at end of file
+}
diff --git a/scripts/npm-sync-in-server.js b/scripts/npm-sync-in-server.js
new file mode 100644
index 00000000..9db42b83
--- /dev/null
+++ b/scripts/npm-sync-in-server.js
@@ -0,0 +1,309 @@
+#!/usr/bin/env node
+
+/**
+ * sync-in-server.js - Command-line interface for:
+ * - Starting the server (with optional daemon mode)
+ * - Stopping the server
+ * - Checking server status
+ * - Displaying the server version
+ * - Running database migrations
+ * - Updating the server version
+ * - Displaying help information
+ */
+
+const [nodeMajorVersion] = process.versions.node.split('.').map((num) => parseInt(num, 10))
+const { spawn, spawnSync, exec } = require('child_process')
+const { promisify } = require('util')
+const path = require('path')
+const fs = require('fs')
+
+// Paths relative to this script
+const PKILL_GRACEFUL_TIMEOUT = 10000 // 10s timeout
+const ROOT_DIR = path.resolve(__dirname)
+const SERVER_ENTRY = path.join(ROOT_DIR, 'server', 'main.js')
+const ENV_DIST_FILE = path.join(ROOT_DIR, 'environment', 'environment.dist.yaml')
+const ENV_DIST_MIN_FILE = path.join(ROOT_DIR, 'environment', 'environment.dist.min.yaml')
+const USER_DIST_FILE = path.join(ROOT_DIR, '../../../environment.yaml')
+const PID_FILE = path.join(ROOT_DIR, 'server.pid')
+const LOG_FILE = path.join(ROOT_DIR, '../../../logs/server.log')
+const DB_CONF_FILE = path.join(ROOT_DIR, 'server', 'infrastructure', 'database', 'configuration.js')
+const CMD_DB_ARGS = ['drizzle-kit', 'migrate', `--config=${DB_CONF_FILE}`]
+
+function printHelp() {
+ console.log(`
+Usage: npx sync-in-server <command> [options]
+
+Available commands:
+ init Copy initial configuration into the server directory
+ start [-d] Start the server; use -d for daemon (detached) mode
+ stop Stop the server
+ status Show server status (daemon mode only)
+ version Show installed sync-in-server version
+ migrate-db Run database migrations
+ update Update the server version
+ help Show this help message
+
+Examples:
+ npx sync-in-server init # copy default environment.yaml
+ npx sync-in-server start # attached mode
+ npx sync-in-server start -d # daemon mode
+ npx sync-in-server version
+ npx sync-in-server help
+`)
+}
+
+function init() {
+ if (!fs.existsSync(ENV_DIST_MIN_FILE)) {
+ console.error(`❌ Default configuration not found at: ${ENV_DIST_MIN_FILE}`)
+ process.exit(1)
+ }
+ if (fs.existsSync(USER_DIST_FILE)) {
+ console.error(`❌ Configuration file already exists: ${USER_DIST_FILE}`)
+ process.exit(1)
+ }
+ try {
+ fs.copyFileSync(ENV_DIST_MIN_FILE, USER_DIST_FILE)
+ console.log(`✅ Default configuration has been copied to: ${USER_DIST_FILE}`)
+ console.log('⚠️ Remember to set your secrets before running the server.')
+ console.log(`ℹ️ For the full list of options: \n see ${ENV_DIST_FILE} \n or visit https://sync-in.com/docs/setup-guide/server`)
+ console.log(`ℹ️ For environment variable setup instructions, visit https://sync-in.com/docs/setup-guide/docker#during-execution`)
+ } catch (e) {
+ console.error(`❌ Unable to copy initial configuration: ${e}`)
+ process.exit(1)
+ }
+}
+
+function startServer(detached = false) {
+ if (!fs.existsSync(SERVER_ENTRY)) {
+ console.error(`❌ Sync-in Server entry point not found: ${SERVER_ENTRY}`)
+ process.exit(1)
+ }
+ if (statusServer(true)) {
+ console.log('⚠️ Use \x1b[1mnpx sync-in-server stop\x1b[0m to stop it')
+ process.exit(0)
+ }
+ try {
+ if (detached) {
+ console.log('🚀 Starting Sync-in Server in daemon mode...')
+ const env = {
+ ...{
+ SYNCIN_LOGGER_STDOUT: false,
+ SYNCIN_LOGGER_COLORIZE: false,
+ SYNCIN_LOGGER_FILEPATH: LOG_FILE
+ },
+ ...process.env
+ }
+ const child = spawn('node', [SERVER_ENTRY], { detached: true, stdio: 'ignore', env: env })
+ child.unref()
+ fs.writeFileSync(PID_FILE, String(child.pid))
+ console.log(`✅ Sync-in Server started with PID ${child.pid}`)
+ console.log(`📝 Logging to file → ${env.SYNCIN_LOGGER_FILEPATH}`)
+ process.exit(0)
+ } else {
+ console.log('🚀 Starting Sync-in Server attached...')
+ const child = spawn('node', [SERVER_ENTRY], { stdio: 'inherit' })
+ // forward exit code
+ child.on('exit', (code) => process.exit(code))
+ }
+ } catch (e) {
+ console.error(`❌ Sync-in Server failed to start: ${e}`)
+ process.exit(1)
+ }
+}
+
+async function stopServer() {
+ if (!fs.existsSync(PID_FILE)) {
+ console.error('❌ PID file not found. Is the server running?')
+ process.exit(1)
+ }
+ const pid = parseInt(fs.readFileSync(PID_FILE, 'utf-8'), 10)
+ if (isNaN(pid)) {
+ console.error(`❌ Invalid PID in file: ${PID_FILE}`)
+ process.exit(1)
+ }
+ try {
+ // Send SIGTERM
+ process.kill(pid, 'SIGTERM')
+ console.log(`🛑 Sent SIGTERM to process ${pid}, waiting for graceful shutdown...`)
+
+ // Wait for process to exit (poll every 100ms)
+ const success = await waitForProcessExit(pid)
+ if (!success) {
+ console.error(`⏱️ Process ${pid} did not exit after ${PKILL_GRACEFUL_TIMEOUT}ms`)
+ process.exit(1)
+ }
+ fs.unlinkSync(PID_FILE)
+ console.log(`✅ Sync-in Server process ${pid} stopped and PID file removed.`)
+ } catch (e) {
+ if (e.code === 'ESRCH') {
+ console.warn(`⚠️ Process ${pid} not found. Removing stale PID file.`)
+ fs.unlinkSync(PID_FILE)
+ return
+ }
+ console.error(`❌ Failed to stop process ${pid}: ${e}`)
+ process.exit(1)
+ }
+}
+
+function statusServer(returnStatus = false) {
+ if (!fs.existsSync(PID_FILE)) {
+ if (returnStatus) return false
+ console.log('ℹ️ Sync-in Server is not running (no PID file).')
+ process.exit(1)
+ }
+
+ const pid = parseInt(fs.readFileSync(PID_FILE, 'utf-8'), 10)
+ if (isNaN(pid)) {
+ if (returnStatus) return false
+ console.error(`❌ Invalid PID in ${PID_FILE}`)
+ process.exit(1)
+ }
+
+ try {
+ // signal 0 does not kill the process; it only checks if it exists
+ process.kill(pid, 0)
+ console.log(`✅ Sync-in Server is running (PID ${pid}).`)
+ if (returnStatus) return true
+ process.exit(0)
+ } catch (err) {
+ if (returnStatus) return false
+ if (err.code === 'ESRCH') {
+ console.log(`⚠️ No process found at PID ${pid}. Cleaning up stale PID file.`)
+ fs.unlinkSync(PID_FILE)
+ process.exit(1)
+ } else if (err.code === 'EPERM') {
+ console.log(`✅ Sync-in Server is running, but no permission to signal PID ${pid}.`)
+ process.exit(0)
+ } else {
+ console.error(`❌ Error checking status of PID ${pid}:`, err.message)
+ process.exit(1)
+ }
+ }
+}
+
+function showVersion() {
+ const pkgJson = getPackageJson()
+ console.log(`🔖 Sync-in Server version: ${pkgJson.version}`)
+}
+
+function migrateDatabase() {
+ console.log('🗄️ Running database migrations...')
+ const result = spawnSync('npx', CMD_DB_ARGS, { stdio: 'inherit' })
+ if (result.status !== 0) {
+ console.error('❌ Database migrations failed. Please verify database connectivity and credentials (stdout error case).')
+ process.exit(result.status)
+ }
+ console.log('✅ Database migrations completed successfully.')
+}
+
+async function updateVersion() {
+ const currentPackage = getPackageJson()
+ let latestVersion
+ console.log('📡 Checking Sync-in Server version...')
+ try {
+ const execAsync = promisify(exec)
+ const { stdout, stderr } = await execAsync(`npm view ${currentPackage.name} version`)
+ // npm sometimes writes warnings to stderr
+ if (stderr) console.warn(`⚠️ Warnings: ${stderr}`)
+ latestVersion = stdout.trim()
+ if (currentPackage.version === latestVersion) {
+ console.log('✅ Sync-in Server is up to date.')
+ process.exit(0)
+ }
+ } catch (e) {
+ console.error(`❌ Unable to check version: ${e.stderr || e.message}`)
+ process.exit(1)
+ }
+ console.log(`🔄 Updating Sync-in Server ${currentPackage.version} to ${latestVersion} ...`)
+ const result = spawnSync('npm', ['update', currentPackage.name], { stdio: 'inherit' })
+ if (result.status !== 0) {
+ console.error('❌ Failed to update Sync-in Server.')
+ process.exit(result.status)
+ }
+ migrateDatabase()
+ console.log('✅ Sync-in Server updated.')
+}
+
+function getPackageJson() {
+ try {
+ const pkgPath = path.join(ROOT_DIR, 'package.json')
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
+ } catch (e) {
+ console.error(`❌ Unable to parse ${path.join(ROOT_DIR, 'package.json')} : ${e}`)
+ process.exit(1)
+ }
+}
+
+function waitForProcessExit(pid) {
+ const interval = 500
+ let waited = 0
+
+ return new Promise((resolve) => {
+ const timer = setInterval(() => {
+ try {
+ process.kill(pid, 0) // does not kill, just checks existence
+ waited += interval
+ if (waited >= PKILL_GRACEFUL_TIMEOUT) {
+ clearInterval(timer)
+ resolve(false)
+ }
+ } catch (e) {
+ if (e.code === 'ESRCH') {
+ clearInterval(timer)
+ resolve(true) // process is gone
+ } else {
+ clearInterval(timer)
+ resolve(false) // some unexpected error
+ }
+ }
+ }, interval)
+ })
+}
+
+;(function main() {
+ // Ensure Nodejs.version
+ if (nodeMajorVersion < 22) {
+ console.error(`❌ Sync-in Server requires Node.js >= 22.x. Detected version: ${process.versions.node}`)
+ process.exit(1)
+ }
+ // Ensure CLI isn’t run on Windows
+ if (process.platform === 'win32') {
+ console.error('❌ Sync-in Server is not supported on Windows')
+ process.exit(1)
+ }
+ const args = process.argv.slice(2)
+ const command = args[0]
+
+ switch (command) {
+ case 'init':
+ init()
+ break
+ case 'start':
+ const detached = args.includes('-d') || args.includes('--daemon')
+ startServer(detached)
+ break
+ case 'stop':
+ stopServer().catch(console.error)
+ break
+ case 'status':
+ statusServer()
+ break
+ case 'version':
+ showVersion()
+ break
+ case 'migrate-db':
+ migrateDatabase()
+ break
+ case 'update':
+ updateVersion().catch(console.error)
+ break
+ case 'help':
+ case undefined:
+ printHelp()
+ break
+ default:
+ console.error(`Unknown command: ${command}`)
+ printHelp()
+ process.exit(1)
+ }
+})()