77 isUnresolvedShellReference ,
88 readStateDirDotEnvFromStateDir ,
99} from "../config/state-dir-dotenv.js" ;
10+ import { hasErrnoCode } from "../infra/errors.js" ;
1011import { resolveGatewayServiceDescription } from "./constants.js" ;
1112import { formatLine , writeFormattedLines } from "./output.js" ;
1213import {
@@ -121,7 +122,7 @@ function sanitizeSystemdUnitBackupContent(params: {
121122 // Backups should not retain file-managed secrets that OpenClaw moved into the
122123 // generated EnvironmentFile during this rewrite.
123124 const sanitizedLines : string [ ] = [ ] ;
124- for ( const rawLine of params . content . split ( "\n" ) ) {
125+ for ( const rawLine of params . content . replace ( / \\ \r ? \n \s * / gu , " " ) . split ( "\n" ) ) {
125126 const line = rawLine . trim ( ) ;
126127 if ( ! line . startsWith ( "Environment=" ) ) {
127128 sanitizedLines . push ( rawLine ) ;
@@ -153,6 +154,11 @@ function sanitizeSystemdUnitBackupContent(params: {
153154 return sanitizedLines . join ( "\n" ) ;
154155}
155156
157+ const SYSTEMD_MANAGED_CREDENTIAL_KEYS = normalizeServiceEnvKeys ( [
158+ "OPENCLAW_GATEWAY_TOKEN" ,
159+ "OPENCLAW_GATEWAY_PASSWORD" ,
160+ ] ) ;
161+
156162async function writeSystemdUnit ( {
157163 env,
158164 programArguments,
@@ -169,7 +175,7 @@ async function writeSystemdUnit({
169175 resolveManagedGatewayServiceCommand ( await readSystemdServiceExecStart ( env ) ) ?. environment ,
170176 ) ;
171177 await fs . mkdir ( path . dirname ( unitPath ) , { recursive : true } ) ;
172- await assertSystemdManagedPathIsNotSymlink ( unitPath ) ;
178+ await assertSystemdManagedPathIsRegularOrMissing ( unitPath ) ;
173179 const fileManagedKeys = collectSystemdFileManagedKeys ( {
174180 environmentValueSources,
175181 } ) ;
@@ -179,17 +185,22 @@ async function writeSystemdUnit({
179185 try {
180186 const backupPath = `${ unitPath } .bak` ;
181187 const existingUnit = await fs . readFile ( unitPath , "utf8" ) ;
182- const existingStat = await fs . stat ( unitPath ) ;
183- const backupMode = existingStat . mode & 0o777 || 0o600 ;
188+ await assertSystemdManagedPathIsRegularOrMissing ( backupPath ) ;
184189 const backupUnit = sanitizeSystemdUnitBackupContent ( {
185190 content : existingUnit ,
186- fileManagedKeys,
191+ fileManagedKeys : normalizeServiceEnvKeys ( [
192+ ...fileManagedKeys ,
193+ ...priorManagedKeys ,
194+ ...readManagedServiceEnvKeysFromEnvironment ( environment ) ,
195+ ...SYSTEMD_MANAGED_CREDENTIAL_KEYS ,
196+ ] ) ,
187197 } ) ;
188- await fs . writeFile ( backupPath , backupUnit , { encoding : "utf8" , mode : backupMode } ) ;
189- await fs . chmod ( backupPath , backupMode ) ;
198+ await publishSystemdPrivateFile ( backupPath , backupUnit ) ;
190199 backedUp = true ;
191- } catch {
192- // File does not exist yet — nothing to back up.
200+ } catch ( error ) {
201+ if ( ! hasErrnoCode ( error , "ENOENT" ) ) {
202+ throw error ;
203+ }
193204 }
194205
195206 const serviceDescription = resolveGatewayServiceDescription ( { env, description } ) ;
@@ -281,18 +292,58 @@ async function writeSystemdUnit({
281292
282293type SystemdFileSnapshot = { contents : Buffer ; mode : number } | null ;
283294
284- async function assertSystemdManagedPathIsNotSymlink ( filePath : string ) : Promise < void > {
295+ async function assertSystemdManagedPathIsRegularOrMissing ( filePath : string ) : Promise < boolean > {
285296 try {
286297 const stat = await fs . lstat ( filePath ) ;
287298 if ( stat . isSymbolicLink ( ) ) {
288299 throw new Error ( `Refusing to rewrite symlinked managed systemd file: ${ filePath } ` ) ;
289300 }
301+ if (
302+ stat . isDirectory ( ) ||
303+ stat . isBlockDevice ( ) ||
304+ stat . isCharacterDevice ( ) ||
305+ stat . isFIFO ( ) ||
306+ stat . isSocket ( )
307+ ) {
308+ throw new Error ( `Refusing to rewrite non-regular managed systemd file: ${ filePath } ` ) ;
309+ }
290310 } catch ( error ) {
291- if ( ( error as NodeJS . ErrnoException ) . code === "ENOENT" ) {
292- return ;
311+ if ( hasErrnoCode ( error , "ENOENT" ) ) {
312+ return false ;
293313 }
294314 throw error ;
295315 }
316+ return true ;
317+ }
318+
319+ async function publishSystemdPrivateFile ( filePath : string , contents : string ) : Promise < void > {
320+ const temporaryPath = `${ filePath } .openclaw-${ randomUUID ( ) } .tmp` ;
321+ try {
322+ await fs . writeFile ( temporaryPath , contents , { encoding : "utf8" , flag : "wx" , mode : 0o600 } ) ;
323+ await fs . chmod ( temporaryPath , 0o600 ) ;
324+ await fs . rename ( temporaryPath , filePath ) ;
325+ } finally {
326+ await fs . unlink ( temporaryPath ) . catch ( ( ) => undefined ) ;
327+ }
328+ }
329+
330+ export async function removeSystemdUnitArtifacts ( unitPath : string ) : Promise < boolean > {
331+ // The generated unit and its recovery copy share one lifecycle. Validate both
332+ // before unlinking either so an unexpected artifact cannot cause partial cleanup.
333+ const backupPath = `${ unitPath } .bak` ;
334+ const unitExists = await assertSystemdManagedPathIsRegularOrMissing ( unitPath ) ;
335+ if ( await assertSystemdManagedPathIsRegularOrMissing ( backupPath ) ) {
336+ await fs . unlink ( backupPath ) ;
337+ }
338+ if ( unitExists ) {
339+ await fs . unlink ( unitPath ) ;
340+ }
341+ return unitExists ;
342+ }
343+
344+ export async function assertSystemdUnitArtifactsRemovable ( unitPath : string ) : Promise < void > {
345+ await assertSystemdManagedPathIsRegularOrMissing ( unitPath ) ;
346+ await assertSystemdManagedPathIsRegularOrMissing ( `${ unitPath } .bak` ) ;
296347}
297348
298349async function readSystemdFileSnapshot ( filePath : string ) : Promise < SystemdFileSnapshot > {
@@ -481,11 +532,10 @@ async function removeNodeSystemdManagedEnvironmentKeys(env: GatewayServiceEnv):
481532 } catch {
482533 return ;
483534 }
484- const managedKeys = new Set ( [ "OPENCLAW_GATEWAY_TOKEN" , "OPENCLAW_GATEWAY_PASSWORD" ] ) ;
485535 const remaining = Object . fromEntries (
486536 Object . entries ( existingFile . environment ) . filter ( ( [ key , value ] ) => {
487537 const normalized = normalizeServiceEnvKey ( key ) ;
488- if ( normalized && managedKeys . has ( normalized ) ) {
538+ if ( normalized && SYSTEMD_MANAGED_CREDENTIAL_KEYS . has ( normalized ) ) {
489539 return false ;
490540 }
491541 return existingFile . literalShellReferenceKeys . has ( key ) || ! isUnresolvedShellReference ( value ) ;
@@ -616,19 +666,10 @@ export async function uninstallSystemdService({
616666 await assertSystemdAvailable ( env ) ;
617667 const serviceName = resolveSystemdServiceName ( env ) ;
618668 const unitName = `${ serviceName } .service` ;
619- await disableSystemdUserUnitForRemoval ( env , unitName ) ;
620-
621669 const unitPath = resolveSystemdUnitPath ( env ) ;
622- let removed = false ;
623- try {
624- await fs . unlink ( unitPath ) ;
625- removed = true ;
626- } catch ( error ) {
627- if ( ( error as NodeJS . ErrnoException ) . code !== "ENOENT" ) {
628- throw error ;
629- }
630- // Unit file was already absent; still clean generated node env state below.
631- }
670+ await assertSystemdUnitArtifactsRemovable ( unitPath ) ;
671+ await disableSystemdUserUnitForRemoval ( env , unitName ) ;
672+ const removed = await removeSystemdUnitArtifacts ( unitPath ) ;
632673 await removeNodeSystemdManagedEnvironmentKeys ( env ) ;
633674 if ( removed ) {
634675 stdout . write ( `${ formatLine ( "Removed systemd service" , unitPath ) } \n` ) ;
0 commit comments